我一直在尝试用 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)
答案 0 :(得分:2)
在准备此答案时,我意识到我对 cv2.boxPoints
的暗示具有误导性。当然,我有cv2.boundingRect
- 抱歉!
尽管如此,以下是完整的分步方法:
cv2.inRange
屏蔽所有黄色像素。注意:您的图像具有 JPG 伪影,因此蒙版中会出现大量噪点,请参见。输出:使用 cv2.findContours
查找掩码中的所有轮廓。由于存在许多微小的文物,这将超过 50 个。
在(列表)找到的轮廓上使用 Python 的 max
函数,使用 cv2.contourArea
作为关键字以获得最大的轮廓。
最后用cv2.boundingRect
得到轮廓的边界矩形。那是一个元组 (x, y, widht, height)
。只需使用最后两个元素,即可获得所需信息。
那是我的代码:
import cv2
# Read image with OpenCV
img = cv2.imread('path/to/your/image.ext')
# Mask yellow color (0, 255, 255) in image; Attention: OpenCV uses BGR ordering
yellow_mask = cv2.inRange(img, (0, 255, 255), (0, 255, 255))
# Find contours in yellow mask w.r.t the OpenCV version
cnts = cv2.findContours(yellow_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
# Get the largest contour
cnt = max(cnts, key=cv2.contourArea)
# Get width and height from bounding rectangle of largest contour
(x, y, w, h) = cv2.boundingRect(cnt)
print('Width:', w, '| Height:', h)
输出
Width: 518 | Height: 320
看起来很合理。
----------------------------------------
System information
----------------------------------------
Platform: Windows-10-10.0.16299-SP0
Python: 3.8.5
OpenCV: 4.5.1
----------------------------------------