Skip to content Skip to sidebar Skip to footer

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, thr

Solution 1:

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 inrange(0, height):
    for j inrange(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.

Solution 2:

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)

Post a Comment for "Opencv In Python Can't Scan Through Pixels"