C# OCR图片文字识别

发布时间 2023-12-16 16:55:49作者: 四月柳巷
博主这里采用了两种库进行文字识别,一种是“Spire.OCR”,另一种是“PaddleOCRSharp”,这两种库,都可以直接到Nuget中去安装。

 

这里要注意一下,PaddleOCRSharp库是可以直接安装使用的,但是Spire.OCR库在安装后,需要将下载目录“nuget\packages\spire.ocr\1.8.0\runtimes\win-x64\native”中的所有文件都拷贝到exe执行目录下才行,否则将无法正常使用。
在单个字符的识别效果中:PaddleOCRSharp的准确率会比Spire.OCR来的高。

 

准备一张测试图片:

 

演示效果如下:

 

Form1.cs工程源码如下:
C# using PaddleOCRSharp;
using Spire.OCR;

namespace WinFormsApp
{
    public partial class Form1 : Form
    {
        public PaddleOCREngine engine;
        public Form1()
        {
            InitializeComponent();
            engine = CreateOCRParameter();// 这个只能引用一次,否则会出现内存一直增加的问题
        }

        #region SpireOCR
        private void SpireOCR_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            this.openFileDialog1.FileName = "";
            this.openFileDialog1.Filter = "所有文件(*.*)|*.*";
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                OcrScanner scanner = new OcrScanner();
                scanner.Scan(this.openFileDialog1.FileName);
                scanner.Dispose();
                textBox1.Text = "SpireOCR识别结果:\r\n" + scanner.Text.ToString().Split("Evaluation")[0];
            }
        }
        #endregion

        #region PaddleOCRSharp
        public PaddleOCREngine CreateOCRParameter()
        {
            OCRParameter oCRParameter = new OCRParameter();
            oCRParameter.numThread = 6;//预测并发线程数
            oCRParameter.Enable_mkldnn = 1;//web部署该值建议设置为0,否则出错,内存如果使用很大,建议该值也设置为0.
            oCRParameter.cls = 1; //是否执行文字方向分类;默认false
            oCRParameter.det = 1;//是否开启方向检测,用于检测识别180旋转
            oCRParameter.use_angle_cls = 1;//是否开启方向检测,用于检测识别180旋转
            oCRParameter.det_db_score_mode = 1;//是否使用多段线,即文字区域是用多段线还是用矩形,
            oCRParameter.UnClipRatio = 8.6f;
            oCRParameter.MaxSideLen = 960;
            OCRModelConfig config = null;
            PaddleOCREngine engine = new PaddleOCREngine(config, oCRParameter);
            return engine;
        }

        private void PaddleOCRSharp_Click(object sender, EventArgs e)
        {
            textBox1.Text = "";
            this.openFileDialog1.FileName = "";
            this.openFileDialog1.Filter = "所有文件(*.*)|*.*";
            if (this.openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                OCRResult ocrResult = engine.DetectText(this.openFileDialog1.FileName);
                textBox1.Text = "PaddleOCRSharp识别结果:\r\n" + ocrResult.Text;
            }
        }
        #endregion
    }
}
注意:使用SpireOCR时要取消目标平台【首选32位】的勾选,否则会报错。