开发者

OpenCV in Python can't scan through pixels

I'm stuck with a problem of the python wrapper for OpenCv. I have this function that returns 1 if the number of black pixels is greater than treshold

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  

The loop (scan each pixel of a given image) works good when the input is an RGB image...but if the input is a single channel image I get this error:

for j in range( width ):
TypeError: Nested sequences should have 2 or 3 dimensions

The input single channel image (called 'rg' in the next example) is taken from an RGB image called 'src' processed with cvSplit and then cvAbsDiff

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

I've also already noticed that the problem comes from the difference image got from cvSplit...

Anyone can help me? Thank you


widthStep and imageData are no longer valid attributes for IplImage object. Thus, the correct way to loop through each pixel and grabbing its color value would be

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

Hope you find this useful.


What version of OpenCV and which Python wrapper are you using? I recommend using OpenCV 2.1 or 2.2 with the Python interface that comes with the library.

I also recommend that you avoid scanning pixels manually, and instead use the low-level functions provided by OpenCV (see the Operations on Arrays part of the OpenCV docs). That way will be less error-prone and much faster.

If you want to count the number of black pixels in a single-channel image or in a color image with the COI set (so that the color image is effectively treated as a single-channel one), you could use the function CountNonZero:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜