Count green and white pixels in an image

Viewed 33

I need to count white and green pixels in an image. I have tried following code for calculating white and black pixels:

# importing libraries
import cv2
import numpy as np
  
# reading the image data from desired directory
img = cv2.imread("img_1.png")
cv2.imshow('Image',img)
  
# counting the number of pixels
number_of_white_pix = np.sum(img == 255)
number_of_black_pix = np.sum(img == 0)
  
print('Number of white pixels:', number_of_white_pix)
print('Number of black pixels:', number_of_black_pix)

How I can get green pixels count instead of black pixels using python code.

1 Answers

Your current analysis is not correct. Your data is loaded to be 3D: (height, width, number_of_channels). Here, the channels will be red, green, and blue.

Now, you are just counting all 255's in the 3D matrix, which may lead to a higher value than the number of pixels.

Depending on your needs, you may want to use:

# counting the number of pixels that have a value of 255 in the green channel
number_of_green_pix = np.sum(img[:,:,1] == 255)

You may use the where option in np.sum if you only want to find pixels that contain only green:

number_of_green_pix = np.sum(img[:,:,1] == 255, where=((img[:,:,0] == 0) & (img[:,:,2] == 0)))
#or
number_of_green_pix = np.sum(img[:,:,1] > 0, where=((img[:,:,0] == 0) & (img[:,:,2] == 0)))
Related