Python中的OpenCV无法扫描像素

Mar*_* L. 1 python opencv pixels

我遇到了 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  
Run Code Online (Sandbox Code Playgroud)

当输入是 RGB 图像时,循环(扫描给定图像的每个像素)效果很好……但如果输入是单通道图像,我会收到此错误:

for j in range( width ):
TypeError: Nested sequences should have 2 or 3 dimensions
Run Code Online (Sandbox Code Playgroud)

输入的单通道图像(在下一个示例中称为“rg”)取自称为“src”的 RGB 图像,使用 cvSplit 然后 cvAbsDiff

cvSplit( src, r, g, b, 'NULL' )
rg = cvCreateImage( cvGetSize(src), src.depth, 1 ) # R - G
cvAbsDiff( r, g, rg )
Run Code Online (Sandbox Code Playgroud)

我也已经注意到问题来自从 cvSplit 得到的差异图像......

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

Abh*_*ood 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
Run Code Online (Sandbox Code Playgroud)

希望您觉得这个有帮助。