项目启动

这是我入职以来第一个任务吧,要完成巡检机器人的一个视觉定位功能,目前想的是机器人通过摄像头检测到张贴在室内各个定点位置二维码,通过识别二维码内部的信息和定制二维码的大小,获取到机器人的位置。

(机器人现在还是冰山一脚,目前很多功能都没有实现,还处于项目的初级阶段)

前期准备

opencv4.0版本也是发布了,以后应该都是用opencv4.0了,现在已经内置了二维码识别模块,但是在写这段代码的时候还是用的是3.0版本,利用了pyzbar模块进行解码

环境准备:

  • opencv4.0(3.0)
  • python3任意版本
  • pyzbar

详情可以查看我的csdn里面的内容也差不多

初步效果

这里的话是3个二维码都可以扫描出来,由于qrcode的信息是中文的所以打印在屏幕上会出错请使用matplotlib显示图像。正确信息可以从控制台查看。


code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import cv2
from pyzbar import pyzbar
#二维码动态识别
camera=cv2.VideoCapture(0)
camera.set(3,1280) #设置分辨率
camera.set(4,768)
while True:
(grabbed,frame)=camera.read()
#获取画面中心点
h1,w1= frame.shape[0],frame.shape[1]

# 纠正畸变(这里把相机标定的代码去除了,各位自行标定吧)
dst = frame

# 扫描二维码
text = pyzbar.decode(dst)
for texts in text:
textdate = texts.data.decode('utf-8')
print(textdate)
(x, y, w, h) = texts.rect#获取二维码的外接矩形顶点坐标
print('识别内容:'+textdate)

# 二维码中心坐标
cx = int(x + w / 2)
cy = int(y + h / 2)
cv2.circle(dst, (cx, cy), 2, (0, 255, 0), 8) # 做出中心坐标
print('中间点坐标:',cx,cy)
coordinate=(cx,cy)
#在画面左上角写出二维码中心位置
cv2.putText(dst,'QRcode_location'+str(coordinate),(20,20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
#画出画面中心与二维码中心的连接线
cv2.line(dst, (cx,cy),(int(w1/2),int(h1/2)), (255, 0, 0), 2)
#cv2.rectangle(dst, (x, y), (x + w, y + h), (0, 255, 255), 2) # 做出外接矩形
#二维码最小矩形
cv2.line(dst, texts.polygon[0], texts.polygon[1], (255, 0, 0), 2)
cv2.line(dst, texts.polygon[1], texts.polygon[2], (255, 0, 0), 2)
cv2.line(dst, texts.polygon[2], texts.polygon[3], (255, 0, 0), 2)
cv2.line(dst, texts.polygon[3], texts.polygon[0], (255, 0, 0), 2)
#写出扫描内容
txt = '(' + texts.type + ') ' + textdate
cv2.putText(dst, txt, (x - 10, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 50, 255), 2)


cv2.imshow('dst',dst)
if cv2.waitKey(1) & 0xFF == ord('q'): # 按q保存一张图片
cv2.imwrite("./frame.jpg", frame)
break

camera.release()
cv2.destroyAllWindows()

代码直接运行就行,适用于opencv3.x和4.x版本