【发布时间】:2021-04-26 17:25:45
【问题描述】:
我一直在尝试在 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)
【问题讨论】:
-
欢迎来到 Stack Overflow!请使用tour 并阅读How to Ask。请edit 发布您自己的努力来解决这个问题。后者最好在代码中,这称为minimal reproducible example。
-
也许您可以添加第二张带注释的图像,准确显示您想要找到的内容,因为不太清楚“黄色块末端之间的垂直距离是什么意思,假设至少有 2 个或 5 个黄色块,并且您没有说明它需要垂直于什么。
-
@MarkSetchell 它只是中间的黄色大块
-
所以你想要最大的黄色矩形的高度?
-
@MarkSetchell 是的。高度和宽度。
标签: python numpy image-processing distance