count number of black pixels in an image in Python with OpenCV

import cv2
image = cv2.imread("pathtoimg", 0)
count = cv2.countNonZero(image)
print(count)

For black images you get the total number of pixels (rows*cols) and then subtract it from the result you get from cv2.countNonZero(mat).

For other values, you can create a mask using cv2.inRange() to return a binary mask showing all the locations of the color/label/value you want and then use cv2.countNonZero to count how many of them there are.

UPDATE (Per Miki's comment):

When trying to find the count of elements with a particular value, Python allows you to skip the cv2.inRange() call and just do:

cv2.countNonZero(img == scalar_value)  

Tags:

Python

Opencv