C# 使用 PaddleOCRSharp 识别 图片中的文字、 使用QRCoder生成二维码

发布时间 2023-08-25 09:49:34作者: 我本梁人

使用PaddleOCRSharp识别图片中的文字

  在只用PaddleOCRSharp之前用过另外一种识别:Tesseract。它识别速度是非常快的,但是准确率堪忧,而且使用的时候需要区分语言,这里权当一些经验交流,不是说Tesseract不好。

PaddleOCRSharp资料汇总:

开源工具开发者博客:https://www.cnblogs.com/raoyutian/p/15938913.html
GitHub:https://github.com/raoyutian/PaddleOCRSharp
Gitee:https://gitee.com/raoyutian/paddle-ocrsharp


  如何使用PaddleOCRSharp在GitHub源码中有一个PaddleOCRDemo项目是有完整的代码实现,里面功能比较齐全

VS版本:VS2022,使用其他版本无法加载源码
而且作者也写了一篇博客 https://www.cnblogs.com/raoyutian/p/15912470.html。

1.将源码编译成对应的.Net 版本引入到项目中

  在作者给出的示例中是直接使用的Nuget包进行的管理,我在尝试的时候没有使用成功,所以采用了引用Dll的方式。

2. 初始化PaddleOCREngine

 ```  
        private PaddleOCREngine engine;
        //自带轻量版中英文模型V4模型
        OCRModelConfig config = null;
        //OCR参数
        OCRParameter oCRParameter = new OCRParameter();
        oCRParameter.cpu_math_library_num_threads = 10;//预测并发线程数
        oCRParameter.enable_mkldnn = true;//web部署该值建议设置为0,否则出错,内存如果使用很大,建议该值也设置为0.
        oCRParameter.cls = false; //是否执行文字方向分类;默认false
        oCRParameter.det = true;//是否开启方向检测,用于检测识别180旋转
        oCRParameter.use_angle_cls = false;//是否开启方向检测,用于检测识别180旋转
        oCRParameter.det_db_score_mode = true;//是否使用多段线,即文字区域是用多段线还是用矩形,
        oCRParameter.max_side_len = 1500;
        oCRParameter.rec_img_h = 48;
        oCRParameter.rec_img_w = 320;
        oCRParameter.det_db_thresh = 0.3f;
        oCRParameter.det_db_box_thresh = 0.618f;

        //初始化OCR引擎
        engine = new PaddleOCREngine(config, oCRParameter);

        //模型配置,使用默认值
        StructureModelConfig structureModelConfig = null;
        //表格识别参数配置,使用默认值
        StructureParameter structureParameter = new StructureParameter();
        structengine = new PaddleStructureEngine(structureModelConfig, structureParameter);

3. 调用DetectText识别文字

OCRResult ocrResult = engine.DetectText(imagebyte);

4. 使用QRCoder生成二维码

        public static Bitmap GetQRCodeImage(string qrCode)
        {    //获取含水印的二维码图像对象
            QRCodeGenerator generator = new QRCodeGenerator();
            QRCodeData data = generator.CreateQrCode(qrCode, QRCodeGenerator.ECCLevel.M);    //qrCode是二维码内容,ECCLevel用于设置容错率
            QRCode code = new QRCode(data);
            //Bitmap icon = new Bitmap("水印文件路径");
            //定义二维码中央水印图标,文件路径一定要是绝对路径,如果是Web工程,可用Server.MapPath函数获取绝对路径
            //icon:由于这里没水印图片,所以用null
            Bitmap qrImage = code.GetGraphic(10, Color.Black, Color.White,null, 15, 6, true);
            //获得含水印的二维码图像信息,如不需要水印可以调用另外函数:Bitmap qrImage = code.GetGraphic(10);
            return qrImage;
        }