说明:以下是python2对二维码的识别,如果你用的是python3,可参考
https://blog.csdn.net/weixin_42365428/article/details/85772055 这篇博客。
1 Ubuntu下安装zbar,在终端输入:
sudo apt-get install python-zbar
2 实现代码
#coding=utf8
#有中文要加上面这句
import zbar
from PIL import Image
import cv2
def decode(frame):
scanner = zbar.ImageScanner()#获得扫描对象
scanner.parse_config('enable') #配置
img = Image.fromarray(frame).convert('L')#转为灰度图片
width, height = img.size
raw = img.tobytes()#图片转为二进制
zbarimage = zbar.Image(width, height, 'Y800', raw)#读取二维码数据 Y800为灰度图片格式
scanner.scan(zbarimage)#扫描图片
data = ''
for symbol in zbarimage:
data += symbol.data#得到数据
return data
def detect():
camera = cv2.VideoCapture(0)
while True:
flag,frame=camera.read()
if decode(frame) != '':
with open('data.txt', 'w') as f: # w表示写入
f.write(decode(frame))
break
cv2.waitKey(1)
cv2.imshow("camera", frame)
camera.release()
cv2.destroyAllWindows()
if __name__=='__main__':
detect()