For black images, you get the total number of pixels (lines * cols), and then subtract them from the result obtained from countNonZero(mat) .
For other values, you can create a mask using inRange() to return a binary mask displaying all the color / label / value locations you want, and then use countNonZero to count how many of them exist.
UPDATE (Per Miki comment):
When trying to find the number of elements with a specific value, Python allows you to skip the inRange() call and simply:
countNonZero(img == scalar_value)
source share