opencv-120-二维码检测与识别 发表于 2019-05-25 | 分类于 opencv 知识点OpenCV在对象检测模块中QRCodeDetector有两个相关API分别实现二维码检测与二维码解析: 12345678910111213141516171819202122232425# 检测二维码bool cv::QRCodeDetector::detect( InputArray img, OutputArray points )constimg输入图像,灰度或者彩色图像points 得到的二维码四个点的坐标信息# 解析二维码std::string cv::QRCodeDetector::decode( InputArray img, InputArray points, OutputArray straight_qrcode = noArray() )img输入图像,灰度或者彩色图像points 二维码ROI最小外接矩形顶点坐标qrcode 输出的是二维码区域ROI图像信息返回的二维码utf-8字符串上述两个API功能,可以通过一个API调用实现,该API如下:std::string cv::QRCodeDetector::detectAndDecode( InputArray img, OutputArray points = noArray(), OutputArray straight_qrcode = noArray() ) 代码(c++,python)123456789101112131415161718192021222324252627#include <opencv2/opencv.hpp>#include <iostream>using namespace cv;using namespace std;int main(int argc, char** argv) { Mat src = imread("D:/images/qrcode.png"); imshow("image", src); Mat gray, qrcode_roi; cvtColor(src, gray, COLOR_BGR2GRAY); QRCodeDetector qrcode_detector; vector<Point> pts; string detect_info; bool det_result = qrcode_detector.detect(gray, pts); if (det_result) { detect_info = qrcode_detector.decode(gray, pts, qrcode_roi); } vector< vector<Point> > contours; contours.push_back(pts); drawContours(src, contours, 0, Scalar(0, 0, 255), 2); putText(src, detect_info.c_str(), Point(20, 200), FONT_HERSHEY_SIMPLEX, 1.0, Scalar(0, 0, 255), 2, 8); printf("qrcode info %s \n", detect_info.c_str()); imshow("result", src); waitKey(0); return 0;} 1234567891011121314151617181920212223"""二维码检测与识别"""import cv2 as cvimport numpy as npsrc = cv.imread("images/fanfan.jpg")cv.imshow("image", src)gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)qrcoder = cv.QRCodeDetector()codeinfo, points, straight_qrcode = qrcoder.detectAndDecode(gray)print(points)result = np.copy(src)cv.drawContours(result, [np.int32(points)], 0, (0, 0, 255), 2)print("qrcode : %s" % codeinfo)cv.imshow("result", result)code_roi = np.uint8(straight_qrcode)cv.namedWindow("qrcode roi", cv.WINDOW_NORMAL)cv.imshow("qrcode roi", code_roi)cv.waitKey(0)cv.destroyAllWindows() 结果 代码地址github