C#使用ZBar實(shí)現(xiàn)識(shí)別條形碼
一.識(shí)別庫
目前主流的識(shí)別庫主要有ZXing.NET和ZBar,這里我使用的是ZBar,ZXing.NET也試過,同等條件下,識(shí)別率不高。
ZBar相關(guān)類庫包括:libzbar.dll,libzbar-cil.dll,libiconv-2.dll;
很奇怪為什么不能直接引用libzbar.dll,實(shí)際使用時(shí)引用的是libzbar-cil.dll,libiconv-2.dll是libzbar-cil.dll用來映射libzbar.dll的。
二.從一張圖片中提取多個(gè)條形碼
先上截圖:
需要提取條形碼的圖片:

識(shí)別結(jié)果

三.主要代碼
/// <summary>
/// 條碼識(shí)別
/// </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 += "條碼內(nèi)容:" + s.Data + " 條碼質(zhì)量:" + 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;
}四.注意事項(xiàng)
如果條碼識(shí)別率不高,考慮是圖片的DPI不夠。我的項(xiàng)目初期使用的是500萬像素的高拍儀,拍出來的圖片識(shí)別率始終不高,DPI為96。后來更換為800萬像素的高拍儀,DPI為120,識(shí)別率從60%直接上升到95%+。當(dāng)然,也需要對(duì)圖片做一些裁剪。另外,灰度處理是必須的,可減少拍攝照片時(shí)反光引起的識(shí)別率不高問題。
到此這篇關(guān)于C#使用ZBar實(shí)現(xiàn)識(shí)別條形碼的文章就介紹到這了,更多相關(guān)C# ZBar識(shí)別條形碼內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#實(shí)現(xiàn)將選中復(fù)選框的信息返回給用戶的方法
這篇文章主要介紹了C#實(shí)現(xiàn)將選中復(fù)選框的信息返回給用戶的方法,涉及C#針對(duì)復(fù)選框操作的相關(guān)技巧,需要的朋友可以參考下2015-06-06
跳一跳自動(dòng)跳躍C#代碼實(shí)現(xiàn)
這篇文章主要為大家詳細(xì)介紹了跳一跳自動(dòng)跳躍C#代碼實(shí)現(xiàn),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
C# WebService發(fā)布以及IIS發(fā)布
這篇文章主要介紹了C# WebService發(fā)布以及IIS發(fā)布的相關(guān)資料,感興趣的小伙伴們可以參考一下2016-07-07

