在我们的日常生活中, 处处可见条形码和二维码.
在以前, 我们去逛书店时, 或者你现在随手拿起你身边的一本书, 你肯定能看到书本的封页后面印有一排黑色线条组成的标签, 也就是条形码; 你去你们学校的自助机上借书还书时识别的也是条形码; 哦, 对了, 你还记得每次大型考试答题卡上都会贴上监考老师分发给你的那个标签吗? 还是条形码; 甚至现在你随随便便逛个超市或便利店, 收银员或者自助机也都是通过扫商品条形码给你计价的. 条形码在我们的日常生活中真的是随处可见.
到了后来, 2016 年之后, 二维码也渐渐开始普及起来, 现在二维码几乎成了我们日常生活的一部分: 新朋友微信加个好友; 上下班搭乘公交地铁; 平时买东西付款; 和别人收付款的当面交易; 各个大小公司或者商场甚至地摊搞活动的时候也告诉你扫码有优惠.
现在只要你出门, 或者你不出门, 你只要用手机, 你是个网民, 你就很难不接触到各种条形码与二维码.
那么这些个条形码识别和二维码识别是怎么完成的呢?
其实使用 OpenCV 和 Zbar 这两个 python 模块就可以实现二维码和条形码的识别.
1. 软件安装
在 Ubuntu 上安装 Zbar:
$ sudo apt-get install libzbar0
在 MacOS 系统中安装 Zbar:
$ brew install zbar
另外还需要安装 OpenCV:
pip install opencv-python
2. 识别图片上的二维码或条形码
- # 导入模块
- from pyzbar import pyzbar
- import matplotlib.pyplot as plt
- import cv2
- # 读取图片
- image = cv2.imread('image.jpeg')
- # 找到图像中的条形码并进行解码
- barcodes = pyzbar.decode(image)
- def decode(image, barcodes):
- # 循环检测到的条形码
- for barcode in barcodes:
- # 提取条形码的边界框的位置
- # 画出图像中条形码的边界框
- (x, y, w, h) = barcode.rect
- cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 5)
- # 条形码数据为字节对象, 所以如果我们想在输出图像上
- # 画出来, 就需要先将它转换成字符串
- barcodeData = barcode.data.decode("utf-8")
- barcodeType = barcode.type
- # 绘出图像上条形码的数据和条形码类型
- text = "{} ({})".format(barcodeData, barcodeType)
- cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,.8, (255, 0, 0), 2)
- # 向终端打印条形码数据和条形码类型
- print("[INFO] Found {} barcode: {}".format(barcodeType, barcodeData))
- plt.figure(figsize=(10,10))
- plt.imshow(image)
- plt.show()
- #. 识别二维码
- decode(image, barcodes)
- # 读取图片
- image = cv2.imread('image2.png')
- # 找到图像中的条形码并进行解码
- barcodes = pyzbar.decode(image)
- # 识别条形码
- decode(image, barcodes)
输出结果:
[INFO] Found QRCODE barcode: http://weixin.qq.com/r/-irJ0RbEbU***VKy93-s
[INFO] Found CODE128 barcode: http://weixin.qq.com/r/-irJ0RbEbU***VKy93-s
3. 识别视频中的二维码或条形码
- from pyzbar import pyzbar
- import cv2
- # 获取二维码或条形码
- def decode(image):
- # 找到图像中的条形码并进行解码
- barcodes = pyzbar.decode(image)
- # 循环检测到的条形码
- for barcode in barcodes:
- # 提取条形码的边界框的位置
- # 画出图像中条形码的边界框
- (x, y, w, h) = barcode.rect
- cv2.rectangle(image, (x, y), (x + w, y + h), (255, 0, 0), 5)
- # 条形码数据为字节对象, 所以如果我们想在输出图像上
- # 画出来, 就需要先将它转换成字符串
- barcodeData = barcode.data.decode("utf-8")
- barcodeType = barcode.type
- # 绘出图像上条形码的数据和条形码类型
- text = "{} ({})".format(barcodeData, barcodeType)
- cv2.putText(image, text, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX,.8, (255, 0, 0), 2)
- # 读取摄像头
- cap = cv2.VideoCapture(0)
- while(True):
- ret, frame = cap.read()
- if ret==True:
- # 获取二维码或条形码
- decode(frame)
- # 显示图片
- cv2.imshow('frame',frame)
- # 按 q 退出
- if cv2.waitKey(1) & 0xff == ord('q'):
- break
- else:
- break
- cap.release()
- cv2.destroyAllWindows()
识别效果: 视频地址 https://v.qq.com/x/page/x0809jhjhtt.html
参考资料:
4. 项目打包
百度云盘:
用 OpenCV 和 Python 识别二维码和条形码
https://pan.baidu.com/s/14CKjZh9YnyDa-KmY2wJcKg
来源: http://www.bubuko.com/infodetail-2889280.html