首页 > 解决方案 > 如何找到numpy数组的中心点?

问题描述

我正在使用 PIL 和 numpy 检测绿色。由于代码即使在非绿色区域也能找到大量绿色像素。因此,我找到了与我指定的值最接近的值,我得到了一个提供 (1512L, 3L) 矩阵的 3 个匹配点。代码如下。结果,我想在原始图像上绘制这个矩阵来查看位置。我怎样才能做到这一点 ?示例图像也在下面。

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')

示例图像

标签: pythonnumpypython-imaging-library

解决方案


推荐阅读