文章主要介绍如何自己编译opencvsharp源码,因为需要.net 6 ,所以介绍vs2022 的编译。
https://github.com/shimat/opencvsharp
首先在github 下载,速度慢的复制到gitee下载,或者早上下载很快。
nuget上的最新版本4.5.5,不带微信二维码扫描,尝试自己编译。
预计下一次更新可以在nuget直接下载,但是现在的release暂时还不支持。所以自己编译源码。
运行 download_opencv_windows.ps1 。自动下载opencv4.5.5,下载失败的请在早上下载。
然后 运行download_tesseract_windows.ps1 . 自动下载tesseract,下载失败的请在早上下载。
然后运行OpenCvSharp.sln。
设置到release。
编译,结果报错,没有报错的请忽视。。
error LNK2001: 无法解析的外部符号 __imp___std_init_once_begin_init
报错20几个
选择OpencvsharpExtern,这个c++ 项目,右键属性。
将平台工具集设为 VS2019(v142)
编译成功。之前有下载vs2019。或者运行vs installer。勾选2019 c++ 生成工具。
dll生成完毕,dll复制到自己的工程中。添加到引用。
using OpenCvSharp;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace WinFormsApp5
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static Bitmap DrawRect(Bitmap bmp, float x1, float y1, float x2, float y2,string text)
{
Graphics gg = Graphics.FromImage(bmp);
Pen p = new Pen(Brushes.Red);
gg.DrawRectangle(p, x1, y1, x2 - x1, y2 - y1);
Font drawFont = new Font("Arial", 8, FontStyle.Bold, GraphicsUnit.Millimeter);
SolidBrush drawBush = new SolidBrush(Color.Red);
gg.DrawString(text, drawFont, drawBush, x1, y2);
gg.Dispose();
return bmp;
}
const string _wechat_QCODE_detector_prototxt_path = "_data/wechat_qrcode/detect.prototxt";
const string _wechat_QCODE_detector_caffe_model_path = "_data/wechat_qrcode/detect.caffemodel";
const string _wechat_QCODE_super_resolution_prototxt_path = "_data/wechat_qrcode/sr.prototxt";
const string _wechat_QCODE_super_resolution_caffe_model_path = "_data/wechat_qrcode/sr.caffemodel";
void detect(string location)
{
// Bitmap bitmap = (Bitmap)Image.FromFile(location);
// OpenCvSharp.Mat src = OpenCvSharp.Extensions.BitmapConverter.ToMat(bitmap);
Stopwatch sw = new Stopwatch();
sw.Start();
using var wechatQrcode = OpenCvSharp.WeChatQRCode.Create(
_wechat_QCODE_detector_prototxt_path, _wechat_QCODE_detector_caffe_model_path,
_wechat_QCODE_super_resolution_prototxt_path, _wechat_QCODE_super_resolution_caffe_model_path);
using var src = Cv2.ImRead(location);
Bitmap bitmap= OpenCvSharp.Extensions.BitmapConverter.ToBitmap(src);
pictureBox1.Image = bitmap;
wechatQrcode.DetectAndDecode(src, out var rects, out var texts);
sw.Stop();
StringBuilder sb = new StringBuilder();
sb.Append("耗时" + sw.ElapsedMilliseconds.ToString() + "ms\r\n");
for (int i = 0; i < rects.Length; i++)
{
var x1 = rects[i].At(0, 0);
var y1 = rects[i].At(0, 1);
var x2 = rects[i].At(2, 0);
var y2 = rects[i].At(2, 1);
string result = texts[i];
DrawRect(bitmap, x1, y1, x2, y2, result);
sb.Append("内容:" + result + " 位置:" + x1 + ", " + y1 + ", " + x2 + ", " + y2 + "\r\n");
}
MessageBox.Show(sb.ToString());
}
private void button1_Click(object sender, EventArgs e)
{
detect("_data/image/dm.bmp");
detect("_data/image/dm2.bmp");//i5 10400 21ms
}
}
}
运行速度,i5 10400 在21ms左右。
源码下载:
opencvsharp4.5.5wechats微信二维码识别c#-C#文档类资源-CSDN文库
2022.6.9 opencvsharp4.6.0 更新了,现在支持 wechat_qrcode 扫描了。