如何计算两条线之间的距离?

2024-04-19 19:01:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在用Python计算图像中两行之间的距离。例如,在下面给出的图像中,我想找到黄色块两端之间的垂直距离。到目前为止,我只能得出两个像素之间的距离

Image of engine

我能做的代码是找到红色和蓝色像素之间的距离。我想我可以改进这一点,使两个点/线之间的距离在这张图片上,但没有运气

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)

Tags: from图像importnumpy距离npbluered
1条回答
网友
1楼 · 发布于 2024-04-19 19:01:34

在准备这个答案时,我意识到我关于^{}的暗示是误导性的。当然,我有^{}在我的脑海里-抱歉

然而,以下是完整的逐步方法:

  1. 使用^{}遮罩所有黄色像素。注意:您的图像存在JPG伪影,因此在遮罩中会产生大量噪声,参见输出:

Mask

  1. 使用^{}查找遮罩中的所有轮廓。那将超过50,因为有很多微小的人工制品

  2. 使用Python的^{}函数对已找到的轮廓(列表)使用^{}键获得最大轮廓

  3. 最后,使用^{}获得轮廓的边界矩形。这是一个元组(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
                    

相关问题 更多 >