1

对于 numpy 中的 RGB 图像,cv::MatIterator 的等价物是什么?我读过,numpy.nditer但我无法准确地使用它来制定我的要求。

例如,考虑以下使用 OpenCV 迭代每个像素并分配 RGB 值的 C++ 代码:

cv::Mat rgbImage(someheight, somewidth, CV_8UC3);
cv::MatIterator_<cv::Vec3b> first = rgbImage.begin<cv::Vec3b>()
cv::MatIterator_<cv::Vec3b> last = rgbImage.end<cv::Vec3b>()

while (first!=last){
    *first = (get <cv::Vec3b> value from somewhere)
    ++first;
}

在上面的代码中,MatIteratorfirst用于直接在图像中的每个像素处分配 cv::Vec3b 类型的 (R,G,B) 值。

考虑到下面的 Python 代码,

rgbImage = np.zeros((someheight, somewidth, 3), dtype = np.uint8)
first= np.nditer(rgbImage)
while not first.finished():
     ???

有人可以提供一个示例,说明直接分配 (R,G,B) 值的元组的等效 numpy 版本可能是什么样的?谢谢!

4

1 回答 1

0

遍历数组的一种简单方法是使用np.ndenumerate一个 for 循环,然后您可以在其中修改图像,这是一个如何使用它的示例:

import numpy as np

# generate a random numpy array as loaded from cv2.imread()
img = np.random.randint(255, size=(8, 10, 3))

for (x,y,z), value in np.ndenumerate(img):
    do_something(img[x,y,z]) # modify to do whatever you want

请记住,OpenCV 使用 BGR 而不是 RGB。因此,如果您想将洋红色 (BGR=(255,0,255)) 分配给尺寸为 3x4 的黑色图像中的像素 (x=1, y=2),您将执行以下操作:

>>> import numpy as np

>>> img = np.zeros((3, 4, 3), dtype = np.uint8)

>>> for (x,y), value in np.ndenumerate(img[:,:,0]):
>>>     if x == 1 and y == 2:
>>>         img[x,y,:] = (255,0,255)    
>>> print img
[[[  0   0   0]
  [  0   0   0]
  [  0   0   0]
  [  0   0   0]]

 [[  0   0   0]
  [  0   0   0]
  [255   0 255]
  [  0   0   0]]

 [[  0   0   0]
  [  0   0   0]
  [  0   0   0]
  [  0   0   0]]]
于 2013-08-20T08:42:25.827 回答