1

我遇到了 OpenCv 的 python 包装器的问题。如果黑色像素的数量大于阈值,我有这个函数返回 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 获得的差异图像......

任何人都可以帮助我吗?谢谢

4

2 回答 2

5

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

希望您觉得这个有帮助。

于 2011-12-10T13:06:59.157 回答
3

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

我还建议您避免手动扫描像素,而是使用 OpenCV 提供的低级函数(请参阅OpenCV 文档的数组操作部分)。这种方式将更不容易出错并且速度更快。

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

def countBlackPixels(grayImg):
    (w,h) = cv.GetSize(grayImg)
    size = w * h
    return size - cv.CountNonZero(grayImg)
于 2011-01-15T03:49:49.417 回答