Python中的OpenCV无法扫描像素

2024-10-01 02:40:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到了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时,循环(扫描给定图像的每个像素)工作良好 图像…但如果输入是单通道图像,则会出现以下错误:

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得到的不同图像。。。

有人能帮我吗? 谢谢你


Tags: in图像srcimgfordatasteprange
2条回答

widthStepimageData不再是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

希望你觉得这个有用。

您使用的是什么版本的OpenCV和哪个Python包装器?我建议在库附带的Python接口中使用OpenCV 2.1或2.2。

我还建议您避免手动扫描像素,而是使用OpenCV提供的低级函数(请参阅OpenCV文档的Operations on Arrays 部分)。这样就不容易出错,而且更快。

如果要计算单通道图像或具有COI集的彩色图像中的黑色像素数(以便将彩色图像有效地视为单通道图像),可以使用函数CountNonZero

def countBlackPixels(grayImg):
    (w,h) = cv.GetSize(grayImg)
    size = w * h
    return size - cv.CountNonZero(grayImg)

相关问题 更多 >