【发布时间】: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