首页 最新 热门 推荐

  • 首页
  • 最新
  • 热门
  • 推荐

C# AI鉴图宝 利用OCR技术对违规图片进行判别

  • 25-02-19 03:41
  • 3912
  • 7789
blog.csdn.net

目录

效果

项目

代码

下载


效果

项目

代码

using Aspose.Cells;
using NLog;
using OpenCvSharp;
using OpenVINO.OCRService;
using Sdcb.OpenVINO;
using Sdcb.OpenVINO.PaddleOCR;
using Sdcb.OpenVINO.PaddleOCR.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace OpenVINO.OCR
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
            NLog.Windows.Forms.RichTextBoxTarget.ReInitializeAllTextboxes(this);
        }

        String startupPath;
        private string excelFileFilter = "表格|*.xlsx;*.xls;";
        private Logger log = NLog.LogManager.GetCurrentClassLogger();
        CancellationTokenSource cts;

        ConcurrentQueue ltImgInfo = new ConcurrentQueue();
        ConcurrentQueue matQueue = new ConcurrentQueue();

        bool saveImg = false;
        bool saveOcr = false;

        int ocrNum = 0;//完成OCR识别的数量
        int totalCount = 0;//图片总数量
        int downloadCount = 0;//图片下载数量
        int vioIDCount = 0;//违规ID;

        private void frmMain_Load(object sender, EventArgs e)
        {
            DateTime limitTime = new DateTime(2024, 08, 30, 00, 00, 00);
            //测试使用
            if (DateTime.Now > limitTime)
            {
                MessageBox.Show("此软件试用期已过");
                Application.Exit();
            }

            //初始化
            startupPath = System.Windows.Forms.Application.StartupPath;


            string detectionModelDir = startupPath + "\\inference\\ch_PP-OCRv3_det_infer";
            string classificationModelDir = startupPath + "\\inference\\ch_ppocr_mobile_v2.0_cls_infer";
            string recognitionModelDir = startupPath + "\\inference\\ch_PP-OCRv3_rec_infer";
            string labelFilePath = startupPath + "\\inference\\ppocr_keys.txt";

            FullOcrModel model = FullOcrModel.FromDirectory(detectionModelDir, classificationModelDir, recognitionModelDir, labelFilePath, ModelVersion.V3);

            PaddleOcrOptions paddleOcrOptions = new PaddleOcrOptions();
            paddleOcrOptions.DetectionDeviceOptions = new DeviceOptions("CPU");
            paddleOcrOptions.DetectionStaticSize = new OpenCvSharp.Size(800, 800);
            paddleOcrOptions.RecognitionStaticWidth = 512;

            Program.paddleOcr = new PaddleOcrAll(model, paddleOcrOptions);
            Program.paddleOcr.Detector.UnclipRatio = 1.5f;
            Program.paddleOcr.AllowRotateDetection = true;    /* 允许识别有角度的文字 */
            Program.paddleOcr.Enable180Classification = false; /* 允许识别旋转角度大于90度的文字 */

            ServicePointManager.Expect100Continue = false;
            ServicePointManager.DefaultConnectionLimit = 512;

            //加载违禁词
            Common.ltRuleContains.Clear();
            Common.ltRuleTel.Clear();

            string ruleContainsPath = "rules\\rule_contains.txt";
            if (File.Exists(ruleContainsPath))
            {
                Common.ltRuleContains = File.ReadAllLines(ruleContainsPath).ToList();

            }
            StringBuilder sb = new StringBuilder();
            foreach (var item in Common.ltRuleContains)
            {
                sb.AppendLine(item);
            }
            log.Info("rule_contains.txt---->包含" + Common.ltRuleContains.Count() + "个违禁词,内容如下:\r\n" + sb.ToString());


            string ruleTelPath = "rules\\rule_tel.txt";
            if (File.Exists(ruleTelPath))
            {
                foreach (var item in File.ReadAllLines(ruleTelPath))
                {
                    Common.ltRuleTel.Add(item.ToLower());
                }
            }

            sb.Clear();
            foreach (var item in Common.ltRuleTel)
            {
                sb.AppendLine(item);
            }
            log.Info("rule_tel.txt---->包含" + Common.ltRuleTel.Count() + "个号码前缀,内容如下:\r\n" + sb.ToString());

        }

        ///


        /// 选择表格
        ///

        ///
        ///
        private void button2_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Filter = excelFileFilter;
                if (ofd.ShowDialog() != DialogResult.OK) return;

                log.Info("解析中……");
                Application.DoEvents();

                Stopwatch sw = new Stopwatch();
                sw.Start();  //开始计时

                string excelPath = ofd.FileName;

                Workbook workbook = new Workbook(excelPath);
                Cells cells = workbook.Worksheets[0].Cells;
                System.Data.DataTable dataTable1 = cells.ExportDataTable(1, 0, cells.MaxDataRow, cells.MaxColumn + 1);//noneTitle

                ltImgInfo = new ConcurrentQueue();

                //遍历
                ImgInfo temp;
                int imgCount = 0;
                foreach (DataRow row in dataTable1.Rows)
                {
                    temp = new ImgInfo();
                    temp.id = row[0].ToString();
                    temp.title = row[1].ToString();

                    List list = new List();
                    for (int i = 2; i < cells.MaxColumn + 1; i++)
                    {

                        string tempStr = row[i].ToString();
                        if (!string.IsNullOrEmpty(tempStr))
                        {
                            if (i >= 7)
                            {
                                List ltScrUrlTemp = Common.GetScrUrl(tempStr);
                                if (ltScrUrlTemp.Count > 0)
                                {
                                    foreach (var item in ltScrUrlTemp)
                                    {

                                        MatInfo matInfo = new MatInfo();
                                        matInfo.url = item;
                                        list.Add(matInfo);
                                    }
                                }
                            }
                            else
                            {
                                MatInfo matInfo = new MatInfo();
                                matInfo.url = tempStr;
                                list.Add(matInfo);
                            }
                        }
                    }
                    temp.images = list;
                    imgCount = imgCount + list.Count();
                    ltImgInfo.Enqueue(temp);

                    //for test
                    //if (ltImgInfo.Count()>10)
                    //{
                    //    break;
                    //}
                }
                log.Info("解析完毕,一共[" + ltImgInfo.Count + "]条记录,[" + imgCount + "]张图片,耗时:" + sw.ElapsedMilliseconds + "毫秒");
            }
            catch (Exception ex)
            {
                log.Error("解析表格异常:" + ex.Message);
                MessageBox.Show("解析表格异常:" + ex.Message);
            }
        }

        void ShowCostTime(string total, string ocrNum, string downloadCount, long time, int vioIDCount)
        {
            txtTotal.Invoke(new Action(() =>
            {
                TimeSpan ts = TimeSpan.FromMilliseconds(time);
                txtTotal.Text = string.Format("下载完成:{0}/{1},识别完成:{2}/{3},违规ID数量:{5},用时:{4}"
                    , downloadCount
                    , total
                    , ocrNum
                    , total
                    , ts.ToString()
                    , vioIDCount
                    );
            }));
        }

        ///


        /// 下载识别
        ///

        ///
        ///
        private void button1_Click(object sender, EventArgs e)
        {
            if (ltImgInfo.Count == 0)
            {
                MessageBox.Show("请先选择表格!");
                return;
            }

            DialogResult result = MessageBox.Show("确认开始下载识别?此操作会清空上一次的数据,请注意备份!", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                log.Info("确认开始下载识别!");
            }
            else
            {
                log.Info("取消开始下载识别!");
                return;
            }

            if (!Directory.Exists("img"))
            {
                Directory.CreateDirectory("img");
            }

            if (!Directory.Exists("ocr_result"))
            {
                Directory.CreateDirectory("ocr_result");
            }

            if (!Directory.Exists("result"))
            {
                Directory.CreateDirectory("result");
            }

            if (!Directory.Exists("result//img"))
            {
                Directory.CreateDirectory("result//img");
            }

            //清空结果
            File.WriteAllText("result//result.txt", "");
            File.WriteAllText("result//result_detail.txt", "");
            // 清空文件夹中的文件
            foreach (string filePath in Directory.GetFiles("result", "*", SearchOption.AllDirectories))
            {
                File.Delete(filePath);
            }

            // 写入列标题
            File.WriteAllText("result//result.txt", "id\ttitel\tcontent\r\n");

            btnStop.Enabled = true;
            btnStart.Enabled = false;
            chkSaveImg.Enabled = false;
            chkSaveOcr.Enabled = false;

            if (chkSaveImg.Checked)
            {
                saveImg = true;
            }
            else
            {
                saveImg = false;
            }

            if (chkSaveOcr.Checked)
            {
                saveOcr = true;
            }
            else
            {
                saveOcr = false;
            }

            Application.DoEvents();

            cts = new CancellationTokenSource();

            Stopwatch total = new Stopwatch();
            total.Start();  //开始计时

            // 清空队列
            matQueue = new ConcurrentQueue();
            //while (!matQueue.IsEmpty)
            //{
            //    matQueue.TryDequeue(out _);
            //}


            ocrNum = 0;//完成OCR识别的数量
            totalCount = ltImgInfo.Count();//图片总数量
            downloadCount = 0;

            //下载线程
            int downloadThreadNum = 2;
            for (int i = 0; i < downloadThreadNum; i++)
            {
                Task.Factory.StartNew(() =>
                {
                    while (true)
                    {
                        //判断是否被取消;
                        if (cts.Token.IsCancellationRequested)
                        {
                            return;
                        }

                        if (downloadCount == totalCount)
                        {
                            log.Info("--------------------------------->下载完成!<----------------------------------");
                            return;
                        }

                        ImgInfo imgInfo = new ImgInfo();
                        if (ltImgInfo.TryDequeue(out imgInfo))
                        {
                            //队列容量大于50 休息一秒
                            if (matQueue.Count > 50)
                            {
                                System.Threading.Thread.Sleep(1000);
                            }

                            if (matQueue.Count > 100)
                            {
                                System.Threading.Thread.Sleep(2000);
                            }

                            int imagesCount = imgInfo.images.Count();
                            for (int j = 0; j < imagesCount; j++)
                            {
                                try
                                {
                                    Stopwatch sw = new Stopwatch();
                                    sw.Start();  //开始计时
                                    HttpWebRequest request = WebRequest.Create(imgInfo.images[j].url) as HttpWebRequest;
                                    request.KeepAlive = false;
                                    request.ServicePoint.Expect100Continue = false;
                                    request.Timeout = 2000;// 2秒
                                    request.ReadWriteTimeout = 2000;//2秒

                                    request.ServicePoint.UseNagleAlgorithm = false;
                                    request.ServicePoint.ConnectionLimit = 65500;
                                    request.AllowWriteStreamBuffering = false;
                                    request.Proxy = null;

                                    request.CookieContainer = new CookieContainer();
                                    request.CookieContainer.Add(new Cookie("AspxAutoDetectCookieSupport", "1") { Domain = new Uri(imgInfo.images[j].url).Host });

                                    HttpWebResponse wresp = (HttpWebResponse)request.GetResponse();
                                    Stream s = wresp.GetResponseStream();
                                    Bitmap bmp = (Bitmap)System.Drawing.Image.FromStream(s);
                                    s.Dispose();
                                    wresp.Close();
                                    wresp.Dispose();
                                    request.Abort();

                                    sw.Stop();


                                    if (saveImg)
                                    {
                                        bmp.Save("img//" + imgInfo.id + "_" + j + ".jpg");
                                    }

                                    var mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);

                                    if (mat.Channels() == 4)
                                    {
                                        Cv2.CvtColor(mat, mat, ColorConversionCodes.BGRA2BGR);
                                    }

                                    imgInfo.images[j].mat = mat;
                                    imgInfo.images[j].name = imgInfo.id + "_" + j;

                                    if (saveImg)
                                    {
                                        bmp.Save("img//" + imgInfo.images[j].name + ".jpg");
                                    }

                                    log.Info("  " + imgInfo.images[j].name + "-->下载用时:" + sw.ElapsedMilliseconds + "毫秒");
                                }
                                catch (Exception ex)
                                {
                                    log.Error("---->id:" + imgInfo.id + ",url[" + imgInfo.images[j].url + "],下载异常:" + ex.Message);
                                }
                            }
                            matQueue.Enqueue(imgInfo);
                            Interlocked.Increment(ref downloadCount);
                        }

                    }
                }, TaskCreationOptions.LongRunning);

            }

            //识别线程
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    //判断是否被取消;
                    if (cts.Token.IsCancellationRequested)
                    {
                        return;
                    }

                    if (ocrNum == totalCount)
                    {
                        log.Info("--------------------------------->识别完成!<----------------------------------");
                        return;
                    }

                    ImgInfo imgInfo = new ImgInfo();
                    if (matQueue.TryDequeue(out imgInfo))
                    {

                        Stopwatch perID = new Stopwatch();
                        perID.Start();//开始计时
                        int imagesCount = imgInfo.images.Count();
                        for (int j = 0; j < imagesCount; j++)
                        {
                            //Mat mat= imgInfo.images[j].mat;
                            Stopwatch sw = new Stopwatch();
                            sw.Start();  //开始计时
                            PaddleOcrResult ocrResult = null;
                            try
                            {
                                if (imgInfo.images[j].mat != null && (!imgInfo.images[j].mat.Empty()))
                                {
                                    ocrResult = Program.paddleOcr.Run(imgInfo.images[j].mat);

                                    sw.Stop();
                                    log.Info("  " + imgInfo.images[j].name + "---->识别用时:" + sw.ElapsedMilliseconds + "毫秒");

                                    //string ocrInfo = ocrResult.Text.ToString();

                                    string ocrInfo = string.Join("\n", from x in ocrResult.Regions
                                                                       where x.Score > 0.8
                                                                       orderby x.Rect.Center.Y, x.Rect.Center.X
                                                                       select x.Text);

                                    if (saveOcr)
                                    {
                                        File.WriteAllText("ocr_result//" + imgInfo.images[j].name + ".txt", ocrInfo);
                                    }

                                    //规则校验
                                    Stopwatch ruleSw = new Stopwatch();
                                    ruleSw.Start();//开始计时
                                    ocrInfo = ocrInfo.Trim();
                                    ocrInfo = ocrInfo.Replace(" ", "");

                                    string words = "";
                                    string resultInfo = "";
                                    if (Common.RuleContainsCheck(ocrInfo, out words, ocrResult))
                                    {
                                        resultInfo = string.Format("ID:{0},Title:[{1}],------>包含违禁词:{2}", imgInfo.id, imgInfo.title, words);
                                        log.Info(resultInfo);

                                        //存数据
                                        File.AppendAllText("result//result.txt", imgInfo.id + "\t" + imgInfo.title + "\t包含违禁词:" + words + "\r\n");
                                        File.AppendAllText("result//result_detail.txt", "-------->\r\n" + resultInfo + ",识别内容" + ocrInfo + "\r\n<--------\r\n");

                                        //存图
                                        Cv2.ImWrite("result//img//" + imgInfo.images[j].name + ".jpg", imgInfo.images[j].mat);
                                        imgInfo.images[j].mat.Dispose();

                                        Interlocked.Increment(ref vioIDCount);

                                        break;
                                    }

                                    if (Common.RuleTelCheck(ocrInfo, out words, ocrResult))
                                    {
                                        resultInfo = string.Format("ID:{0},Title:[{1}],------>疑似包含电话号码:{2}", imgInfo.id, imgInfo.title, words);
                                        log.Info(resultInfo);
                                        //File.AppendAllText("result//result.txt", resultInfo+ "\r\n");
                                        File.AppendAllText("result//result.txt", imgInfo.id + "\t" + imgInfo.title + "\t疑似包含电话号码:" + words + "\r\n");
                                        File.AppendAllText("result//result_detail.txt", "-------->\r\n" + resultInfo + ",识别内容" + ocrInfo + "\r\n<--------\r\n");

                                        //存图
                                        Cv2.ImWrite("result//img//" + imgInfo.images[j].name + ".jpg", imgInfo.images[j].mat);
                                        imgInfo.images[j].mat.Dispose();

                                        Interlocked.Increment(ref vioIDCount);

                                        break;
                                    }
                                    imgInfo.images[j].mat.Dispose();
                                    ruleSw.Stop();
                                    //log.Info("  " + imgInfo.images[j].name + "---->违禁词校验用时:" + ruleSw.ElapsedMilliseconds + "毫秒");
                                }
                            }
                            catch (Exception ex)
                            {
                                imgInfo.images[j].mat.Dispose();
                                log.Info("  " + imgInfo.images[j].name + "---->识别异常:" + ex.Message);
                            }
                        }

                        perID.Stop();
                        log.Info("---->id:" + imgInfo.id + ",图片张数[" + imagesCount + "],识别小计用时:" + perID.ElapsedMilliseconds + "毫秒");
                        Interlocked.Increment(ref ocrNum);
                        ShowCostTime(totalCount.ToString(), ocrNum.ToString(), downloadCount.ToString(), total.ElapsedMilliseconds, vioIDCount);

                    }
                }
            }, TaskCreationOptions.LongRunning);
        }

        ///


        /// 停止
        ///

        ///
        ///
        private void button3_Click(object sender, EventArgs e)
        {
            cts.Cancel();
            btnStop.Enabled = false;
            btnStart.Enabled = true;

            chkSaveImg.Enabled = true;
            chkSaveOcr.Enabled = true;
        }
    }
}

  1. using Aspose.Cells;
  2. using NLog;
  3. using OpenCvSharp;
  4. using OpenVINO.OCRService;
  5. using Sdcb.OpenVINO;
  6. using Sdcb.OpenVINO.PaddleOCR;
  7. using Sdcb.OpenVINO.PaddleOCR.Models;
  8. using System;
  9. using System.Collections.Concurrent;
  10. using System.Collections.Generic;
  11. using System.Data;
  12. using System.Diagnostics;
  13. using System.Drawing;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Net;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using System.Windows.Forms;
  21. namespace OpenVINO.OCR
  22. {
  23. public partial class frmMain : Form
  24. {
  25. public frmMain()
  26. {
  27. InitializeComponent();
  28. NLog.Windows.Forms.RichTextBoxTarget.ReInitializeAllTextboxes(this);
  29. }
  30. String startupPath;
  31. private string excelFileFilter = "表格|*.xlsx;*.xls;";
  32. private Logger log = NLog.LogManager.GetCurrentClassLogger();
  33. CancellationTokenSource cts;
  34. ConcurrentQueue<ImgInfo> ltImgInfo = new ConcurrentQueue<ImgInfo>();
  35. ConcurrentQueue<ImgInfo> matQueue = new ConcurrentQueue<ImgInfo>();
  36. bool saveImg = false;
  37. bool saveOcr = false;
  38. int ocrNum = 0;//完成OCR识别的数量
  39. int totalCount = 0;//图片总数量
  40. int downloadCount = 0;//图片下载数量
  41. int vioIDCount = 0;//违规ID;
  42. private void frmMain_Load(object sender, EventArgs e)
  43. {
  44. DateTime limitTime = new DateTime(2024, 08, 30, 00, 00, 00);
  45. //测试使用
  46. if (DateTime.Now > limitTime)
  47. {
  48. MessageBox.Show("此软件试用期已过");
  49. Application.Exit();
  50. }
  51. //初始化
  52. startupPath = System.Windows.Forms.Application.StartupPath;
  53. string detectionModelDir = startupPath + "\\inference\\ch_PP-OCRv3_det_infer";
  54. string classificationModelDir = startupPath + "\\inference\\ch_ppocr_mobile_v2.0_cls_infer";
  55. string recognitionModelDir = startupPath + "\\inference\\ch_PP-OCRv3_rec_infer";
  56. string labelFilePath = startupPath + "\\inference\\ppocr_keys.txt";
  57. FullOcrModel model = FullOcrModel.FromDirectory(detectionModelDir, classificationModelDir, recognitionModelDir, labelFilePath, ModelVersion.V3);
  58. PaddleOcrOptions paddleOcrOptions = new PaddleOcrOptions();
  59. paddleOcrOptions.DetectionDeviceOptions = new DeviceOptions("CPU");
  60. paddleOcrOptions.DetectionStaticSize = new OpenCvSharp.Size(800, 800);
  61. paddleOcrOptions.RecognitionStaticWidth = 512;
  62. Program.paddleOcr = new PaddleOcrAll(model, paddleOcrOptions);
  63. Program.paddleOcr.Detector.UnclipRatio = 1.5f;
  64. Program.paddleOcr.AllowRotateDetection = true; /* 允许识别有角度的文字 */
  65. Program.paddleOcr.Enable180Classification = false; /* 允许识别旋转角度大于90度的文字 */
  66. ServicePointManager.Expect100Continue = false;
  67. ServicePointManager.DefaultConnectionLimit = 512;
  68. //加载违禁词
  69. Common.ltRuleContains.Clear();
  70. Common.ltRuleTel.Clear();
  71. string ruleContainsPath = "rules\\rule_contains.txt";
  72. if (File.Exists(ruleContainsPath))
  73. {
  74. Common.ltRuleContains = File.ReadAllLines(ruleContainsPath).ToList();
  75. }
  76. StringBuilder sb = new StringBuilder();
  77. foreach (var item in Common.ltRuleContains)
  78. {
  79. sb.AppendLine(item);
  80. }
  81. log.Info("rule_contains.txt---->包含" + Common.ltRuleContains.Count() + "个违禁词,内容如下:\r\n" + sb.ToString());
  82. string ruleTelPath = "rules\\rule_tel.txt";
  83. if (File.Exists(ruleTelPath))
  84. {
  85. foreach (var item in File.ReadAllLines(ruleTelPath))
  86. {
  87. Common.ltRuleTel.Add(item.ToLower());
  88. }
  89. }
  90. sb.Clear();
  91. foreach (var item in Common.ltRuleTel)
  92. {
  93. sb.AppendLine(item);
  94. }
  95. log.Info("rule_tel.txt---->包含" + Common.ltRuleTel.Count() + "个号码前缀,内容如下:\r\n" + sb.ToString());
  96. }
  97. /// <summary>
  98. /// 选择表格
  99. /// </summary>
  100. /// <param name="sender"></param>
  101. /// <param name="e"></param>
  102. private void button2_Click(object sender, EventArgs e)
  103. {
  104. try
  105. {
  106. OpenFileDialog ofd = new OpenFileDialog();
  107. ofd.Filter = excelFileFilter;
  108. if (ofd.ShowDialog() != DialogResult.OK) return;
  109. log.Info("解析中……");
  110. Application.DoEvents();
  111. Stopwatch sw = new Stopwatch();
  112. sw.Start(); //开始计时
  113. string excelPath = ofd.FileName;
  114. Workbook workbook = new Workbook(excelPath);
  115. Cells cells = workbook.Worksheets[0].Cells;
  116. System.Data.DataTable dataTable1 = cells.ExportDataTable(1, 0, cells.MaxDataRow, cells.MaxColumn + 1);//noneTitle
  117. ltImgInfo = new ConcurrentQueue<ImgInfo>();
  118. //遍历
  119. ImgInfo temp;
  120. int imgCount = 0;
  121. foreach (DataRow row in dataTable1.Rows)
  122. {
  123. temp = new ImgInfo();
  124. temp.id = row[0].ToString();
  125. temp.title = row[1].ToString();
  126. List<MatInfo> list = new List<MatInfo>();
  127. for (int i = 2; i < cells.MaxColumn + 1; i++)
  128. {
  129. string tempStr = row[i].ToString();
  130. if (!string.IsNullOrEmpty(tempStr))
  131. {
  132. if (i >= 7)
  133. {
  134. List<string> ltScrUrlTemp = Common.GetScrUrl(tempStr);
  135. if (ltScrUrlTemp.Count > 0)
  136. {
  137. foreach (var item in ltScrUrlTemp)
  138. {
  139. MatInfo matInfo = new MatInfo();
  140. matInfo.url = item;
  141. list.Add(matInfo);
  142. }
  143. }
  144. }
  145. else
  146. {
  147. MatInfo matInfo = new MatInfo();
  148. matInfo.url = tempStr;
  149. list.Add(matInfo);
  150. }
  151. }
  152. }
  153. temp.images = list;
  154. imgCount = imgCount + list.Count();
  155. ltImgInfo.Enqueue(temp);
  156. //for test
  157. //if (ltImgInfo.Count()>10)
  158. //{
  159. // break;
  160. //}
  161. }
  162. log.Info("解析完毕,一共[" + ltImgInfo.Count + "]条记录,[" + imgCount + "]张图片,耗时:" + sw.ElapsedMilliseconds + "毫秒");
  163. }
  164. catch (Exception ex)
  165. {
  166. log.Error("解析表格异常:" + ex.Message);
  167. MessageBox.Show("解析表格异常:" + ex.Message);
  168. }
  169. }
  170. void ShowCostTime(string total, string ocrNum, string downloadCount, long time, int vioIDCount)
  171. {
  172. txtTotal.Invoke(new Action(() =>
  173. {
  174. TimeSpan ts = TimeSpan.FromMilliseconds(time);
  175. txtTotal.Text = string.Format("下载完成:{0}/{1},识别完成:{2}/{3},违规ID数量:{5},用时:{4}"
  176. , downloadCount
  177. , total
  178. , ocrNum
  179. , total
  180. , ts.ToString()
  181. , vioIDCount
  182. );
  183. }));
  184. }
  185. /// <summary>
  186. /// 下载识别
  187. /// </summary>
  188. /// <param name="sender"></param>
  189. /// <param name="e"></param>
  190. private void button1_Click(object sender, EventArgs e)
  191. {
  192. if (ltImgInfo.Count == 0)
  193. {
  194. MessageBox.Show("请先选择表格!");
  195. return;
  196. }
  197. DialogResult result = MessageBox.Show("确认开始下载识别?此操作会清空上一次的数据,请注意备份!", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
  198. if (result == DialogResult.Yes)
  199. {
  200. log.Info("确认开始下载识别!");
  201. }
  202. else
  203. {
  204. log.Info("取消开始下载识别!");
  205. return;
  206. }
  207. if (!Directory.Exists("img"))
  208. {
  209. Directory.CreateDirectory("img");
  210. }
  211. if (!Directory.Exists("ocr_result"))
  212. {
  213. Directory.CreateDirectory("ocr_result");
  214. }
  215. if (!Directory.Exists("result"))
  216. {
  217. Directory.CreateDirectory("result");
  218. }
  219. if (!Directory.Exists("result//img"))
  220. {
  221. Directory.CreateDirectory("result//img");
  222. }
  223. //清空结果
  224. File.WriteAllText("result//result.txt", "");
  225. File.WriteAllText("result//result_detail.txt", "");
  226. // 清空文件夹中的文件
  227. foreach (string filePath in Directory.GetFiles("result", "*", SearchOption.AllDirectories))
  228. {
  229. File.Delete(filePath);
  230. }
  231. // 写入列标题
  232. File.WriteAllText("result//result.txt", "id\ttitel\tcontent\r\n");
  233. btnStop.Enabled = true;
  234. btnStart.Enabled = false;
  235. chkSaveImg.Enabled = false;
  236. chkSaveOcr.Enabled = false;
  237. if (chkSaveImg.Checked)
  238. {
  239. saveImg = true;
  240. }
  241. else
  242. {
  243. saveImg = false;
  244. }
  245. if (chkSaveOcr.Checked)
  246. {
  247. saveOcr = true;
  248. }
  249. else
  250. {
  251. saveOcr = false;
  252. }
  253. Application.DoEvents();
  254. cts = new CancellationTokenSource();
  255. Stopwatch total = new Stopwatch();
  256. total.Start(); //开始计时
  257. // 清空队列
  258. matQueue = new ConcurrentQueue<ImgInfo>();
  259. //while (!matQueue.IsEmpty)
  260. //{
  261. // matQueue.TryDequeue(out _);
  262. //}
  263. ocrNum = 0;//完成OCR识别的数量
  264. totalCount = ltImgInfo.Count();//图片总数量
  265. downloadCount = 0;
  266. //下载线程
  267. int downloadThreadNum = 2;
  268. for (int i = 0; i < downloadThreadNum; i++)
  269. {
  270. Task.Factory.StartNew(() =>
  271. {
  272. while (true)
  273. {
  274. //判断是否被取消;
  275. if (cts.Token.IsCancellationRequested)
  276. {
  277. return;
  278. }
  279. if (downloadCount == totalCount)
  280. {
  281. log.Info("--------------------------------->下载完成!<----------------------------------");
  282. return;
  283. }
  284. ImgInfo imgInfo = new ImgInfo();
  285. if (ltImgInfo.TryDequeue(out imgInfo))
  286. {
  287. //队列容量大于50 休息一秒
  288. if (matQueue.Count > 50)
  289. {
  290. System.Threading.Thread.Sleep(1000);
  291. }
  292. if (matQueue.Count > 100)
  293. {
  294. System.Threading.Thread.Sleep(2000);
  295. }
  296. int imagesCount = imgInfo.images.Count();
  297. for (int j = 0; j < imagesCount; j++)
  298. {
  299. try
  300. {
  301. Stopwatch sw = new Stopwatch();
  302. sw.Start(); //开始计时
  303. HttpWebRequest request = WebRequest.Create(imgInfo.images[j].url) as HttpWebRequest;
  304. request.KeepAlive = false;
  305. request.ServicePoint.Expect100Continue = false;
  306. request.Timeout = 2000;// 2秒
  307. request.ReadWriteTimeout = 2000;//2秒
  308. request.ServicePoint.UseNagleAlgorithm = false;
  309. request.ServicePoint.ConnectionLimit = 65500;
  310. request.AllowWriteStreamBuffering = false;
  311. request.Proxy = null;
  312. request.CookieContainer = new CookieContainer();
  313. request.CookieContainer.Add(new Cookie("AspxAutoDetectCookieSupport", "1") { Domain = new Uri(imgInfo.images[j].url).Host });
  314. HttpWebResponse wresp = (HttpWebResponse)request.GetResponse();
  315. Stream s = wresp.GetResponseStream();
  316. Bitmap bmp = (Bitmap)System.Drawing.Image.FromStream(s);
  317. s.Dispose();
  318. wresp.Close();
  319. wresp.Dispose();
  320. request.Abort();
  321. sw.Stop();
  322. if (saveImg)
  323. {
  324. bmp.Save("img//" + imgInfo.id + "_" + j + ".jpg");
  325. }
  326. var mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
  327. if (mat.Channels() == 4)
  328. {
  329. Cv2.CvtColor(mat, mat, ColorConversionCodes.BGRA2BGR);
  330. }
  331. imgInfo.images[j].mat = mat;
  332. imgInfo.images[j].name = imgInfo.id + "_" + j;
  333. if (saveImg)
  334. {
  335. bmp.Save("img//" + imgInfo.images[j].name + ".jpg");
  336. }
  337. log.Info(" " + imgInfo.images[j].name + "-->下载用时:" + sw.ElapsedMilliseconds + "毫秒");
  338. }
  339. catch (Exception ex)
  340. {
  341. log.Error("---->id:" + imgInfo.id + ",url[" + imgInfo.images[j].url + "],下载异常:" + ex.Message);
  342. }
  343. }
  344. matQueue.Enqueue(imgInfo);
  345. Interlocked.Increment(ref downloadCount);
  346. }
  347. }
  348. }, TaskCreationOptions.LongRunning);
  349. }
  350. //识别线程
  351. Task.Factory.StartNew(() =>
  352. {
  353. while (true)
  354. {
  355. //判断是否被取消;
  356. if (cts.Token.IsCancellationRequested)
  357. {
  358. return;
  359. }
  360. if (ocrNum == totalCount)
  361. {
  362. log.Info("--------------------------------->识别完成!<----------------------------------");
  363. return;
  364. }
  365. ImgInfo imgInfo = new ImgInfo();
  366. if (matQueue.TryDequeue(out imgInfo))
  367. {
  368. Stopwatch perID = new Stopwatch();
  369. perID.Start();//开始计时
  370. int imagesCount = imgInfo.images.Count();
  371. for (int j = 0; j < imagesCount; j++)
  372. {
  373. //Mat mat= imgInfo.images[j].mat;
  374. Stopwatch sw = new Stopwatch();
  375. sw.Start(); //开始计时
  376. PaddleOcrResult ocrResult = null;
  377. try
  378. {
  379. if (imgInfo.images[j].mat != null && (!imgInfo.images[j].mat.Empty()))
  380. {
  381. ocrResult = Program.paddleOcr.Run(imgInfo.images[j].mat);
  382. sw.Stop();
  383. log.Info(" " + imgInfo.images[j].name + "---->识别用时:" + sw.ElapsedMilliseconds + "毫秒");
  384. //string ocrInfo = ocrResult.Text.ToString();
  385. string ocrInfo = string.Join("\n", from x in ocrResult.Regions
  386. where x.Score > 0.8
  387. orderby x.Rect.Center.Y, x.Rect.Center.X
  388. select x.Text);
  389. if (saveOcr)
  390. {
  391. File.WriteAllText("ocr_result//" + imgInfo.images[j].name + ".txt", ocrInfo);
  392. }
  393. //规则校验
  394. Stopwatch ruleSw = new Stopwatch();
  395. ruleSw.Start();//开始计时
  396. ocrInfo = ocrInfo.Trim();
  397. ocrInfo = ocrInfo.Replace(" ", "");
  398. string words = "";
  399. string resultInfo = "";
  400. if (Common.RuleContainsCheck(ocrInfo, out words, ocrResult))
  401. {
  402. resultInfo = string.Format("ID:{0},Title:[{1}],------>包含违禁词:{2}", imgInfo.id, imgInfo.title, words);
  403. log.Info(resultInfo);
  404. //存数据
  405. File.AppendAllText("result//result.txt", imgInfo.id + "\t" + imgInfo.title + "\t包含违禁词:" + words + "\r\n");
  406. File.AppendAllText("result//result_detail.txt", "-------->\r\n" + resultInfo + ",识别内容" + ocrInfo + "\r\n<--------\r\n");
  407. //存图
  408. Cv2.ImWrite("result//img//" + imgInfo.images[j].name + ".jpg", imgInfo.images[j].mat);
  409. imgInfo.images[j].mat.Dispose();
  410. Interlocked.Increment(ref vioIDCount);
  411. break;
  412. }
  413. if (Common.RuleTelCheck(ocrInfo, out words, ocrResult))
  414. {
  415. resultInfo = string.Format("ID:{0},Title:[{1}],------>疑似包含电话号码:{2}", imgInfo.id, imgInfo.title, words);
  416. log.Info(resultInfo);
  417. //File.AppendAllText("result//result.txt", resultInfo+ "\r\n");
  418. File.AppendAllText("result//result.txt", imgInfo.id + "\t" + imgInfo.title + "\t疑似包含电话号码:" + words + "\r\n");
  419. File.AppendAllText("result//result_detail.txt", "-------->\r\n" + resultInfo + ",识别内容" + ocrInfo + "\r\n<--------\r\n");
  420. //存图
  421. Cv2.ImWrite("result//img//" + imgInfo.images[j].name + ".jpg", imgInfo.images[j].mat);
  422. imgInfo.images[j].mat.Dispose();
  423. Interlocked.Increment(ref vioIDCount);
  424. break;
  425. }
  426. imgInfo.images[j].mat.Dispose();
  427. ruleSw.Stop();
  428. //log.Info(" " + imgInfo.images[j].name + "---->违禁词校验用时:" + ruleSw.ElapsedMilliseconds + "毫秒");
  429. }
  430. }
  431. catch (Exception ex)
  432. {
  433. imgInfo.images[j].mat.Dispose();
  434. log.Info(" " + imgInfo.images[j].name + "---->识别异常:" + ex.Message);
  435. }
  436. }
  437. perID.Stop();
  438. log.Info("---->id:" + imgInfo.id + ",图片张数[" + imagesCount + "],识别小计用时:" + perID.ElapsedMilliseconds + "毫秒");
  439. Interlocked.Increment(ref ocrNum);
  440. ShowCostTime(totalCount.ToString(), ocrNum.ToString(), downloadCount.ToString(), total.ElapsedMilliseconds, vioIDCount);
  441. }
  442. }
  443. }, TaskCreationOptions.LongRunning);
  444. }
  445. /// <summary>
  446. /// 停止
  447. /// </summary>
  448. /// <param name="sender"></param>
  449. /// <param name="e"></param>
  450. private void button3_Click(object sender, EventArgs e)
  451. {
  452. cts.Cancel();
  453. btnStop.Enabled = false;
  454. btnStart.Enabled = true;
  455. chkSaveImg.Enabled = true;
  456. chkSaveOcr.Enabled = true;
  457. }
  458. }
  459. }

下载

源码下载

天天代码码天天
微信公众号
.NET 人工智能实践
注:本文转载自blog.csdn.net的天天代码码天天的文章"https://lw112190.blog.csdn.net/article/details/141086877"。版权归原作者所有,此博客不拥有其著作权,亦不承担相应法律责任。如有侵权,请联系我们删除。
复制链接
复制链接
相关推荐
发表评论
登录后才能发表评论和回复 注册

/ 登录

评论记录:

未查询到任何数据!
回复评论:

分类栏目

后端 (14832) 前端 (14280) 移动开发 (3760) 编程语言 (3851) Java (3904) Python (3298) 人工智能 (10119) AIGC (2810) 大数据 (3499) 数据库 (3945) 数据结构与算法 (3757) 音视频 (2669) 云原生 (3145) 云平台 (2965) 前沿技术 (2993) 开源 (2160) 小程序 (2860) 运维 (2533) 服务器 (2698) 操作系统 (2325) 硬件开发 (2492) 嵌入式 (2955) 微软技术 (2769) 软件工程 (2056) 测试 (2865) 网络空间安全 (2948) 网络与通信 (2797) 用户体验设计 (2592) 学习和成长 (2593) 搜索 (2744) 开发工具 (7108) 游戏 (2829) HarmonyOS (2935) 区块链 (2782) 数学 (3112) 3C硬件 (2759) 资讯 (2909) Android (4709) iOS (1850) 代码人生 (3043) 阅读 (2841)

热门文章

101
推荐
关于我们 隐私政策 免责声明 联系我们
Copyright © 2020-2025 蚁人论坛 (iYenn.com) All Rights Reserved.
Scroll to Top