新建桌面程序
安装opencvsharp
拖拽设计页面
选择图片识别代码
using OpenCvSharp;
using System.Text;
namespace QRcodeIdentity
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 选择图片
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void selectBtn_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
// 设置文件对话框的标题
openFileDialog.Title = "选择图片";
// 设置文件类型过滤器
// 注意这里"PNG 图片 (*.png)|*.png|JPG 图片 (*.jpg)|*.jpg"的写法
// "|"用于分隔不同的过滤器,每个过滤器由“描述|文件扩展名”组成
openFileDialog.Filter = "PNG 图片 (*.png)|*.png|JPG 图片 (*.jpg)|*.jpg";
// 设置默认文件类型过滤器为第一个(PNG 图片)
openFileDialog.FilterIndex = 1;
// 显示文件对话框
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
this.imgPathTxt.Text = openFileDialog.FileName;
}
}
/// <summary>
/// 识别图片中的二维码位置和内容
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void runBtn_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.imgPathTxt.Text))
{
MessageBox.Show("请选择图片");
return;
}
var src = Cv2.ImRead(this.imgPathTxt.Text);
//图像灰度
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();
/*
img 为输入图像,灰度或者彩色图像;
points 是二维码ROI最小外接矩形顶点坐标;
straightQrcode 输出的是二维码区域ROI图像信息 返回的二维码utf-8字符串
返回值是已识别的二维码内容
*/
string code = qRCodeDetector.DetectAndDecode(src, out point2Fs, mat);
Cv2.Rectangle(src, new OpenCvSharp.Point((int)point2Fs[3].X, (int)point2Fs[1].Y), new OpenCvSharp.Point((int)point2Fs[2].X, (int)point2Fs[2].Y), new Scalar(0, 255, 255), 2);
//Cv2.ImShow("src", src);
// 使用Cv2.ImWrite方法保存Mat对象为图片文件
var filePath = $"{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")}.jpg";
bool result = Cv2.ImWrite(filePath, src);
StringBuilder str = new StringBuilder();
str.AppendLine("识别成功\r\n");
str.Append($"二维码内容为:{code}\r\n");
var xLeft = (int)point2Fs[3].X;
var yTop = (int)point2Fs[1].Y;
var width = (int)point2Fs[2].X - (int)point2Fs[3].X;
str.Append($"距离顶部{yTop},距离左侧{xLeft},宽度:{width}");
this.resultTxt.Text = str.ToString();
}
}
}
参考
https://blog.csdn.net/qq_37835727/article/details/127809933
https://blog.csdn.net/weixin_63357306/article/details/132830563
https://blog.51cto.com/u_16099252/10915538
https://cloud.tencent.com/developer/article/2420183