TypeError: ´numpy.uint8´ object is not iterable`

TypeError: ´numpy.uint8´ object is not iterable`

此代码会将我的 RGB 图像转换为 Black/White 并向我提供 RGB 值 - 应为 (0, 0, 0) 或 (255, 255, 255)。

import cv2
import numpy as np

template = cv2.imread('C:\colorbars.png')

gray = cv2.cvtColor(template, cv2.COLOR_RGB2GRAY)

gray = cv2.resize(gray,(640,480))
ret,gray = cv2.threshold(gray,120,255,0)
gray2 = gray.copy()
mask = np.zeros(gray.shape,np.uint8)

contours, hier = cv2.findContours(gray,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
    if 200<cv2.contourArea(cnt)<5000:
        cv2.drawContours(gray2,[cnt],0,(0,255,0),2)
        cv2.drawContours(mask,[cnt],0,(0,255,0),-1)
cv2.bitwise_not(gray2,gray2,mask)

y = 250
x = 200
r, g, b = gray2[y,x]

print r, g, b

如果我用 r, g, b = template[y,x] 行检查彩色图像的 RGB 值,它就会起作用;但是,一旦我想要 Black/White 图像的 RGB 值,就会出现以下错误消息:

File "C:\Python27\Lib\site-packages\myprogram.py", Line 22, in <module> r, g, b = gray2[y,x] TypeError: ´numpy.uint8´ object is not iterable

我认为这意味着数组中没有足够的对象,我认为问题出在从颜色到 B/W 的转换中。

你的 "gray" 变量是一个二维矩阵(因为灰度),所以当你要求 gray2[x,y] 时,它 returns 一个 8 位无符号整数 (np .unint8)对应[x,y]像素点的灰度值。

当您执行:r,g,b =gray2[x,y] 时,您期望有 3 个值(r、g、b),但 returns 只有 1 个,因此您会收到错误消息。

您应该准确地说明您正在尝试做什么,因为询问灰度图像的 RGB 值是没有意义的。

请尝试仅使用一个通道而不是三个通道来获取结果, 例如:r = gray2[x,y]