类型错误:"numpy.uint8"对象不可迭代"



此代码应将我的RGB图像转换为黑/白,并为我提供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值,它可以工作;但是一旦我想获得黑/白图像的RGB值,就会出现以下错误消息:

File "C:Python27Libsite-packagesmyprogram.py", Line 22, in <module> r, g, b = gray2[y,x] TypeError: ´numpy.uint8´ object is not iterable

我假设这意味着数组中没有足够的对象,并且我认为问题出在从颜色到黑白的转换中的某个地方。

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

当你执行 : r,g,b

=gray2[x,y] 时,你期望 3 个值(r、g、b),但它只返回 1,所以你会得到一个错误。

您应该精确地执行操作,因为询问灰度图像的RGB值是没有意义的。

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

最新更新