C#中OCR的靠譜方式

法宝發表於2024-05-08

https://www.cnblogs.com/xuexz/p/17905030.html

注意:使用SpireOCR時要取消目標平臺【首選32位】的勾選,否則會報錯。

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
    }
}

相關文章