Home > Blockchain >  Find Distance Between Points in Opencv
Find Distance Between Points in Opencv

Time:09-18

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:

demo

The coordinates are already being displayed. First x-y 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()

CodePudding user response:

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
    dis=abs(dis)   #removing negative sign.
    return dis

EDIT: 3rd line 'dis=abs(dis) ' dosen't change anything. Can be ignored

  • Related