查找具有特定颜色的图像部分索引的最快方法

时间:2018-12-05 04:57:56

标签: python-3.x numpy opencv

如何最有效地找到距所需颜色L2距离的epsilon内的像素索引?

我可以做三个嵌套循环,但是我告诉我循环效率很低,也许可以使用矢量化解决方案。是否可以使用np.where或np.argwhere之类的东西来找到它?

1 个答案:

答案 0 :(得分:1)

您可以使用numpy计算与所需颜色之间的L2距离,然后使用np.where获取距离小于epsilon的像素的坐标。

img = np.zeros((400, 600, 3), dtype=np.uint8)
color = [255, 5, 31]    # desired color
epsilon = 10

# L2 distance from the desired color
distance_L2 = np.sqrt(np.sum((img.astype(int) - color)**2, 
axis=2))

# coordinates of the pixels that are within epsilon from the 
# desired color
y_coords, x_coords = np.where(distance_L2 < epsilon)