-2

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
    You need to provide a lot more information than this snippet to get a meaningful answer. What format is this image in? What is "green"? How have you tried to actually solve the problem? – Mad Physicist Sep 12 '22 at 12:38
  • Use a mask to identify green regions [from here](https://stackoverflow.com/questions/47483951/how-to-define-a-threshold-value-to-detect-only-green-colour-objects-in-an-image). Next count the number of pixels in the resulting binary image – Jeru Luke Sep 12 '22 at 12:40

1 Answers1

1

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)))
Stefan
  • 36
  • 5