Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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('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 within the image with a certain label, for instance black. How can I do that ? I looked at tutorials of OpenCV but did not find any help :-(

Thanks!

like image 485
Aurélie JEAN Avatar asked Sep 15 '15 16:09

Aurélie JEAN


2 Answers

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)  
like image 98
Rick Smith Avatar answered Oct 23 '22 17:10

Rick Smith


import cv2
image = cv2.imread("pathtoimg", 0)
count = cv2.countNonZero(image)
print(count)
like image 22
Danny Avatar answered Oct 23 '22 17:10

Danny