效果
项目
代码
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Emgu.CV;
using Emgu.CV.Util;
using static Emgu.CV.BarcodeDetector;
namespace Emgu.CV_条码检测
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string fileFilter = "*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tiff;*.png";
Bitmap bmp;
String imgPath = "";
Graphics g = null;
Pen p = new Pen(Brushes.Red);
SolidBrush drawBush = new SolidBrush(Color.Red);
Brush bush = new SolidBrush(Color.Green);
Font drawFont = new Font("Arial", 8, FontStyle.Bold, GraphicsUnit.Millimeter);
const string prototxt_path = "sr.prototxt";
const string caffe_model_path = "sr.caffemodel";
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = fileFilter;
if (ofd.ShowDialog() != DialogResult.OK) return;
imgPath = ofd.FileName;
bmp = new Bitmap(imgPath);
pictureBox1.Image = bmp;
g = Graphics.FromImage(bmp);
g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
}
private void button1_Click(object sender, EventArgs e)
{
if (pictureBox1.Image == null)
{
return;
}
BarcodeDetector barcodeDetector = new BarcodeDetector(prototxt_path, caffe_model_path);
VectorOfCvString vectorOfCvString = new VectorOfCvString();
VectorOfInt vectorOfInt = new VectorOfInt();
Mat src = new Mat(imgPath, CV.CvEnum.ImreadModes.Grayscale);
Mat rects = new Mat();
bool b = barcodeDetector.Detect(src, rects);
Mat mat = new Mat();
bool b2 = barcodeDetector.DetectAndDecode(src, vectorOfCvString, vectorOfInt, mat);
Array data = rects.GetData();
if (data == null) { return; }
int num = data.GetLength(0);
for (int i = 0; i < num; i++)
{
float x1 = (float)data.GetValue(i, 0, 0);
float y1 = (float)data.GetValue(i, 0, 1);
float x2 = (float)data.GetValue(i, 1, 0);
float y2 = (float)data.GetValue(i, 1, 1);
float x3 = (float)data.GetValue(i, 2, 0);
float y3 = (float)data.GetValue(i, 2, 1);
float x4 = (float)data.GetValue(i, 3, 0);
float y4 = (float)data.GetValue(i, 3, 1);
g.FillEllipse(bush, x1, y1, 10, 10);
g.DrawString("1", drawFont, drawBush, x1, y1);
g.FillEllipse(bush, x2, y2, 10, 10);
g.DrawString("2", drawFont, drawBush, x2, y2);
g.FillEllipse(bush, x3, y3, 10, 10);
g.DrawString("3", drawFont, drawBush, x3, y3);
g.FillEllipse(bush, x4, y4, 10, 10);
g.DrawString("4", drawFont, drawBush, x4, y4);
g.DrawRectangle(p, x2, y2, x4 - x2, y4 - y2);
}
pictureBox2.Image = bmp;
}
}
}
Demo下载