在Windows上用WinForm建立一个Webcam应用须要用到DirectShow。DirectShow没有提供C#的接口。若是要用C#开发,须要建立一个桥接DLL。Touchless SDK是一个免费开源的.NET库,对DirectShow进行了简单的封装。使用Touchless能够很方便的在WinForm应用中调用camera。这里分享下如何建立一个调用webcam的barcode reader。html
参考原文:WinForm Barcode Reader with Webcam and C# git
做者:Xiao Linggithub
翻译:yushulxweb
下载Touchless SDK。算法
Dynamsoft Barcode Reader SDK用于barcode识别. 如要想用免费开源的,能够选择ZXing.NET。windows
打开Visual Studio 2015建立一个WinForm工程.less
经过Nuget能够在工程中直接下载安装Dynamsoft Barcode Reader:函数
在引用中添加TouchlessLib.dll:visual-studio
把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");