PaddleOCRHelper.cs
3.6 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
using Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BLL
{
public class PaddleOCRHelper
{
private static Process progressTest;
static DateTime startTime;
/// <summary>
/// 开始检测
/// </summary>
/// <param name="pythonExePath">python解释器路径</param>
/// <param name="pythonFile">python文件</param>
/// <param name="imgPath">图像文件路径</param>
/// <returns></returns>
public static string StartTest(string pythonExePath, string pythonFile, string imgPath)
{
string state = "";
try
{
string sArguments = pythonFile + " " + imgPath;
ProcessStartInfo start = new ProcessStartInfo();
start.FileName = pythonExePath + " ";//环境路径需要配置好
start.Arguments = sArguments;
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
start.RedirectStandardInput = true;
start.RedirectStandardError = true;
start.CreateNoWindow = true;
startTime = DateTime.Now;
using (progressTest = Process.Start(start))
{
state = progressTest.StandardOutput.ReadToEnd();
progressTest.WaitForExit(30000);
//// 异步获取命令行内容
//progressTest.BeginOutputReadLine();
//// 为异步获取订阅事件
//progressTest.OutputDataReceived += new DataReceivedEventHandler(outputDataReceived);
}
string[] result = state.Split(new string[] { "\r\n" }, StringSplitOptions.None);
if (result != null && result.Length > 1)
{
foreach (var item in result.Reverse())
{
if (item.Contains("OCR-Result:"))
{
var ocrR = item.Substring(12);
if (!string.IsNullOrEmpty(ocrR))
{
var lst = DeserializeJsonToList<string>(ocrR);
if (lst != null && lst.Count > 0)
{
state = string.Join(" ", lst);
LogNet.log.Info($"Paddle OCR匹配["+ $"{(DateTime.Now - startTime).TotalSeconds.ToString("f2")}s" + "]:"+ state);
}
else
{
state = "";
}
}
break;
}
}
return state;
}
else
return "";
}catch(Exception ex)
{
LogNet.log.Error("Paddle OCR匹配异常",ex);
}
return "";
}
static List<T> DeserializeJsonToList<T>(string json) where T : class
{
JsonSerializer serializer = new JsonSerializer();
StringReader sr = new StringReader(json);
object o = serializer.Deserialize(new JsonTextReader(sr), typeof(List<T>));
List<T> list = o as List<T>;
return list;
}
}
}