1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| using OpenCvSharp; using System; using System.Diagnostics; using System.Drawing; using System.Text; using System.Windows.Forms;
namespace OpenCvSharp_微信二维码引擎 { public partial class Form1 : Form { public Form1() { InitializeComponent(); }
const string detector_prototxt_path = "detect.prototxt"; const string detector_caffe_model_path = "detect.caffemodel"; const string prototxt_path = "sr.prototxt"; const string caffe_model_path = "sr.caffemodel"; private string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png"; WeChatQRCode wechatQrcode = null; Mat src = null; Bitmap bitmap = null; Stopwatch sw = null; StringBuilder sb = null; Graphics g = null; Pen p = new Pen(Brushes.Red); SolidBrush drawBush = new SolidBrush(Color.Red); Font drawFont = new Font("Arial", 8, FontStyle.Bold, GraphicsUnit.Millimeter); void Detect(string location) { sw = new Stopwatch(); sw.Start();
src = Cv2.ImRead(location);
bitmap = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(src);
if (pictureBox1.Image != null) { pictureBox1.Image.Dispose(); } pictureBox1.Image = bitmap;
wechatQrcode.DetectAndDecode(src, out var rects, out var texts);
sw.Stop();
sb = new StringBuilder(); sb.AppendLine("耗时:" + sw.ElapsedMilliseconds.ToString() + "ms");
for (int i = 0; i < rects.Length; i++) { var x1 = rects[i].At<float>(0, 0); var y1 = rects[i].At<float>(0, 1); var x2 = rects[i].At<float>(2, 0); var y2 = rects[i].At<float>(2, 1); string result = texts[i]; DrawRect(bitmap, x1, y1, x2, y2, result); sb.AppendLine("内容:[" + result + "] 位置:" + x1 + "," + y1 + "," + x2 + "," + y2); }
MessageBox.Show(sb.ToString(), "识别信息"); }
public Bitmap DrawRect(Bitmap bmp, float x1, float y1, float x2, float y2, string text) { g = Graphics.FromImage(bmp); g.DrawRectangle(p, x1, y1, x2 - x1, y2 - y1); g.DrawString(text, drawFont, drawBush, x1, y2); g.Dispose(); return bmp; }
private void button2_Click(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = fileFilter; if (ofd.ShowDialog() == DialogResult.OK) { Detect(ofd.FileName); } }
private void Form1_Load(object sender, EventArgs e) { wechatQrcode = OpenCvSharp.WeChatQRCode.Create( detector_prototxt_path , detector_caffe_model_path , prototxt_path , caffe_model_path); }
private void button1_Click(object sender, EventArgs e) { Detect("test.png"); } } }
|