i have two lines that will be draw through mouse events and to find the angle between them like if i draw two parallel line the angle give me 0
What I have tried:
import numpy as np
import cv2
import math
btn_down = False
def get_points(im):
data = {}
data['im'] = im.copy()
data['lines'] = []
cv2.imshow("Image", im)
cv2.setMouseCallback("Image", mouse_handler,data)
cv2.waitKey(0)
points = np.uint16(data['lines'])
return points, data['im']
def mouse_handler(event, x, y, flags, data):
global btn_down
if event == cv2.EVENT_LBUTTONUP and btn_down:
btn_down = False
data['lines'][0].append((x, y))
cv2.circle(data['im'], (x, y), 3, (0, 0, 255),5)
cv2.line(data['im'], data['lines'][0][0], data['lines'][0][1], (0,0,255), 2)
cv2.imshow("Image", data['im'])
elif event == cv2.EVENT_MOUSEMOVE and btn_down:
image = data['im'].copy()
cv2.line(image, data['lines'][0][0], (x, y), (0,0,0), 1)
cv2.imshow("Image", image)
elif event == cv2.EVENT_LBUTTONDOWN:
btn_down = True
data['lines'].insert(0,[(x, y)])
cv2.circle(data['im'], (x, y), 3, (0, 0, 255), 5, 16)
cv2.imshow("Image", data['im'])
def gradient(pt1, pt2):
return (pt2[1] - pt1[1]) / (pt2[0] - pt1[0])
def getangle(pt1,pt2,pt3,pt4):
pt1,pt2,pt3,pt4 = data['im'][-4:]
print(f"point1: {pt1} \n point2: {pt2} \n point3 : {pt3}")
m1 = gradient(pt1, pt2)
m2 = gradient(pt1, pt3)
angR = math.atan((m2 - m1) / (1 + (m2 * m1)))
angD = math.degrees(angR)
cv2.putText(final_image, str(angD), (pt1[0] - 20, pt1[1] - 20), cv2.FONT_HERSHEY_COMPLEX,1, (0, 0, 255), 2)
print(f"angle: {angD} \n angleR: {angR}")
img = cv2.imread('2.jpg', 1)
pts, final_image = get_points(img)
while True:
if len(pts) % 4 == 0 and len(pts) != 0:
getangle( data['im'])
cv2.imshow('Image', final_image)
print(pts[-2:])
cv2.waitKey(0)