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))
添加回答
举报