Counting the number of black pixels in an image in Python with OpenCV

I have the following test code in Python for reading, threshold, and displaying an image:

import cv2 import numpy as np from matplotlib import pyplot as plt # read image img = cv2.imread('slice-309.png',0) ret,thresh = cv2.threshold(img,0,230, cv2.THRESH_BINARY) height, width = img.shape print "height and width : ",height, width size = img.size print "size of the image in number of pixels", size # plot the binary image imgplot = plt.imshow(img, 'gray') plt.show() 

I would like to count the number of pixels inside an image with a specific label, for example, black. How can i do this? I looked at OpenCV tutorials, but did not find any help: - (

Thanks!

+6
source share
2 answers

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) 
+9
source
 import cv2 image = cv2.imread("pathtoimg", 0) count = cv2.countNonZero(image) print(count) 
0
source

All Articles