一.識別庫blog
二.從一張圖片中提取多個條形碼three
三.注意事項圖片
從博客園學了不少,本着分享的目的,但願後來者遇到相似問題時,沒必要重複造輪子,早點下班回家^-^。ip
目前主流的識別庫主要有ZXing.NET和ZBar,這裏我使用的是ZBar,ZXing.NET也試過,同等條件下,識別率不高。ci
ZBar相關類庫包括:libzbar.dll,libzbar-cil.dll,libiconv-2.dll;get
很奇怪爲何不能直接引用libzbar.dll,實際使用時引用的是libzbar-cil.dll,libiconv-2.dll是libzbar-cil.dll用來映射libzbar.dll的。源碼
ZBar識別庫包含在源碼中,文末可直接下載。博客
先上截圖:string
須要提取條形碼的圖片:it
識別結果
主要代碼:
/// <summary> /// 條碼識別 /// </summary> private void ScanBarCode(string fileName) { DateTime now = DateTime.Now; Image primaryImage = Image.FromFile(fileName); Bitmap pImg = MakeGrayscale3((Bitmap)primaryImage); using (ZBar.ImageScanner scanner = new ZBar.ImageScanner()) { scanner.SetConfiguration(ZBar.SymbolType.None, ZBar.Config.Enable, 0); scanner.SetConfiguration(ZBar.SymbolType.CODE39, ZBar.Config.Enable, 1); scanner.SetConfiguration(ZBar.SymbolType.CODE128, ZBar.Config.Enable, 1); List<ZBar.Symbol> symbols = new List<ZBar.Symbol>(); symbols = scanner.Scan((Image)pImg); if (symbols != null && symbols.Count > 0) { string result = string.Empty; symbols.ForEach(s => result += "條碼內容:" + s.Data + " 條碼質量:" + s.Quality + Environment.NewLine); MessageBox.Show(result); } } } /// <summary> /// 處理圖片灰度 /// </summary> /// <param name="original"></param> /// <returns></returns> public static Bitmap MakeGrayscale3(Bitmap original) { //create a blank bitmap the same size as original Bitmap newBitmap = new Bitmap(original.Width, original.Height); //get a graphics object from the new image Graphics g = Graphics.FromImage(newBitmap); //create the grayscale ColorMatrix System.Drawing.Imaging.ColorMatrix colorMatrix = new System.Drawing.Imaging.ColorMatrix( new float[][] { new float[] {.3f, .3f, .3f, 0, 0}, new float[] {.59f, .59f, .59f, 0, 0}, new float[] {.11f, .11f, .11f, 0, 0}, new float[] {0, 0, 0, 1, 0}, new float[] {0, 0, 0, 0, 1} }); //create some image attributes ImageAttributes attributes = new ImageAttributes(); //set the color matrix attribute attributes.SetColorMatrix(colorMatrix); //draw the original image on the new image //using the grayscale color matrix g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height), 0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes); //dispose the Graphics object g.Dispose(); return newBitmap; }
若是條碼識別率不高,考慮是圖片的DPI不夠。個人項目初期使用的是500萬像素的高拍儀,拍出來的圖片識別率始終不高,DPI爲96。後來更換爲800萬像素的高拍儀,DPI爲120,識別率從60%直接上升到95%+。固然,也須要對圖片作一些裁剪。另外,灰度處理是必須的,可減小拍攝照片時反光引發的識別率不高問題。
源碼下載:條碼識別