繁体   English   中英

查找 Opencv 中点之间的距离

[英]Find Distance Between Points in Opencv

我有一个代码可以让我打开图像并单击以在图片上添加点,它会显示它们的坐标,如下所示:

演示

坐标已经显示。 第一个 xy 坐标:(131,133) 第二个:(28,242) 第三个:(99,328) 第四个:(111,321)...

我需要找到两个连续点之间的直线距离。 那是:

  1. 第二坐标和第一坐标之间的距离,
  2. 第三和第二坐标之间的距离,
  3. 第四和第三坐标之间的距离,...

示例:(131,133) & (28,242)

使用√[(x₂ - x₁)² + (y₂ - y₁)²] 的距离。

有人可以帮忙吗? 谢谢!

代码:

import cv2
[print(i) for i in dir(cv2) if 'EVENT' in i]

# importing the module
import cv2


# function to display the coordinates of
# of the points clicked on the image
def click_event(event, x, y, flags, params):
    # checking for left mouse clicks
    if event == cv2.EVENT_LBUTTONDOWN:
        # displaying the coordinates
        # on the Shell
        print(x, ' ', y)

        # displaying the coordinates
        # on the image window
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(img, str(x) + ',' +
                    str(y), (x, y), font,
                    1, (255, 0, 0), 2)
        cv2.imshow('image', img)

    # checking for right mouse clicks
    if event == cv2.EVENT_RBUTTONDOWN:
        # displaying the coordinates
        # on the Shell
        print(x, ' ', y)

        # displaying the coordinates
        # on the image window
        font = cv2.FONT_HERSHEY_SIMPLEX
        b = img[y, x, 0]
        g = img[y, x, 1]
        r = img[y, x, 2]
        cv2.putText(img, str(b) + ',' +
                    str(g) + ',' + str(r),
                    (x, y), font, 1,
                    (255, 255, 0), 2)
        cv2.imshow('image', img)


# driver function
if __name__ == "__main__":
    # reading the image
    img = cv2.imread('shirt.jpg', 1)
    img = cv2.resize(img, (0, 0), None, 0.2, 0.2)

    # displaying the image
    cv2.imshow('image', img)

    # setting mouse hadler for the image
    # and calling the click_event() function
    cv2.setMouseCallback('image', click_event)

    # wait for a key to be pressed to exit
    cv2.waitKey(0)

    # close the window
    cv2.destroyAllWindows()

您可以创建一个 function 接受 2 个点作为参数并返回它们之间的距离:

def distanceCalculate(p1, p2):
    """p1 and p2 in format (x1,y1) and (x2,y2) tuples"""
    dis = ((p2[0] - p1[0]) ** 2 + (p2[1] - p1[1]) ** 2) ** 0.5
    return dis

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM