【问题标题】:Need to find a way to calculate the G pixel percentage需要想办法计算G像素百分比
【发布时间】:2020-12-15 04:39:09
【问题描述】:

我需要为一个项目计算给定图片中绿色像素的数量。

我已经找到了一种生成图像绿色部分的方法。只需要找到一种方法来计算给定图像的绿色百分比。以及如何将其循环用于图像目录?

这是我收集的代码。请帮我获取所选饱和区域百分比中的绿色像素。

 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)

【问题讨论】:

    标签: python image-processing python-imaging-library hsv


    【解决方案1】:

    下面的方法不是那么准确,但它做得很好。你可以找到完整的源代码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
    
    

    【讨论】:

    • 只是一个问题,我如何使用你的代码来计算饱和图片?
    • 正如我所说,它不是 100% 准确的。我使用这种方法来计算卫星图像的绿化百分比。饱和度几乎没有太大变化。因此它工作得很好。
    猜你喜欢
    • 2014-06-24
    • 2018-02-17
    • 1970-01-01
    • 2021-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-01
    • 2021-01-10
    相关资源
    最近更新 更多