为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

喵喔喔 2021-10-10 18:56:33
我正在阅读 OpenCV python 教程,他们说 NumPy 数组函数 item() 是访问图像中像素值的最佳方式,但我不明白它的作用。import cv2import numpy as npimg = cv2.imread('image.jpg')print(img.item(10, 10, 2)) # I don't know what the item() function does/what it's parameters are
查看完整描述

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))


查看完整回答
反对 回复 2021-10-10
  • 1 回答
  • 0 关注
  • 231 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号