简介

主流的识别库主要有ZXing.NET和ZBar,OpenCV 4.0后加入了QR码检测和解码功能。本文使用的是ZBar,同等条件下ZBar识别率更高,图片和部分代码参考在C#中使用ZBar识别条形码

使用ZBar

通过NuGet安装ZBar,必须使用1.0.0版本,最新的1.0.2版本无法自动生成相关的dll并且使用不了1.0.0版的dll。
库默认支持netcoreapp3.1,在.NET6环境下也能正常使用,正常情况下输出目录会自动生成lib文件夹和dll文件
注:ZBar 1.0.0在x86平台下可正常运行,但Debug会报错,建议使用x64或AnyCPU。

条码识别:

/// <summary>
/// 条码识别
/// </summary>
static List<ZBar.Symbol> ScanBarCode(string filename)
{
    var bitmap = (Bitmap)Image.FromFile(filename);
    bitmap = MakeGrayscale3(bitmap);
    List<ZBar.Symbol> result = new List<ZBar.Symbol>();
    using (var scanner = new ZBar.ImageScanner())
    {
        var symbols = scanner.Scan(bitmap);
        if (symbols != null && symbols.Count > 0)
        {
            result.AddRange(symbols);
        }
    }
    return result;
}

/// <summary>
/// 处理图片灰度
/// </summary>
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;
}

使用方法:

Console.WriteLine(ZBar.ZBar.Version);
var symbols = ScanBarCode("426301-20160127111209879-611759974.jpg");
string result = string.Empty;
symbols.ForEach(s => Console.WriteLine($"条码类型:{s.Type} 条码内容:{s.Data} 条码质量:{s.Quality}"));
Console.ReadKey();

扩展:其它条码识别库

在C#平台下还有一个ThoughtWorks.QRCode库也支持条码解析,具体效果还没有测试。原始代码最后的版本是在2015年,后面的版本只是将库做了个标准版,按自己的需求选择版本:

识别库使用方法参考:C#使用zxing,zbar,thoughtworkQRcode解析二维码,附源代码

扩展:开源扫码软件

推荐一个C# WPF 原生开发的在电脑上识别条码的工具软件QrCodeScanner,功能如下:

  • 支持四种模式:截图识别 + 摄像头识别 + 本地图片识别 + 作为扫描枪使用
  • 支持ZbarZxing两种主流引擎
  • 支持多码同扫
  • 支持Material Design缤纷主题色与暗黑模式
  • 独创的扫描枪模式
    image

附件

内容来源于网络如有侵权请私信删除

文章来源: 博客园

原文链接: https://www.cnblogs.com/timefiles/p/17573031.html

你还没有登录,请先登录注册
  • 还没有人评论,欢迎说说您的想法!