引言
QR二维码在我们的日常生活中非常多见,比如微信和支付宝,火车票和商品标识等。二维码的出现极大地方便了我们的日常·生活,同时也能将信息较为隐蔽地进行传输。
1、定位结果的detect()函数
bool cv::QRCodeDetector::detect(InputArray img, OutputArray points)
img:待检测是否含有QR二维码的灰度图像或者彩色图像
points:包含QR二维码的最小区域四边形的4个顶点坐标,即二维码的4个顶点
2、 定位结果解码的decode()函数
std::string cv::QRCodeDetector::decode(InputArray img, InputArray points, OutputArray straight_qrcode = noArray())
img:含有QR二维码的图像
points:包含QR二维码的最小区域的四边形的四个顶点
straight_qrcode:经过校正和二值化的QR二维码
3、识别并解码的detectAndDecode()函数
std::string cv::QRCodeDetector::decode(InputArray img, OutputArray points = noArray(), OutputArray straight_qrcode = noArray())
img:含有QR二维码的图像
points:包含QR二维码的最小区域的四边形的四个顶点
straight_qrcode:经过校正和二值化的QR二维码
4、代码实现
#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/core.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main()
{
Mat img = imread("F:\\图像处理\\图片\\QR.jpg");
if (img.empty()) {
cout << "请确认文件名称是否正确!" << endl;
return -1;
}
Mat gray, qrcode_bin;
cvtColor(img, gray, COLOR_BGR2GRAY);
QRCodeDetector qrcodedetector;
vector<Point> points;
string information;
bool isQRcode;
isQRcode = qrcodedetector.detect(gray, points); //识别二维码
if (isQRcode) {
//解码二维码
information = qrcodedetector.decode(gray, points, qrcode_bin);
cout << points << endl; //输出4个坐标的顶点
}
else {
cout << "无法识别二维码,请确认图像是否含有二维码!" << endl;
return -1;
}
//绘制二维码边框
for (int i = 0; i < points.size(); i++) {
if (i == points.size() - 1) {
line(img, points[i], points[0], Scalar(0, 0, 255), 2, 8);
break;
}
line(img, points[i], points[i + 1], Scalar(0, 0, 255), 2, 8);
}
//将解码内容输出到图片上
putText(img, information.c_str(), Point(20, 30), 0, 1.0, Scalar(0, 0, 255), 2, 8);
//利用函数直接定位二维码并解码
string information2;
vector<Point> points2;
information2 = qrcodedetector.detectAndDecode(gray, points2);
cout << points2 << endl;
putText(img, information2.c_str(), Point(20, 55), 0, 1.0, Scalar(0, 0, 0), 2, 8);
//输出结果
namedWindow("result", WINDOW_NORMAL);
imshow("result", img);
namedWindow("qrcode_bin", WINDOW_NORMAL);
imshow("qrcode_bin", qrcode_bin);
waitKey(0);
return 0;
}
5、结果
QR二维码检测的流程到这里就全部完成了,如果您觉得以上内容对您有所帮助,不妨一键三连,感想您的观看!