lw.PPOCRSharp_GPU_Test paddle_inference v3.3

29 阅读3分钟

效果

NVIDIA GeForce RTX 4060 Laptop GPU 效果

图片

项目

图片

代码

using Newtonsoft.Json;
using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace OCRV5Test
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        const string DllName"lw.PPOCRSharp.dll";

        //初始化
        [DllImport(DllName, EntryPoint = "init", CallingConvention = CallingConvention.Cdecl)]
        public extern static int init(ref IntPtr engine

            , bool use_gpu
            , int gpu_id
            , int gpu_mem

            , int cpu_threads
            , bool enable_mkldnn

            , string det_model_dir
            , int limit_side_len
            , double det_db_thresh
            , double det_db_box_thresh
            , double det_db_unclip_ratio
            , bool use_dilation

            , bool cls
            , bool use_angle_cls
            , string cls_model_dir
            , double cls_thresh
            , double cls_batch_num

            , string rec_model_dir
            , string rec_char_dict_path
            , int rec_batch_num
            , int rec_img_h
            , int rec_img_w
            , int predictor_num

            , StringBuilder msg);

        //识别
        [DllImport(DllName, EntryPoint = "ocr", CallingConvention = CallingConvention.Cdecl)]
        public extern static int ocr(IntPtr engine, IntPtr image, StringBuilder msg, out IntPtr ocr_result, out int ocr_result_len);

        //释放
        [DllImport(DllName, EntryPoint = "destroy", CallingConvention = CallingConvention.Cdecl)]
        public extern static int destroy(IntPtr engine, StringBuilder msg);

        static IntPtr OCREngine;

        private Bitmap bmp;

        private String imgPath = null;

        private List<OCRResult> ltOCRResult;

        private string fileFilter"*.*|*.bmp;*.jpg;*.jpeg;*.tiff;*.tif;*.png";

        private StringBuilder OCRResultInfo = new StringBuilder();
        private StringBuilder OCRResultAllInfo = new StringBuilder();

        Pen pen = new Pen(Brushes.Red, 2f);

        /// <summary>
        /// 选择图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = fileFilter;
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                imgPath = ofd.FileName;
                bmp = new Bitmap(imgPath);
                pictureBox1.Image = bmp;
                richTextBox1.Clear();

                button2_Click(null, null);
            }
        }

        /// <summary>
        /// 识别
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            if (OCREngine == IntPtr.Zero)
            {
                MessageBox.Show("请先初始化!!!");
                return;
            }

            if (imgPath == null)
            {
                MessageBox.Show("请先选择图片!!!");
                return;
            }

            button1.Enabledfalse;
            button2.Enabledfalse;
            richTextBox1.Clear();
            OCRResultInfo.Clear();
            OCRResultAllInfo.Clear();

            Application.DoEvents();
            Mat img = new Mat(imgPath);
            StringBuilder msgTemp = new StringBuilder(128);
            StringBuilder ocrResultStr = new StringBuilder(1024 * 100);

            Stopwatch stopwatch = new Stopwatch();
            stopwatch.Start();

            IntPtr strPtr;
            int ocr_result_len = 0;

            int res = ocr(OCREngine, img.CvPtr, msgTemp, out strPtr, out ocr_result_len);
            img.Dispose();
            byte[] buffer = new byte[ocr_result_len];
            Marshal.Copy(strPtr, buffer, 0, ocr_result_len);
            string ocr_result = Encoding.UTF8.GetString(buffer);
            Marshal.FreeCoTaskMem(strPtr);
            stopwatch.Stop();
            double totalTime = stopwatch.Elapsed.TotalMilliseconds;

            OCRResultAllInfo.AppendLine($"耗时: {totalTime:F2}ms");
            OCRResultAllInfo.AppendLine("---------------------------");

            OCRResultInfo.AppendLine($"耗时: {totalTime:F2}ms");
            OCRResultInfo.AppendLine("---------------------------");

            if (res == 0)
            {
                ltOCRResult = Newtonsoft.Json.JsonConvert.DeserializeObject<List<OCRResult>>(ocr_result);
                OCRResultAllInfo.Append(JsonConvert.SerializeObject(ltOCRResult, Newtonsoft.Json.Formatting.Indented));
                Graphics graphics = Graphics.FromImage(bmp);

                foreach (OCRResult item in ltOCRResult)
                {
                    OCRResultInfo.AppendLine(item.text);
                    System.Drawing.Point[] pt = new System.Drawing.Point[] {
                              new System.Drawing.Point(item.x1, item.y1)
                            , new System.Drawing.Point(item.x2, item.y2)
                            , new System.Drawing.Point(item.x3, item.y3)
                            , new System.Drawing.Point(item.x4, item.y4)
                        };
                    graphics.DrawPolygon(pen, pt);
                }
                graphics.Dispose();

                if (checkBox1.Checked)
                {
                    richTextBox1.Text = OCRResultAllInfo.ToString();
                }
                else
                {
                    richTextBox1.Text = OCRResultInfo.ToString();
                }

                pictureBox1.Image = null;
                pictureBox1.Image = bmp;
            }
            else
            {
                MessageBox.Show("识别失败," + msgTemp.ToString());
            }

            img.Release();
            button1.Enabledtrue;
            button2.Enabledtrue;
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            radioButton1.Checkedtrue;
            chkUseGPU.Checkedtrue;
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            if (checkBox1.Checked)
            {
                richTextBox1.Text = OCRResultAllInfo.ToString();
            }
            else
            {
                richTextBox1.Text = OCRResultInfo.ToString();
            }
        }

        private void radioButton1_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = sender as RadioButton;
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            UnloadModel();
        }

        private void btnDestroy_Click(object sender, EventArgs e)
        {
            UnloadModel();
        }
     

        void UnloadModel()
        {
            if (OCREngine != IntPtr.Zero)
            {
                StringBuilder msgTemp = new StringBuilder(128);
                destroy(OCREngine, msgTemp);

                Console.WriteLine("释放成功:" + msgTemp.ToString());

                OCREngine = IntPtr.Zero;
            }
        }

        private void btnInit_Click(object sender, EventArgs e)
        {
            if (OCREngine != IntPtr.Zero)
            {
                StringBuilder msgTemp = new StringBuilder(128);
                destroy(OCREngine, msgTemp);

                Console.WriteLine("释放成功:" + msgTemp.ToString());

                OCREngine = IntPtr.Zero;

                LoadModel();
            }
            else {

                LoadModel();
            }
        }

        void LoadModel()
        {
            StringBuilder msgTemp = new StringBuilder(128);
            string root_dir = Application.StartupPath + @"\inference";

            bool use_gputrue;

            int gpu_id = 0;
            int gpu_mem = 4000;

            int cpu_threads = 10;
            bool enable_mkldnntrue;

            string det_model_dir"";
            int limit_side_len = 960;
            double det_db_thresh = 0.3;
            double det_db_box_thresh = 0.6;
            double det_db_unclip_ratio = 1.2;
            bool use_dilationfalse;

            bool clsfalse;
            bool use_angle_clstrue;
            string cls_model_dir"inference/ch_ppocr_mobile_v2.0_cls_infer/";
            double cls_thresh = 0.9;
            int cls_batch_num = 1;

            string rec_model_dir"";
            string rec_char_dict_path"inference/ppocrv5_dict.txt";
            int rec_batch_num = 8;
            int rec_img_h = 48;
            int rec_img_w = 320;
            int predictor_num = 4;


            //赋值
            if (chkUseGPU.Checked == true)
            {
                use_gputrue;
            }
            else
            {
                use_gpufalse;
            }

            if (chkEnableMkldnn.Checked == true)
            {
                enable_mkldnntrue;
            }
            else
            {
                enable_mkldnnfalse;
            }

            cpu_threads = Convert.ToInt32(txtcpu_threads.Text.ToString());
            rec_batch_num = Convert.ToInt32(txtrec_batch_num.Text.ToString());
            rec_img_h = Convert.ToInt32(txtrec_img_h.Text.ToString());
            rec_img_w = Convert.ToInt32(txtrec_img_w.Text.ToString());
            predictor_num = Convert.ToInt32(txtpredictor_num.Text.ToString());

            if (radioButton1.Checked)
            {
                det_model_dir"inference/PP-OCRv5_mobile_det_infer/";
                rec_model_dir"inference/PP-OCRv5_mobile_rec_infer/";
            }
            else
            {
                det_model_dir"inference/PP-OCRv5_server_det_infer/";
                rec_model_dir"inference/PP-OCRv5_server_rec_infer/";
            }
            int res = init(ref OCREngine

                        , use_gpu
                        , gpu_id
                        , gpu_mem

                        , cpu_threads
                        , enable_mkldnn

                        , det_model_dir
                        , limit_side_len
                        , det_db_thresh
                        , det_db_box_thresh
                        , det_db_unclip_ratio
                        , use_dilation

                        , cls
                        , use_angle_cls
                        , cls_model_dir
                        , cls_thresh
                        , cls_batch_num

                        , rec_model_dir
                        , rec_char_dict_path
                        , rec_batch_num
                        , rec_img_h
                        , rec_img_w
                        , predictor_num

                        , msgTemp);

            if (res == 0)
            {
                Console.WriteLine("模型加载成功!");
            }
            else
            {
                string msg = msgTemp.ToString();
                Console.WriteLine("模型加载失败," + msg);
            }
        }
    }

}

下载

通过网盘分享的文件:lw.PPOCRSharp_GPU_Test (天天代码码天天) paddle_inference v3.3 链接: pan.baidu.com/s/1pdv7SEjJ… 提取码: 5bf8