item() 函数在访问像素值时如何工作?

我正在阅读 OpenCV python 教程,他们说 NumPy 数组函数 item() 是访问图像中像素值的最佳方式,但我不明白它的作用。


import cv2

import numpy as np


img = cv2.imread('image.jpg')


print(img.item(10, 10, 2)) # I don't know what the item() function does/what it's parameters are



喵喔喔
浏览 232回答 1
1回答

繁华开满天机

来自文档:numpy.ndarray.item()将数组的一个元素复制到标准 Python 标量并返回它。换句话说,调用img.item(i)会为您获取i数组中索引表示的值的副本,类似于img[i]但不同之处在于它将它作为 Python 标量而不是数组返回。按照文档,获取 Python 标量有助于加快对数组元素的访问,并利用 Python 的优化数学对值进行算术运算。一个例子:>>> x = np.random.randint(9, size=(3, 3))>>> xarray([[1, 8, 4],&nbsp; &nbsp; &nbsp; [8, 7, 5],&nbsp; &nbsp; &nbsp; [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 cv2import numpy as npimg = cv2.imread('image.jpg')img[0, 0] = 255 # Setting a single pixelpx = img[0, 0]&nbsp; # Getting a single pixel做:img.itemset((0, 0), 255)px = img.item((0, 0))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python