Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to Count the number of non zero pixels of the canny image in my python program

Tags:

python

opencv

I'm trying to find the number of non zero pixels of the canny image, could you help?

Here is my code:

import cv
def doCanny(input, lowThresh, highThresh, aperture):
    if input.nChannels != 1:
            return(0)
    out = cv.CreateImage((input.width, input.height), input.depth, 1)
    cv.Canny(input, out, lowThresh, highThresh, aperture)
    return out
def doPyrDown(input):
    assert(input.width !=0 and input.height !=0)
    out = cv.CreateImage((input.width/2, input.height/2), input.depth, input.nChannels)
    cv.PyrDown(input, out)
    return out

img = cv.LoadImage('mypic.jpg')
img2 = cv.CreateImage((img.width, img.height), img.depth, 1)
cv.CvtColor(img, img2, cv.CV_BGR2GRAY)
cv.NamedWindow("Example GRAY", cv.CV_WINDOW_AUTOSIZE)
cv.ShowImage("Example GRAY", img2)
img3 = doCanny(img2, 10, 100, 3)
img2 = doPyrDown(img3)
cv.ShowImage("Example 2", img2)
cv.WaitKey(0)
like image 383
Vicky Karan Avatar asked Mar 11 '15 07:03

Vicky Karan


People also ask

How do I count the number of pixels in an image in Python?

open(img); count = 0 for y in range(img. height): for x in range(img. width): pixel = img. getpixel((x, y)) if pixel >= 200: count += 1 print(count,"pixels are bright.

How do you count white pixels?

Counting PixelsNumPy provides a function sum() that returns the sum of all array elements in the NumPy array. This sum() function can be used to count the number of pixels on the basis of the required criteria.


2 Answers

You can use opencv's function countNonZero for counting the number of non-zero pixels in the image.

img3 = doCanny(img2, 10, 100, 3)
nzCount = cv.CountNonZero(img3);

Update:

In newer versions of OpenCV, the function to count non zeros has been updated as follows:

nzCount = cv2.countNonZero(img3)
like image 198
sgarizvi Avatar answered Sep 18 '22 18:09

sgarizvi


Try cv.countNonZero(), CountNonZero() doesn't work for me.

like image 39
Zhou Avatar answered Sep 18 '22 18:09

Zhou