1:二维码在工业和工作生活中应用广泛,下面基于OpenCvSharp识别图像中二维码;
2:函数:OpenCvSharp中,QRCodeDetector
有两个相关API分别实现二维码检测与二维码解析。
public string DetectAndDecode(InputArray img, out Point2f[] points, OutputArray straightQrcode = null);
其中:
//
// 摘要:
// Both detects and decodes QR code
//
// 参数:
// img:
// grayscale or color (BGR) image containing QR code.
//
// points:
// opiotnal output array of vertices of the found QR code quadrangle. Will be empty
// if not found.
//
// straightQrcode:
// The optional output image containing rectified and binarized QR code
- img 为输入图像,灰度或者彩色图像;
- points 是二维码ROI最小外接矩形顶点坐标;
- straightQrcode 输出的是二维码区域ROI图像信息 返回的二维码utf-8字符串;
- 返回值是已识别的二维码内容
public string DetectQRCode(Mat src)
{
//src = Cv2.ImRead(@"C:\Users\1617\Desktop\Test\qr.png");
//图像灰度
Mat gray = new Mat();
Cv2.CvtColor(src, gray, ColorConversionCodes.BGRA2GRAY);
Cv2.ImShow("gray", gray);
//二值化
Mat threshold = new Mat();
//Cv2.AdaptiveThreshold(gray, threshold, 255.0, AdaptiveThresholdTypes.MeanC, ThresholdTypes.Binary, 13, 2);
Cv2.Threshold(gray, threshold, 0, 255, ThresholdTypes.Binary|ThresholdTypes.Otsu);
Cv2.ImShow("threshold", threshold);
//绘制轮廓
//截取二维码有效区域
//识别二维码
QRCodeDetector qRCodeDetector = new QRCodeDetector();
Point2f[] point2Fs;
//Cv2.ImShow("gray", gray);
Mat mat = new Mat();
string code = qRCodeDetector.DetectAndDecode(src, out point2Fs, mat);
//Point[][] contours;
//HierarchyIndex[] hierarchies;
//Cv2.FindContours(src, out contours, out hierarchies, RetrievalModes.Tree, ContourApproximationModes.ApproxSimple);
//RNG rng = new RNG(12345);
//for (int i = 0; i < point2Fs.Length; i++)
//{
// Cv2.DrawContours(src, point2Fs, i, new Scalar(rng.Uniform(0, 255), rng.Uniform(0, 255), rng.Uniform(0, 255)), 6, LineTypes.Link4);
//}
Cv2.Rectangle(src, new Point((int)point2Fs[3].X, (int)point2Fs[1].Y), new Point((int)point2Fs[2].X, (int)point2Fs[2].Y), new Scalar(0, 255, 255), 2);
Cv2.ImShow("src", src);
return code;
}
3:实测以下两张图片,一张手机拍摄的二维码图像,一张截图
4:处理结果图像如下:
内容:1234567文章来源:https://www.toymoban.com/news/detail-669559.html
内容:http://weixin.qq.com/r/GihgeEPEix70rQcb930I文章来源地址https://www.toymoban.com/news/detail-669559.html
到了这里,关于OpenCv案例(十): 基于OpenCvSharp识别二维码的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!