Skip to content Skip to sidebar Skip to footer

Count Number Of Black Pixels In An Image In Python With Opencv

I have the following test code in Python to read, threshold and display an image: import cv2 import numpy as np from matplotlib import pyplot as plt # read image img = cv2.imread

Solution 1:

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)  

Solution 2:

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

Post a Comment for "Count Number Of Black Pixels In An Image In Python With Opencv"