PaddleSharpAPI.cs 20.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
using log4net;
using log4net.Util;
using Model;
using PaddleOCRSharp;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;

namespace paddleOCR
{
    internal class PaddleSharpAPI
    {
        static PaddleOCREngine engine;
        static string baseDir = ".\\LabelOut\\";

        public static void Init()
        {
            //自带轻量版中英文模型V3模型
            OCRModelConfig config = null;

            //服务器中英文模型
            //OCRModelConfig config = new OCRModelConfig();
            //string root = System.IO.Path.GetDirectoryName(typeof(OCRModelConfig).Assembly.Location);
            //string modelPathroot = root + @"\inferenceserver";
            //config.det_infer = modelPathroot + @"\ch_ppocr_server_v2.0_det_infer";
            //config.cls_infer = modelPathroot + @"\ch_ppocr_mobile_v2.0_cls_infer";
            //config.rec_infer = modelPathroot + @"\ch_ppocr_server_v2.0_rec_infer";
            //config.keys = modelPathroot + @"\ppocr_keys.txt";

            //英文和数字模型V3
            //OCRModelConfig config = new OCRModelConfig();
            //string root = System.IO.Path.GetDirectoryName(typeof(OCRModelConfig).Assembly.Location);
            //string modelPathroot = root + @"\en_v3";
            //config.det_infer = modelPathroot + @"\en_PP-OCRv3_det_infer";
            //config.cls_infer = modelPathroot + @"\ch_ppocr_mobile_v2.0_cls_infer";
            //config.rec_infer = modelPathroot + @"\en_PP-OCRv3_rec_infer";
            //config.keys = modelPathroot + @"\en_dict.txt";


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

        }
        static ILog log = VisionAPI.log;
        static System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        public static bool OCRHandle(string imgPath, out string result)
        {
            result = "";
            sw.Restart();
            if (string.IsNullOrEmpty(imgPath))
            {
                return false;
            }
            if (Directory.Exists(baseDir))
            {
                Directory.Delete(baseDir, true);
            }
            Directory.CreateDirectory(baseDir);


            EyemImage image = new EyemImage();
            EyemImage tpDstImg = new EyemImage();
            int flag;
            log.Info($"准备读取图像:{imgPath}");
            flag = VisionAPI.eyemImageRead(imgPath, -1, out image);
            log.Info($"图像通道为:{image.iChannels}");
            log.Info($"读取图像:{imgPath},rtnCode={flag}");
            ///实例分割
            ///
            {
                RotateBox container = new RotateBox();
                flag = VisionAPI.eyemNNInstanceSegment(image, 0.15f, ref container, out tpDstImg);
                log.Info($"标签分割完成,rtncode={flag}");
                Bitmap b = VisionAPI.eyemCvtToBitmap(tpDstImg);
                log.Info($"转换为Bitmap");
                b?.Save($"labelSplit.jpg", ImageFormat.Jpeg);
                log.Info($"保存分割结果图:labelSplit.jpg");
                VisionAPI.eyemImageFree(ref tpDstImg);
                for (int i = 0; i < 25; i++)
                {

                    EyemImage tpDstImg1 = new EyemImage();
                    if (i < container.p1.Length && container.p1[i].iX != 0)
                    {
                        flag = VisionAPI.eyemAchvRotateImage(image, container.p1[i], container.p2[i], container.p3[i], container.p4[i], out tpDstImg1);
                        //if (flag == 0)
                        {
                            if (!Directory.Exists($"{baseDir}label{i}"))
                                Directory.CreateDirectory($"{baseDir}label{i}");
                            Bitmap lbl = VisionAPI.eyemCvtToBitmap(tpDstImg1);
                            lbl?.Save($"{baseDir}label{i}\\1.jpg", ImageFormat.Jpeg);
                            lbl?.RotateFlip(RotateFlipType.Rotate180FlipNone);
                            lbl?.Save($"{baseDir}label{i}\\2.jpg", ImageFormat.Jpeg);
                            log.Info($"获取标签图像并保存:{baseDir}label{i}");
                        }
                        VisionAPI.eyemImageFree(ref tpDstImg1);
                    }

                }
                VisionAPI.eyemImageFree(ref image);
            }
            log.Info($"分隔标签耗时:{sw.ElapsedMilliseconds}ms");
            sw.Restart();
            DirectoryInfo directoryInfo = new DirectoryInfo(baseDir);
            var files = directoryInfo.GetDirectories();
            if (files != null && files.Length == 0)
            {
                if (!Directory.Exists($"{baseDir}label"))
                    Directory.CreateDirectory($"{baseDir}label");
                log.Info($"无分割的标签,将原图传入名为label.jpg");
                byte[] bytes;
                using (FileStream fs = new FileStream(imgPath, FileMode.Open))
                {
                    bytes = new byte[fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                }
                MemoryStream memoryStream = new MemoryStream(bytes);
                Bitmap bitmap = new Bitmap(memoryStream);
                bitmap.Save($"{baseDir}label\\label.jpg");
            }
            log.Info($"开始OCR识别");
            StringBuilder stringBuilder = new StringBuilder();
            foreach (var dir in directoryInfo.GetDirectories())
            {
                float maxScore = 0f;
                List<TextBlock> list = new List<TextBlock>();
                foreach (var item in dir.GetFiles())
                {
                    try
                    {
                        float score = 0f;
                        var imagebyte = File.ReadAllBytes(item.FullName);
                        var res = engine.DetectText(imagebyte);
                        StringBuilder sb = new StringBuilder();
                        res.TextBlocks.ForEach(s => { score += s.Score; sb.AppendLine(s.Text); });
                        //foreach (var item in ocrResult.TextBlocks)
                        //{
                        //    using (Graphics g = Graphics.FromImage(bitmap))
                        //    {
                        //        g.DrawPolygon(new Pen(Brushes.Red, 2), item.BoxPoints.Select(x => new PointF() { X = x.X, Y = x.Y }).ToArray());
                        //    }
                        //}                 
                        log.Info($"【{item.FullName}】结果:【{score}】【{sb.ToString().Replace("\r", "").Replace("\n", ";")}】");
                        if (score > maxScore)
                        {
                            maxScore = score;
                            list = res.TextBlocks;
                        }
                    }
                    catch (Exception ex)
                    {
                        log.Error($"{item.FullName}异常", ex);
                    }

                }
                log.Info($"使用识别分数【{maxScore}】");
                Dictionary<int, List<TextBlock>> lines = new Dictionary<int, List<TextBlock>>();
                int line = 0, idx = 0, i = 1;
                while (idx < list.Count)
                {
                    while (i < list.Count)
                    {
                        if (IsInSameLine(list[idx], list[i]))
                        {
                            if (lines.ContainsKey(line))
                            {
                                lines[line].Add(list[i]);
                            }
                            else
                            {
                                lines.Add(line, new List<TextBlock> { list[i] });
                            }
                            i++;
                        }
                        else
                        {
                            if (lines.ContainsKey(line))
                            {
                                lines[line].Add(list[idx]);
                            }
                            else
                            {
                                lines[line] = new List<TextBlock> { list[idx] };
                            }
                            line++;
                            idx = i;
                            i++;
                        }
                    }
                    if (i >= list.Count)
                    {
                        if (lines.ContainsKey(line))
                        {
                            lines[line].Add(list[idx]);
                        }
                        else
                        {
                            lines[line] = new List<TextBlock> { list[idx] };
                        }
                        break;
                    }


                }
                foreach (var lineTxt in lines)
                {
                    lineTxt.Value.Sort(delegate (TextBlock x1, TextBlock x2) { if (x1.BoxPoints[0].X > x2.BoxPoints[0].X) return 1; else return -1; });
                    foreach (var text in lineTxt.Value)
                    {
                        log.Info($"行{lineTxt.Key}【{text.ToString()}】");
                        stringBuilder.Append(text.Text);
                    }
                    stringBuilder.AppendLine();
                }
            }
            log.Info($"OCR识别完成");
            sw.Stop();
            log.Info("识别耗时:" + sw.ElapsedMilliseconds.ToString() + "ms");
            string[] strs = stringBuilder.ToString().Replace(":\r", ":").Replace("\r", "").Split('\n');
            foreach (string str in strs)
            {
                if (string.IsNullOrEmpty(str)) continue;
                result += str + ";";
            }
            if (result.EndsWith(";"))
            {
                result = result.Substring(0, result.Length - 1);
            }
            log.Info($"识别结果[{strs.Length}]:" + result);
            return true;
        }
        /// <summary>
        /// 同一行间隔小于多少像素可以合并
        /// </summary>
        //int intervalPixel = ConfigHelper.Config.Get("IntervalPixelInSameLine", 60);
        static bool IsInSameLine(TextBlock t1, TextBlock t2)
        {
            //同一行间隔小于多少像素可以合并
            int intervalPixel = ConfigHelper.Config.Get("IntervalPixelInSameLine", 20);
            int p1y1 = t1.BoxPoints[0].Y;
            int p1y2 = t1.BoxPoints[1].Y;
            int p1y3 = t1.BoxPoints[2].Y;
            int p1y4 = t1.BoxPoints[3].Y;

            int p2y1 = t2.BoxPoints[0].Y;
            int p2y2 = t2.BoxPoints[1].Y;
            int p2y3 = t2.BoxPoints[2].Y;
            int p2y4 = t2.BoxPoints[3].Y;


            int p1x0 = t1.BoxPoints[0].X;
            int p1x1 = t1.BoxPoints[1].X;
            int p2x0 = t2.BoxPoints[0].X;
            int p2x1 = t2.BoxPoints[1].X;
            if (p1x0 < p2x0)//t1在左侧
            {

                if (p1y2 > p2y4 || p1y3 < p2y1) return false;
                if (Math.Abs(p1x1 - p2x0) > intervalPixel) return false;
                else
                    return true;


            }
            else
            {
                if (p2y2 > p1y4 || p2y3 < p1y1) return false;
                if (Math.Abs(p2x1 - p1x0) > intervalPixel) return false;
                else
                    return true;
            }
        }

        public static bool OCRHandleRewrite(string imgPath, out string result)
        {
            result = "";
            sw.Restart();
            if (string.IsNullOrEmpty(imgPath))
            {
                return false;
            }
            if (Directory.Exists(baseDir))
            {
                Directory.Delete(baseDir, true);
            }
            Directory.CreateDirectory(baseDir);
            EyemImage image = new EyemImage();
            EyemImage tpDstImg = new EyemImage();
            int flag;
            log.Info($"OCRHandleRewrite:准备读取图像:{imgPath}");
            flag = VisionAPI.eyemImageRead(imgPath, -1, out image);
            log.Info($"OCRHandleRewrite:读取图像:{imgPath},rtnCode={flag},通道数为{image.iChannels}");
            ///实例分割
            {
                RotateBox container = new RotateBox();
                flag = VisionAPI.eyemNNInstanceSegment(image, 0.15f, ref container, out tpDstImg);
                log.Info($"OCRHandleRewrite:标签分割完成,rtncode={flag}");
                Bitmap b = VisionAPI.eyemCvtToBitmap(tpDstImg);
                log.Info($"OCRHandleRewrite:转换为Bitmap");
                b?.Save($"labelSplit.jpg", ImageFormat.Jpeg);
                log.Info($"OCRHandleRewrite:保存分割结果图:labelSplit.jpg");
                VisionAPI.eyemImageFree(ref tpDstImg);
                for (int i = 0; i < 25; i++)
                {
                    EyemImage tpDstImg1 = new EyemImage();
                    if (i < container.p1.Length && container.p1[i].iX != 0)
                    {
                        flag = VisionAPI.eyemAchvRotateImage(image, container.p1[i], container.p2[i], container.p3[i], container.p4[i], out tpDstImg1);
                        //if (flag == 0)
                        {
                            if (!Directory.Exists($"{baseDir}label{i}"))
                                Directory.CreateDirectory($"{baseDir}label{i}");
                            Bitmap lbl = VisionAPI.eyemCvtToBitmap(tpDstImg1);
                            lbl?.Save($"{baseDir}label{i}\\1.jpg", ImageFormat.Jpeg);
                            lbl?.RotateFlip(RotateFlipType.Rotate180FlipNone);
                            lbl?.Save($"{baseDir}label{i}\\2.jpg", ImageFormat.Jpeg);
                            log.Info($"OCRHandleRewrite:获取标签图像并保存:{baseDir}label{i}");
                        }
                        VisionAPI.eyemImageFree(ref tpDstImg1);
                    }
                }
                VisionAPI.eyemImageFree(ref image);
            }
            log.Info($"OCRHandleRewrite:分隔标签耗时:{sw.ElapsedMilliseconds}ms");
            sw.Restart();
            DirectoryInfo directoryInfo = new DirectoryInfo(baseDir);
            var files = directoryInfo.GetDirectories();
            if (files != null && files.Length == 0)
            {
                if (!Directory.Exists($"{baseDir}label"))
                    Directory.CreateDirectory($"{baseDir}label");
                log.Info($"OCRHandleRewrite:无分割的标签,将原图传入名为label.jpg");
                byte[] bytes;
                using (FileStream fs = new FileStream(imgPath, FileMode.Open))
                {
                    bytes = new byte[fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                }
                MemoryStream memoryStream = new MemoryStream(bytes);
                Bitmap bitmap = new Bitmap(memoryStream);
                bitmap.Save($"{baseDir}label\\label.jpg");
            }
            log.Info($"OCRHandleRewrite:开始OCR识别");
            StringBuilder stringBuilder = new StringBuilder();
            List<string> stringLists = new List<string>();
            foreach (var dir in directoryInfo.GetDirectories())
            {
                float maxScore = 0f;
                List<TextBlock> list = new List<TextBlock>();
                foreach (var item in dir.GetFiles())
                {
                    float score = 0f;
                    var imagebyte = File.ReadAllBytes(item.FullName);
                    var res = engine.DetectText(imagebyte);
                    StringBuilder sb = new StringBuilder();
                    res.TextBlocks.ForEach(s => { score += s.Score; sb.AppendLine(s.Text); });
                    //Bitmap bitmap = new Bitmap(item.FullName);
                    //foreach (var items in res.TextBlocks)
                    //{
                    //    using (Graphics g = Graphics.FromImage(bitmap))
                    //    {
                    //        g.DrawPolygon(new Pen(Brushes.Red, 2), items.BoxPoints.Select(x => new PointF() { X = x.X, Y = x.Y }).ToArray());
                    //    }
                    //}
                    //// 保存带有绘制边界框的图像
                    //bitmap.Save("C:\\Users\\BOO\\Desktop\\项目\\ns100\\NS100\\paddleOCR\\bin\\Debug\\LabelOut\\label0\\1_with_boxes.jpg");
                    //// 最后不要忘记释放Bitmap对象
                    //bitmap.Dispose();
                    log.Info($"OCRHandleRewrite:【{item.FullName}】结果:【{score}】【{sb.ToString().Replace("\r", "").Replace("\n", ";")}】");
                    if (score > maxScore)
                    {
                        maxScore = score;
                        list = res.TextBlocks;
                    }
                }
                #region ocr文字统一一行   
                //矩形中心点的相差阈值
                int threshold = int.Parse(ConfigHelper.Config.Get("paddleOcr_RowThreshold", "10"));
                List<StringIntPair> mergedTextlist = new List<StringIntPair>();
                double lastYAvg = 0;
                foreach (var entity in list)
                {
                    double avgY = entity.BoxPoints.Average(a => a.Y);
                    if (Math.Abs(lastYAvg - avgY) < threshold)
                    {
                        mergedTextlist.Add(new StringIntPair(entity.Text, entity.BoxPoints[0].X));
                    }
                    else
                    {
                        if (mergedTextlist.Count != 0)
                        {
                            var stringdata = mergedTextlist.OrderBy(a => a.IntValue);
                            string str = "";
                            foreach (var item in stringdata)
                            {
                                str += item.StringValue + " ";
                            }
                            stringLists.Add(str);
                            mergedTextlist.Clear();
                        }
                        mergedTextlist.Add(new StringIntPair(entity.Text, entity.BoxPoints[0].X));
                    }
                    lastYAvg = avgY;
                }
                if (mergedTextlist.Count != 0)
                {
                    var stringdata = mergedTextlist.OrderBy(a => a.IntValue);
                    string str = "";
                    foreach (var item in stringdata)
                    {
                        str += item.StringValue + " ";
                    }
                    stringLists.Add(str);
                    mergedTextlist.Clear();
                }
                log.Info($"OCRHandleRewrite:矩形中心点相差阈值为:{threshold}");
                #endregion
                log.Info($"OCRHandleRewrite:使用识别分数【{maxScore}】");
            }
            log.Info($"OCRHandleRewrite:OCR识别完成");
            sw.Stop();
            log.Info("OCRHandleRewrite:识别耗时:" + sw.ElapsedMilliseconds.ToString() + "ms");
            string[] strs = stringLists.ToArray();
            foreach (string str in strs)
            {
                if (string.IsNullOrWhiteSpace(str)) continue;
                result += str + ";";
            }
            if (result.EndsWith(";"))
            {
                result = result.Substring(0, result.Length - 1);
            }
            log.Info($"OCRHandleRewrite:识别结果[{strs.Length}]:" + result);
            return true;
        }
    }
}