我正在使用PIL和numpy检测绿色。由于该代码即使在非绿色区域中也会找到许多绿色像素。因此,我发现它们与我指定的值最接近,我得到3个匹配点,它们提供一个(1512L,3L)矩阵。代码如下。结果,我想将此矩阵绘制在原始图像上以查看位置。我怎样才能做到这一点 ?示例图片也在下面。
import numpy as np
from PIL import Image
# Open image and make RGB and HSV versions
RGBim = Image.open("AdjustedNewMaze3.jpg").convert('RGB')
HSVim = RGBim.convert('HSV')
# Make numpy versions
RGBna = np.array(RGBim)
HSVna = np.array(HSVim)
# Extract Hue
H = HSVna[:,:,0]
# Find all green pixels, i.e. where 100 < Hue < 140
lo,hi = 100,140
# Rescale to 0-255, rather than 0-360 because we are using uint8
lo = int((lo * 255) / 360)
hi = int((hi * 255) / 360)
green = np.where((H>lo) & (H<hi))
# Make all green pixels black in original image
RGBna[green] = [0,0,0]
def find_nearest(array, value):
array = np.asarray(array)
idx = (np.abs(array - value)).argmin()
return array[idx]
value = 120
green = find_nearest(RGBna, value)
average = np.average(green)
print(green)
count = green[0].size
print("Pixels matched: {}".format(count))
Image.fromarray(green).save('resultgreen.png')