您的位置:首页 > 其它

简单的Windows Webcam应用:Barcode Reader

2017-09-22 10:19 363 查看
原文:简单的Windows Webcam应用:Barcode Reader

在Windows上用WinForm创建一个Webcam应用需要用到DirectShow。DirectShow没有提供C#的接口。如果要用C#开发,需要创建一个桥接DLL。Touchless SDK是一个免费开源的.NET库,对DirectShow进行了简单的封装。使用Touchless可以很方便的在WinForm应用中调用camera。这里分享下如何创建一个调用webcam的barcode
reader。

参考原文:WinForm Barcode Reader with Webcam and C#

作者:Xiao Ling

翻译:yushulx



WinForm Barcode Reader

下载Touchless SDK

Dynamsoft Barcode Reader SDK用于barcode识别. 如要想用免费开源的,可以选择ZXing.NET

打开Visual Studio 2015创建一个WinForm工程.

通过Nuget可以在工程中直接下载安装Dynamsoft Barcode Reader:



在引用中添加TouchlessLib.dll:



把WebCamLib.dll添加到工程中。属性中设置拷贝。这样工程编译之后就会把DLL拷贝到输出目录中,不需要再手动拷贝。



初始化Touchless和Dynamsoft Barcode Reader:

// Initialize Dynamsoft Barcode Reader
_barcodeReader = new BarcodeReader();
// Initialize Touchless
_touch = new TouchlessMgr();

通过系统对话框把图片加载到PictureBox中:

using (OpenFileDialog dlg = new OpenFileDialog())
{
dlg.Title = "Open Image";

if (dlg.ShowDialog() == DialogResult.OK)
{
Bitmap bitmap = null;

try
{
bitmap =  new Bitmap(dlg.FileName);
}
catch (Exception exception)
{
MessageBox.Show("File not supported.");
return;
}

pictureBox1.Image = new Bitmap(dlg.FileName);
}
}

设置回调函数启动webcam:

// Start to acquire images
_touch.CurrentCamera = _touch.Cameras[0];
_touch.CurrentCamera.CaptureWidth = _previewWidth; // Set width
_touch.CurrentCamera.CaptureWidth = _previewHight; // Set height
_touch.CurrentCamera.OnImageCaptured += new EventHandler<CameraEventArgs>(OnImageCaptured); // Set preview callback function

camera的数据返回不是在UI线程。要显示结果,需要调用UI线程:

private void OnImageCaptured(object sender, CameraEventArgs args)
{
// Get the bitmap
Bitmap bitmap = args.Image;

// Read barcode and show results in UI thread
this.Invoke((MethodInvoker)delegate
{
pictureBox1.Image = bitmap;
ReadBarcode(bitmap);
});
}

识别barcode:

private void ReadBarcode(Bitmap bitmap)
{
// Read barcodes with Dynamsoft Barcode Reader
Stopwatch sw = Stopwatch.StartNew();
sw.Start();
BarcodeResult[] results = _barcodeReader.DecodeBitmap(bitmap);
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalMilliseconds + "ms");

// Clear previous results
textBox1.Clear();

if (results == null)
{
textBox1.Text = "No barcode detected!";
return;
}

// Display barcode results
foreach (BarcodeResult result in results)
{
textBox1.AppendText(result.BarcodeText + "\n");
textBox1.AppendText("\n");
}
}

运行程序:



使用算法接口的时候需要注意一下性能。可以使用Stopwatch来计算时间消耗:

Stopwatch sw = Stopwatch.StartNew();
sw.Start();
BarcodeResult[] results = _barcodeReader.DecodeBitmap(bitmap);
sw.Stop();
Console.WriteLine(sw.Elapsed.TotalMilliseconds + "ms");


源码

https://github.com/yushulx/windows-webcam-barcode-reader
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: