Need to find a way to calculate the G pixel percentage

Viewed 156

I need to calculate the amount of green pixels in a given picture for a project.

I already found a way to generate the green part of a image. Just need to find a way to calculate the green percentage of the given image. And how do you loop it for a image directory?

Here's the codes that I have gathered. Please help me to get the green pixel in the selected saturated area percentage.

 import cv2
    import numpy as np
    import matplotlib.pyplot as plt
    from PIL import Image
    import numpy as np

    img = cv2.imread('Image')

    grid_RGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    plt.figure(figsize=(20,8))
    dimensions = img.shape

    # height, width, number of channels in image
    height = img.shape[0]
    width = img.shape[1]
    channels = img.shape[2]
 
    print('Image Dimension    : ',dimensions)
    print('Image Height       : ',height)
    print('Image Width        : ',width)
    print('Number of Channels : ',channels)

    # area is calculated as “height x width” 
    area = height * width 
  
    # display the area 
    print("Area of the image is : ", area)

    plt.imshow(grid_RGB) # Printing the original picture after converting to RGB

   grid_HSV = cv2.cvtColor(grid_RGB, cv2.COLOR_RGB2HSV) # Converting to HSV
   lower_green = np.array([25,52,72])
   upper_green = np.array([102,255,255])

   mask= cv2.inRange(grid_HSV, lower_green, upper_green)
   res = cv2.bitwise_and(img, img, mask=mask) # Generating image with the green part

   print("Green Part of Image")
   plt.figure(figsize=(20,8))
   plt.imshow(res)


  # Load image and convert to HSV
  im = Image.open('.image').convert('HSV')

  # Extract Hue channel and make Numpy array for fast processing
  Hue = np.array(im.getchannel('H'))

  # Make mask of zeroes in which we will set greens to 1
  mask = np.zeros_like(Hue, dtype=np.uint8) 

  # Set all green pixels to 1
  mask[(Hue>80) & (Hue<90)] = 1 

  print(mask.mean()/100 * area/100)
  # Now print percentage of green pixels
  print((mask.mean()*100))
  print((mask.mean()*mask.size)/100)
1 Answers

The following method is not so accurate but it does the job quite well. You may find the entire source code here

green_pixel_count = 0
TOTAL_PIXELS = 1024 # Some dummy value 

# Find green pixel count for each sector
for i in img:
    for j in i:

        if(j[1]>j[0] and j[1]>j[2] and j[0]<100 and j[2]<100):
            green_pixel_count += 1

greenery_percentage = green_pixel_count*100/TOTAL_PIXELS

Related