我一直在用Python计算图像中两行之间的距离。例如,在下面给出的图像中,我想找到黄色块两端之间的垂直距离。到目前为止,我只能得出两个像素之间的距离
我能做的代码是找到红色和蓝色像素之间的距离。我想我可以改进这一点,使两个点/线之间的距离在这张图片上,但没有运气
import numpy as np
from PIL import Image
import math
# Load image and ensure RGB - just in case palettised
im = Image.open("2points.png").convert("RGB")
# Make numpy array from image
npimage = np.array(im)
# Describe what a single red pixel looks like
red = np.array([255,0,0],dtype=np.uint8)
# Find [x,y] coordinates of all red pixels
reds = np.where(np.all((npimage==red),axis=-1))
print(reds)
# Describe what a single blue pixel looks like
blue=np.array([0,0,255],dtype=np.uint8)
# Find [x,y] coordinates of all blue pixels
blues=np.where(np.all((npimage==blue),axis=-1))
print(blues)
dx2 = (blues[0][0]-reds[0][0])**2 # (200-10)^2
dy2 = (blues[1][0]-reds[1][0])**2 # (300-20)^2
distance = math.sqrt(dx2 + dy2)
print(distance)
在准备这个答案时,我意识到我关于^{} 的暗示是误导性的。当然,我有^{} 在我的脑海里-抱歉
然而,以下是完整的逐步方法:
使用^{} 查找遮罩中的所有轮廓。那将超过50,因为有很多微小的人工制品
使用Python的^{} 函数对已找到的轮廓(列表)使用^{} 键获得最大轮廓
最后,使用^{} 获得轮廓的边界矩形。这是一个元组
(x, y, widht, height)
。只需使用最后两个元素,就可以获得所需的信息这就是我的代码:
输出
看起来很合理
相关问题 更多 >
编程相关推荐