import cv2
import math
path = 'img02.png'
img = cv2.imread(path)
pointList = []
def mousepoints(event,x,y,flags,params):
if event == cv2.EVENT_LBUTTONDOWN:
cv2.circle(img,(x,y),5,(0,0,255),cv2.FILLED)
pointList.append([x,y])
print(pointList)
print(x,y)
while True:
cv2.imshow('img',img)
cv2.setMouseCallback('img',mousepoints)
if cv2.waitKey(1) & 0xFF == ord('q'):
pointList = []
img = cv2.imread(path)
角度的计算公式为
m1,m2为斜率,然后求角度
函数如下图所示
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)
angR = math.atan((m2 - m1) / (1 + (m2 * m1)))
angD = round(math.degrees(angR)) # 将弧度转化成角度,并且以整数输出
print(angD)
cv2.putText(img, str(angD), (pt1[0] - 40, pt1[1] - 20), cv2.FONT_HERSHEY_DUPLEX, 2, (255, 0, 0), 2)
测量出来有一些误差
import cv2
import math
path = 'img02.png'
img = cv2.imread(path)
pointList = []
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)
angR = math.atan((m2 - m1) / (1 + (m2 * m1)))
angD = round(math.degrees(angR)) # 将弧度转化成角度,并且以整数输出
print(angD)
cv2.putText(img, str(angD), (pt1[0] - 40, pt1[1] - 20), cv2.FONT_HERSHEY_DUPLEX, 2, (255, 0, 0), 2)
def mousepoints(event,x,y,flags,params):
if event == cv2.EVENT_LBUTTONDOWN:
size= len(pointList)
if size != 0 and size % 3 != 0:
cv2.line(img, tuple(pointList[round((size - 1) / 3) * 3]), (x, y), (0, 0, 225), 2)
cv2.circle(img,(x,y),5,(0,0,255),cv2.FILLED)
pointList.append([x,y])
# print(pointList)
# print(x,y)
while True:
if len(pointList) % 3 == 0 and len(pointList) != 0:
getAngle(pointList)
cv2.imshow('img',img)
cv2.setMouseCallback('img',mousepoints)
if cv2.waitKey(1) & 0xFF == ord('q'):
pointList = []
img = cv2.imread(path)