在 Opencv 中查找点之间的距离

Find Distance Between Points in Opencv

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

坐标已经显示。 第一个 x-y 坐标:(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()

您可以创建一个接受 2 个点作为参数和 returns 它们之间的距离的函数:

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