在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");