[英]Find Distance Between Points in Opencv
我有一個代碼可以讓我打開圖像並單擊以在圖片上添加點,它會顯示它們的坐標,如下所示:
坐標已經顯示。 第一個 xy 坐標:(131,133) 第二個:(28,242) 第三個:(99,328) 第四個:(111,321)...
我需要找到兩個連續點之間的直線距離。 那是:
示例:(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.