我遇到了OpenCv的python包装器的问题。我有一个函数,如果黑色像素的数量大于treshold,则返回1
def checkBlackPixels( img, threshold ):
width = img.width
height = img.height
nchannels = img.nChannels
step = img.widthStep
dimtot = width * height
data = img.imageData
black = 0
for i in range( 0, height ):
for j in range( 0, width ):
r = data[i*step + j*nchannels + 0]
g = data[i*step + j*nchannels + 1]
b = data[i*step + j*nchannels + 2]
if r == 0 and g == 0 and b == 0:
black = black + 1
if black >= threshold * dimtot:
return 1
else:
return 0 当输入是RGB image...but时,循环(扫描给定图像的每个像素)工作得很好,如果输入是单通道图像,我会得到这个错误:
for j in range( width ):
TypeError: Nested sequences should have 2 or 3 dimensions输入的单通道图像(在下一个示例中称为'rg‘)取自名为'src’的RGB图像,该图像先经过cvSplit处理,然后再经过cvAbsDiff处理
cvSplit( src, r, g, b, 'NULL' )
rg = cvCreateImage( cvGetSize(src), src.depth, 1 ) # R - G
cvAbsDiff( r, g, rg )我也已经注意到这个问题来自于从cvSplit得到的不同图像...
有人能帮我吗?谢谢
发布于 2011-01-15 11:49:49
你使用的是什么版本的OpenCV和哪个Python包装器?我推荐使用Python2.1或2.2以及库附带的OpenCV接口。
我还建议您避免手动扫描像素,而是使用OpenCV提供的低级函数(请参阅OpenCV文档的Operations on Arrays 部分)。这种方式不容易出错,而且速度快得多。
如果要计算单通道图像或设置了COI的彩色图像中黑色像素的数量(以便有效地将彩色图像视为单通道图像),可以使用函数CountNonZero
def countBlackPixels(grayImg):
(w,h) = cv.GetSize(grayImg)
size = w * h
return size - cv.CountNonZero(grayImg)发布于 2011-12-10 21:06:59
widthStep和imageData不再是IplImage对象的有效属性。因此,循环遍历每个像素并获取其颜色值的正确方法是
for i in range(0, height):
for j in range(0, width):
pixel_value = cv.Get2D(img, i, j)
# Since OpenCV loads color images in BGR, not RGB
b = pixel_value[0]
g = pixel_value[1]
r = pixel_value[2]
# cv.Set2D(result, i, j, value)
# ^ to store results of per-pixel
# operations at (i, j) in 'result' image希望这篇文章对你有用。
https://stackoverflow.com/questions/4695691
复制相似问题