简体   繁体   中英

Find Distance Between Points in Opencv

I have a code that allows me to open an image and click to add points on the picture and it shows me their coordinates as shown below:

演示

The coordinates are already being displayed. First xy coordinates: (131,133) Second: (28,242) Third: (99,328) Fourth: (111,321)...

I need to find the linear distance between 2 successive points. That is:

  1. Distance between Second and First coordinates,
  2. Distance between Third and Second coordinates,
  3. Distance between Fourth and Third coordinates, ...

Example: (131,133) & (28,242)

Distance using √[(x₂ - x₁)² + (y₂ - y₁)²].

Can someone help, please? Thanks!

Code:

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

You can create a function that accepts 2 points as parameters and returns the distance between them:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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