让我们从测试图像开始。它是400x300像素的灰度(192),具有:
- 在20,10处有一个红色的3x3正方形,
- 蓝色的3x3正方形,位于300,200
现在执行以下 *** 作:
import numpy as npimport PILimport math# Load image and ensure RGB - just in case palettisedim=Image.open("a.png").convert("RGB")# Make numpy array from imagenpimage=np.array(im)# Describe what a single red pixel looks likered=np.array([255,0,0],dtype=np.uint8)# Find [x,y] coordinates of all red pixelsreds=np.where(np.all((npimage==red),axis=-1))
这给出:
(array([10, 10, 10, 11, 11, 11, 12, 12, 12]), array([20, 21, 22, 20, 21, 22, 20, 21, 22]))
现在让我们做蓝色像素:
# Describe what a single blue pixel looks likeblue=np.array([0,0,255],dtype=np.uint8)# Find [x,y] coordinates of all blue pixelsblues=np.where(np.all((npimage==blue),axis=-1))
这给出:
(array([200, 200, 200, 201, 201, 201, 202, 202, 202]), array([300, 301, 302, 300, 301, 302, 300, 301, 302]))
所以现在我们需要从第一个红色到第一个蓝色像素的距离
dx2 = (blues[0][0]-reds[0][0])**2 # (200-10)^2dy2 = (blues[1][0]-reds[1][0])**2 # (300-20)^2distance = math.sqrt(dx2 + dy2)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)