【opencv-python角度测量】

第一步,输入图片,点击能获得图片中一点的坐标

效果如图
【opencv-python角度测量】_第1张图片
用鼠标的左点击事件

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)


第二步,如何计算角度?求斜率求角度

角度的计算公式为
【opencv-python角度测量】_第2张图片
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)


第三步,画出角度图片,画直线,标角度

测量出来有一些误差

【opencv-python角度测量】_第3张图片
全部代码

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)


你可能感兴趣的:(opencv,opencv,python,计算机视觉)