【问题标题】:Find Distance Between Points in Opencv在 Opencv 中查找点之间的距离
【发布时间】:2021-11-04 02:09:43
【问题描述】:

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

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

我需要找到 2 个连续点之间的线性距离。那就是:

  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()

【问题讨论】:

  • 你为什么不根据你显示的公式计算给定x,y值的距离?
  • 我需要创建一个循环,以我刚刚创建的当前点和上一个点来计算距离。
  • 如果您的问题是如何对列表中的连续点执行计算,为什么需要发布需要鼠标点击并将文本写入图像的代码。如果您创建了一个示例数组并尝试计算距离,那将会更加清晰。 minimal reproducible example 表示发布演示问题的最少代码,而不是您知道可以正常工作的之前的步骤。

标签: python image opencv image-processing


【解决方案1】:

您可以创建一个接受 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
    dis=abs(dis)   #removing negative sign.
    return dis

编辑: 第三行'dis=abs(dis)'并没有改变任何东西。可以忽略

【讨论】:

  • 如何创建以我刚刚创建的当前点和上一个点计算距离的循环?
  • 前一个是指左右点击创建的点之间的距离吗?
  • 你知道我点击图片时如何创建一个小圆圈吗?
  • geeksforgeeks.org/python-opencv-cv2-circle-method 尝试阅读 cv2 的文档以了解这些内容。他们用简单的解释直截了当。
  • 仔细想想,是的,我似乎误判了这一点。谢谢,已编辑。
猜你喜欢
  • 1970-01-01
  • 2019-09-16
  • 2012-06-20
  • 1970-01-01
  • 2023-01-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多