需要找到一种计算G像素百分比的方法



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

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

这是我收集的代码。请帮助我获得所选饱和面积百分比中的绿色像素。

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)

下面的方法不太准确,但它做得很好。你可以在这里找到完整的源代码

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

最新更新