OpenCV零基础实战项目2:测角

简述

主要任务:获取鼠标点击点的位置信息(第一个点是顶点),绘制两条线构成的夹角,计算夹角并显示出来。

其他功能:读取图片,展示图片,键入q清空坐标点,键入d销毁所有窗口。

资源

视频资源:
(强推)OpenCV实战项目

图片:角度识别

实现

1. 获取点位置信息并显示

读取并显示图片:imread(), imshow().
鼠标响应:setMousecallback()。

void setMousecallback(const string& winname, MouseCallback onMouse, void* userdata=0)
   winname:窗口的名字
   onMouse:鼠标响应函数,回调函数。指定窗口里每次鼠标时间发生的时候,被调用的函数指针。 这个函数的原型应该为void on_Mouse(int event, int x, int y, int flags, void* param);
   userdate:传给回调函数的参数 

它的参数函数有固定参数设置,可以自定义名称,这里定义为mousePoints()

void on_Mouse(int event, int x, int y, int flags, void* param);
event是 CV_EVENT_*变量之一
x和y是鼠标指针在图像坐标系的坐标(不是窗口坐标系) 
flags是CV_EVENT_FLAG的组合, param是用户定义的传递到setMouseCallback函数调用的参数。

我们通过自定义的函数mousePoints()绘制出点击的点(cv.circle()),并绘制出两条线。该函数具体如下:

def mousePoints(event, x, y, flags, params):
   if event == cv.EVENT_LBUTTONDOWN:
       cv.circle(img, (x,y), 5, (0,0,255), cv.FILLED)
       pointList.append([x,y])
       #print(pointList)
       #draw out the lines
       size = len(pointList)
       if size != 1 and (size-1) % 3 != 0:
           cv.line(img, tuple(pointList[round((size-2)/3)*3]), (x,y), (0,0,255), 2)

当按下左键时,获取x和y坐标绘制,并通过append()加入pointList。

以三点为一组,第一个点(顶点)作为point1,第二或第三点作为point2. 此处除以三取整(round()四舍五入)再乘三就可以取到这一组的第一个点。
例如该组三点序号为6,7,8. pointList加入点[8]时,size=9,(9-2)/3取整乘3为6. pointList加入点[9]时,size=10,(10-2)/3取整乘3为9,恰是下一组的第一个点。事实上,我们需要的顶点需要应该为0,3,6,9等3的整倍数序号点。

2. 计算夹角

公式:
夹角计算公式

当获取一组点(三个)以后,可以调用自定义的函数getAngle()计算夹角度数。获取最后三个点,调用自定义的gradient()函数计算两条线的斜率,根据公式得到角度并打印。具体代码如下:

def gradient(pt1, pt2):
   #(y2-y1)/(x2-x1)
   return (pt2[1]-pt1[1])/(pt2[0]-pt1[0])

def getAngle(pointList):
   pt1, pt2, pt3 = pointList[-3:]#the last 3 points
   m1 = gradient(pt1, pt2)
   m2 = gradient(pt1, pt3)
   angR = math.atan((m1-m2)/(1+m1*m2))
   angD = round(math.degrees(angR))
   
   cv.putText(img, str(angD), (pt1[0]-40, pt1[1]-20), cv.FONT_HERSHEY_COMPLEX, 
              1.5, (0,0,255), 2)

Math.atan()是arctan的计算,由正切值得到角度,再通过math.degrees()将弧度转化为角度。

3. 键入q清空坐标点,键入d销毁所有窗口

cv.waitkey(delay)在键入字符时返回一个对应的ASCII值,当它等于’q’时,清空pointList。当它等于’d’时,关闭窗口退出。由于我们在一个循环中,需要break才可以。代码如下:

    if cv.waitKey(1) & 0xFF == ord('d'):
        cv.destroyAllWindows()
        break
    elif cv.waitKey(1) & 0xFF == ord('q'):
        pointList = []

其中,cv.waitKey(1) & 0xFF是因为不同系统返回的值不全是八位,与操作进行一个第八位的获取。

cv2.waitKey(1) returns the character code of the currently pressed key
and -1 if no key is pressed. the & 0xFF is a binary AND operation to
ensure only the single byte (ASCII) representation of the key remains
as for some operating systems cv2.waitKey(1) will return a code that
is not a single byte. ord(‘q’) always returns the ASCII representation
of ‘q’ which is 113 (0x71 in hex).

实际操作中的问题和注意事项

  1. Fail to close the window properly
    在这里插入图片描述
    While Ture: 环境内没有break

  2. Too much lines
    在这里插入图片描述
    cv.line(img, tuple(pointList[round((size-1)/3)*3]), (x,y), (0,0,255), 2)
    应该在if event == cv.EVENT_LBUTTONDOWN:下

完整代码与结果示意

import cv2 as cv
import math

path = 'E:\\CV\\pics\\angle.png'
img = cv.imread(path)
pointList = []

def mousePoints(event, x, y, flags, params):
    if event == cv.EVENT_LBUTTONDOWN:
        cv.circle(img, (x,y), 5, (0,0,255), cv.FILLED)
        pointList.append([x,y])
        #print(pointList)
        #draw out the lines
        size = len(pointList)
        if size != 1 and (size-1) % 3 != 0:
            cv.line(img, tuple(pointList[round((size-2)/3)*3]), (x,y), (0,0,255), 2)

def gradient(pt1, pt2):
    #(y2-y1)/(x2-x1)
    return (pt2[1]-pt1[1])/(pt2[0]-pt1[0])

def getAngle(pointList):
    pt1, pt2, pt3 = pointList[-3:]#the last 3 points
    m1 = gradient(pt1, pt2)
    m2 = gradient(pt1, pt3)
    angR = math.atan((m1-m2)/(1+m1*m2))
    angD = round(math.degrees(angR))
    
    cv.putText(img, str(angD), (pt1[0]-40, pt1[1]-20), cv.FONT_HERSHEY_COMPLEX, 
               1.5, (0,0,255), 2)

while True:        
    if len(pointList) % 3 == 0 and len(pointList) != 0:
        getAngle(pointList)

    cv.imshow('image',img)
    cv.setMouseCallback('image', mousePoints)
    #delete the wrong points
    if cv.waitKey(1) & 0xFF == ord('d'):
        cv.destroyAllWindows()
        break
    elif cv.waitKey(1) & 0xFF == ord('q'):
        pointList = []

结果:结果

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Zeror_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值