#导包
import cv2
import math
#图片路径
path = './jiaodu.jpg'
#读取图像
img = cv2.imread(path)
#存放点的列表,是二维的
pointsList = []
#利用鼠标左键画点
def mousePoints(event,x,y,flags,params):
#如果鼠标左键按下
if event == cv2.EVENT_LBUTTONDOWN:
#如果列表长度为2或3,划线将两点连起来
size = len(pointsList)
if size != 0 and size % 3 != 0:
cv2.line(img,tuple(pointsList[round((size-1)/3)*3]),(x,y),(0,0,255),2)
#在鼠标点击处画圆
cv2.circle(img,(x,y),5,(0,0,255),cv2.FILLED)
#将按下点的坐标添加到列表
pointsList.append([x,y])
#计算斜率
def gradient(pt1,pt2):
return (pt2[1]-pt1[1])/(pt2[0]-pt1[0])
#获取角度
def getAngle(pointsList):
#获取三个点的位置
pt1, pt2, pt3 = pointsList[-3:]
#计算两个点之间的斜率
m1 = gradient(pt1,pt2)
m2 = gradient(pt1,pt3)
#利用公式求角度:tanθ=∣(k2- k1)/(1+ k1k2)∣
angR = math.atan((m2-m1)/(1+(m2*m1)))
angD = round(math.degrees(angR))
#在图片上绘制角度
cv2.putText(img,str(angD),(pt1[0]-40,pt1[1]-20),cv2.FONT_HERSHEY_COMPLEX,
1.5,(0,0,255),2)
while True:
if len(pointsList) % 3 == 0 and len(pointsList) !=0:
getAngle(pointsList)
cv2.imshow('Image',img)
cv2.setMouseCallback('Image',mousePoints)
if cv2.waitKey(1) & 0xFF == ord('q'):
pointsList = []
img = cv2.imread(path)
**参考:**https://www.bilibili.com/video/BV18B4y1c7r4?p=5&vd_source=8073a87adf278a421274df509a29a81a