Count total number of white pixels in an image


I am trying to count total number of white pixels in the following image:


But with my code, I get this error

src is not a numpy array, neither a scalar.

This is my code:

TP= width * height
white= TP - cv2.countNonZero(img[1])
print "Dimensions:", img.size, "Total pixels:", TP, "White", white


Notice that Image is capitalized…in PIL, Image is a class. The actual image data is one of the many properties inside the class, and PIL does not use numpy arrays. Thus, your image is not a numpy array. If you want to convert to a numpy array, simply encase the image as an array:

img = np.array(img)

If you read the image with OpenCV, then it already comes as a numpy array.

img = cv2.imread(filename)

Also note that the ordering of channels is different in PIL than OpenCV. In PIL, images are read as RGB order, while in OpenCV, they are in BGR order. So if you read with PIL but display with OpenCV, you’ll need to swap the channels before displaying.

Edit: also, check the OpenCV docs for countNonZero(). This function only works on single channel arrays, so you’ll need to either convert the image to grayscale, or decide how you want to count a zero. You can also just use numpy just by np.sum(img == 0) to count the number of zero values, or np.sum(img > 0) to count non-zero values. For a three channel array, this will count all the zeros in each channel independently. If you want to only include ones that are zero in all three colors, you can do a number of things—the simplest is probably to add all the channels together into one 2D array, and then do the same as above.

Edit2: also, your code right now is counting the number of black pixels, not white. countNonZero() will return the number of all pixels greater than 0. Then you subtract that off the total number of pixels…which will give you only the black pixels. If you just want to count the number of white pixels, np.sum(img == 255).

Edit3: So with your image, this code works fine:

import cv2
import numpy as np

img = cv2.imread('img.png', cv2.IMREAD_GRAYSCALE)
n_white_pix = np.sum(img == 255)
print('Number of white pixels:', n_white_pix)

Number of white pixels: 5

Note here that cv2.IMREAD_GRAYSCALE is just equal to 0, but this is more explicit.

Answered By – alkasm

Answer Checked By – Dawn Plyler (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.