|
| 1 | +# 二维码检测和识别 |
| 2 | + |
| 3 | +## 概述 |
| 4 | +根据Opencv的描述,OpenCV3.4.4以上版本支持二维码检测和识别! |
| 5 | + |
| 6 | +## 函数 |
| 7 | + |
| 8 | +Opencv在对象检测模块中 `QRCodeDetector` 有两个相关API分别实现二维码检测与二维码解析。 |
| 9 | + |
| 10 | +1. 检测API |
| 11 | +``` |
| 12 | +points = QRCodeDetector.detect(img) |
| 13 | +``` |
| 14 | +其中: |
| 15 | +- img为输入图像,灰度或者彩色图像; |
| 16 | +- points输出得到的二维码四个点的坐标信息; |
| 17 | + |
| 18 | +2. 识别API |
| 19 | +``` |
| 20 | +straight_qrcode = QRCodeDetector.decode(img, points) |
| 21 | +``` |
| 22 | +其中: |
| 23 | +- img为输入图像,灰度或者彩色图像; |
| 24 | +- points是二维码ROI最小外接矩形顶点坐标; |
| 25 | +- straight_qrcode输出的是二维码区域ROI图像信息 |
| 26 | +返回的二维码utf-8字符串; |
| 27 | + |
| 28 | +3. 结合检测识别的API |
| 29 | +``` |
| 30 | +points,straight_qrcode = QRCodeDetector.detectAndDecode(img) |
| 31 | +``` |
| 32 | +其中: |
| 33 | +- img为输入图像,灰度或者彩色图像; |
| 34 | +- points输出二维码ROI最小外接矩形顶点坐标; |
| 35 | +- straight_qrcode输出的是二维码区域ROI图像信息 |
| 36 | +返回的二维码utf-8字符串; |
| 37 | + |
| 38 | +## 代码 |
| 39 | + |
| 40 | +整体检测识别的代码如下: |
| 41 | +```python |
| 42 | +import cv2 |
| 43 | +import numpy as np |
| 44 | + |
| 45 | +# 读取二维码 |
| 46 | +src = cv2.imread("qrcode.png") |
| 47 | +gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY) |
| 48 | +# 设置检测器 |
| 49 | +qrcoder = cv2.QRCodeDetector() |
| 50 | +# 检测识别二维码 |
| 51 | +codeinfo, points, straight_qrcode = qrcoder.detectAndDecode(gray) |
| 52 | +result = np.copy(src) |
| 53 | +cv2.drawContours(result, [np.int32(points)], 0, (0, 0, 255), 2) |
| 54 | +# 输出识别二维码的信息 |
| 55 | +print("qrcode information is : \n%s"% codeinfo) |
| 56 | +# 显示图片 |
| 57 | +cv2.imshow("result", result) |
| 58 | +cv2.imshow("qrcode roi", np.uint8(straight_qrcode)) |
| 59 | +cv2.waitKey(0) |
| 60 | +cv2.destroyAllWindows() |
| 61 | +``` |
| 62 | +输出: |
| 63 | +``` |
| 64 | +qrcode information is : |
| 65 | +Hello, this is Jimmy, thanks for your little star~ |
| 66 | +``` |
| 67 | +原图: |
| 68 | + |
| 69 | +<img src=https://i.loli.net/2020/02/24/Lv4TuaMqPehZzFQ.png width=200> |
| 70 | + |
| 71 | +检测: |
| 72 | + |
| 73 | +<img src=https://i.loli.net/2020/02/24/3bY6AgUSCN75QFR.png width=200> |
| 74 | + |
| 75 | +ROI图: |
| 76 | + |
| 77 | +<img src=https://i.loli.net/2020/02/24/Wf2JVXcFbMaOQu6.png width=100> |
0 commit comments