1 回答

TA貢獻1816條經驗 獲得超4個贊
來自文檔:numpy.ndarray.item()將數組的一個元素復制到標準 Python 標量并返回它。
換句話說,調用img.item(i)會為您獲取i數組中索引表示的值的副本,類似于img[i]但不同之處在于它將它作為 Python 標量而不是數組返回。按照文檔,獲取 Python 標量有助于加快對數組元素的訪問,并利用 Python 的優化數學對值進行算術運算。
一個例子:
>>> x = np.random.randint(9, size=(3, 3))
>>> x
array([[1, 8, 4],
[8, 7, 5],
[2, 1, 1]])
>>> x.item((1,0))
8
>>> x[1,0] # both calls seem to return the same value, but...
8
>>> type(x[1,0]) # Numpy's own int32
<class 'numpy.int32'>
>>> type(x.item((1,0))) # Python's standard int
<class 'int'>
item只接受一個參數 can None,它只適用于單項數組, an int_type,它的作用類似于平面索引,以及 a tupleof int_type,它被解釋為數組的多維索引。
回到您的具體問題,OpenCV 建議 item并itemset在使用單個像素值時,因為numpy已針對數組計算進行了優化,因此不鼓勵訪問單個項目。
所以,而不是做:
import cv2
import numpy as np
img = cv2.imread('image.jpg')
img[0, 0] = 255 # Setting a single pixel
px = img[0, 0] # Getting a single pixel
做:
img.itemset((0, 0), 255)
px = img.item((0, 0))
添加回答
舉報