版博士V2.0程序
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

DefectLib - 复制.cs 14 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Drawing;
  5. using System.Drawing.Imaging;
  6. using System.IO;
  7. using System.Reflection;
  8. using System.Threading;
  9. using Microsoft.ML.OnnxRuntime;
  10. using Microsoft.ML.OnnxRuntime.Tensors;
  11. using Yolo5;
  12. namespace ProductionControl.Device
  13. {
  14. public class DefectLib : IDisposable
  15. {
  16. public Action<WarningEnum, string> WarningEvent;
  17. /// <summary>
  18. /// 检测结果JSON(原图,结果)
  19. /// </summary>
  20. public Action<DefectTask> finishEvent;
  21. /// <summary>
  22. /// 是否打开设备成功
  23. /// </summary>
  24. public bool IsInit { get; private set; } = false;
  25. //private System.Timers.Timer timer = new System.Timers.Timer();
  26. private Thread t_task, t_task2, t_task3, t_task4, t_task_operation, t_task_operation2, t_task_tag;
  27. private Yolo_Class yolo1;
  28. private InferenceSession _onnxSession;
  29. public DefectLib()
  30. {
  31. }
  32. public bool start()
  33. {
  34. try
  35. {
  36. yolo1 = new Yolo_Class();
  37. //加载模型(只加载一次即可)
  38. string modelFilePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\DevCfg\\best.onnx";
  39. _onnxSession = yolo1.LoadModel(modelFilePath, true);//false-CPU true-显卡
  40. IsInit = true;
  41. //timer.Elapsed += Timer_Elapsed;
  42. //timer.Interval = 100;
  43. //timer.Enabled = true;
  44. taskList.Clear();
  45. taskOperationList.Clear();
  46. taskTagList.Clear();
  47. t_task = new System.Threading.Thread(run);
  48. t_task.IsBackground = true;
  49. t_task.Start();
  50. t_task2 = new System.Threading.Thread(run);
  51. t_task2.IsBackground = true;
  52. t_task2.Start();
  53. t_task3 = new System.Threading.Thread(run);
  54. t_task3.IsBackground = true;
  55. t_task3.Start();
  56. t_task4 = new System.Threading.Thread(run);
  57. t_task4.IsBackground = true;
  58. t_task4.Start();
  59. t_task_operation = new System.Threading.Thread(run2);
  60. t_task_operation.IsBackground = true;
  61. t_task_operation.Start();
  62. t_task_operation2 = new System.Threading.Thread(run2);
  63. t_task_operation2.IsBackground = true;
  64. t_task_operation2.Start();
  65. t_task_tag = new System.Threading.Thread(run3);
  66. t_task_tag.IsBackground = true;
  67. t_task_tag.Start();
  68. return true;
  69. }
  70. catch (Exception ex)
  71. {
  72. WarningEvent?.Invoke(WarningEnum.High, ex.Message);
  73. return false;
  74. }
  75. }
  76. public void stop()
  77. {
  78. if (!IsInit) return;
  79. try
  80. {
  81. IsInit = false;
  82. //timer.Elapsed -= Timer_Elapsed;
  83. //释放模型
  84. _onnxSession.Dispose();
  85. if (t_task != null)
  86. {
  87. bool b = t_task.Join(5000);
  88. if (!b) t_task.Abort();
  89. t_task = null;
  90. }
  91. if (t_task2 != null)
  92. {
  93. bool b = t_task2.Join(5000);
  94. if (!b) t_task2.Abort();
  95. t_task2 = null;
  96. }
  97. if (t_task3 != null)
  98. {
  99. bool b = t_task3.Join(5000);
  100. if (!b) t_task3.Abort();
  101. t_task3 = null;
  102. }
  103. if (t_task4 != null)
  104. {
  105. bool b = t_task4.Join(5000);
  106. if (!b) t_task4.Abort();
  107. t_task4 = null;
  108. }
  109. if (t_task_operation != null)
  110. {
  111. bool b = t_task_operation.Join(5000);
  112. if (!b) t_task_operation.Abort();
  113. t_task_operation = null;
  114. }
  115. if (t_task_operation2 != null)
  116. {
  117. bool b = t_task_operation2.Join(5000);
  118. if (!b) t_task_operation2.Abort();
  119. t_task_operation2 = null;
  120. }
  121. if (t_task_tag != null)
  122. {
  123. bool b = t_task_tag.Join(5000);
  124. if (!b) t_task_tag.Abort();
  125. t_task_tag = null;
  126. }
  127. taskList.Clear();
  128. taskOperationList.Clear();
  129. taskTagList.Clear();
  130. }
  131. catch { }
  132. }
  133. /// <summary>
  134. /// 保存图片
  135. /// </summary>
  136. /// <param name="Img"></param>图片
  137. /// <param name="pictureUrl"></param>保存路径
  138. /// <param name="pictureName"></param>保存名称
  139. public void SaveImage(Bitmap Img, string pictureUrl, string pictureName)
  140. {
  141. if (!Directory.Exists(pictureUrl))
  142. {
  143. Directory.CreateDirectory(pictureUrl);
  144. }
  145. FileInfo FileUrl = new FileInfo(pictureUrl);//防止路径中有日期导致路径错误
  146. try
  147. {
  148. using (Bitmap bitmap = new Bitmap(Img))
  149. {
  150. using (MemoryStream stream = new MemoryStream())
  151. {
  152. bitmap.Save(stream, ImageFormat.Bmp);
  153. System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
  154. //img.Save(FileUrl +"\\"+ pictureName);
  155. //img.Dispose();
  156. string szURL = FileUrl + "\\" + pictureName;
  157. img.Save(szURL, ImageFormat.Bmp);
  158. img.Dispose();
  159. }
  160. }
  161. }
  162. catch (Exception)
  163. {
  164. if (Img != null)
  165. {
  166. Img.Dispose();
  167. }
  168. }
  169. }
  170. private void run()
  171. {
  172. while (IsInit)
  173. {
  174. if (taskList.Count < 1)
  175. {
  176. Thread.Sleep(0);
  177. continue;
  178. }
  179. //
  180. var task = pop();
  181. try
  182. {
  183. if (task != null)
  184. {
  185. Stopwatch stopwatch = Stopwatch.StartNew();
  186. //源图
  187. //Bitmap bmp = yolo1.Read2Bmp(file_path);
  188. //切割图像,输入图像格式14208*10640
  189. stopwatch.Restart();
  190. task.bmps_cut = yolo1.OpenCVToCuts(task.bmp, task.cut_size.Width, task.cut_size.Height);
  191. stopwatch.Stop();
  192. task.stopwatch[0] = stopwatch.ElapsedMilliseconds;
  193. //Resize图像
  194. stopwatch.Restart();
  195. task.bmps_resize = yolo1.OpenCVToResizes(task.bmps_cut, task.resize.Width, task.resize.Height);
  196. stopwatch.Stop();
  197. task.stopwatch[1] = stopwatch.ElapsedMilliseconds;
  198. //预处理模型
  199. stopwatch.Restart();
  200. task.tensors = yolo1.PreprocessImage(task.bmps_resize);
  201. stopwatch.Stop();
  202. task.stopwatch[2] = stopwatch.ElapsedMilliseconds;
  203. lock (taskOperationList)
  204. taskOperationList.Add(task);
  205. }
  206. }
  207. catch (Exception ex)
  208. {
  209. WarningEvent?.Invoke(WarningEnum.Low, "DefectLib task err:" + ex.Message);
  210. task.isSucceed = false;
  211. task.resultInfo = ex.Message;
  212. callback(task);
  213. }
  214. }
  215. }
  216. private void run2()
  217. {
  218. while (IsInit)
  219. {
  220. if (taskOperationList.Count < 1)
  221. {
  222. Thread.Sleep(0);
  223. continue;
  224. }
  225. //
  226. var task = pop2();
  227. try
  228. {
  229. if (task != null)
  230. {
  231. Stopwatch stopwatch = Stopwatch.StartNew();
  232. //====运行推理(必需单队列)
  233. stopwatch.Restart();
  234. IDisposableReadOnlyCollection<DisposableNamedOnnxValue>[] results = yolo1.RunModlel(_onnxSession, task.tensors);
  235. task.informationList = yolo1.ScreeningResults(results, task.bmps_resize, task.thresholds);
  236. stopwatch.Stop();
  237. task.stopwatch[3] = stopwatch.ElapsedMilliseconds;
  238. if (task.informationList.Count > 0)
  239. {
  240. lock (taskTagList)
  241. taskTagList.Add(task);
  242. }
  243. else
  244. {
  245. task.isSucceed = true;
  246. callback(task);
  247. }
  248. }
  249. }
  250. catch (Exception ex)
  251. {
  252. WarningEvent?.Invoke(WarningEnum.Low, "DefectLib task2 err:" + ex.Message);
  253. task.isSucceed = false;
  254. task.resultInfo = ex.Message;
  255. callback(task);
  256. }
  257. }
  258. }
  259. private void run3()
  260. {
  261. while (IsInit)
  262. {
  263. if (taskTagList.Count < 1)
  264. {
  265. Thread.Sleep(0);
  266. continue;
  267. }
  268. //
  269. var task = pop3();
  270. try
  271. {
  272. if (task != null)
  273. {
  274. Stopwatch stopwatch = Stopwatch.StartNew();
  275. //====打标 null ,有缺陷返回缺陷图片数组,没缺陷返回所有图片数组
  276. stopwatch.Restart();
  277. task.bmps_tag = yolo1.DrawYoloPrediction2(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width);
  278. stopwatch.Stop();
  279. task.stopwatch[4] = stopwatch.ElapsedMilliseconds;
  280. task.isSucceed = true;
  281. callback(task);
  282. }
  283. }
  284. catch (Exception ex)
  285. {
  286. WarningEvent?.Invoke(WarningEnum.Low, "DefectLib task3 err:" + ex.Message);
  287. task.isSucceed = false;
  288. task.resultInfo = ex.Message;
  289. callback(task);
  290. }
  291. }
  292. }
  293. private void callback(DefectTask task)
  294. {
  295. //返回成功/失败,异步调用
  296. if (task.finishEvent != null || (task.finishEvent = finishEvent) != null)
  297. //task.finishEvent.BeginInvoke(result, errInfo, res => task.finishEvent.EndInvoke(res), null);
  298. System.Threading.ThreadPool.QueueUserWorkItem(waitCallback, task);
  299. }
  300. //异步回调
  301. WaitCallback waitCallback = new WaitCallback(o =>
  302. {
  303. var task = (DefectTask)o;
  304. task.finishEvent(task);
  305. });
  306. //=======task list
  307. private List<DefectTask> taskList = new List<DefectTask>();
  308. private List<DefectTask> taskOperationList = new List<DefectTask>();
  309. private List<DefectTask> taskTagList = new List<DefectTask>();
  310. public class DefectTask
  311. {
  312. //图索引
  313. public int index = 0;
  314. /// <summary>
  315. /// 源文件
  316. /// </summary>
  317. public Bitmap bmp;
  318. public Size cut_size = new Size(592, 532);
  319. public Size resize = new Size(224, 224);
  320. /// <summary>
  321. /// 阈值
  322. /// </summary>
  323. public float thresholds = 0.4f;
  324. /// <summary>
  325. /// 完成后回调
  326. /// </summary>
  327. public Action<DefectTask> finishEvent;
  328. //
  329. public long createTime = DateTime.Now.Ticks;
  330. public DateTime nowTime;
  331. //中间变量,供step2使用
  332. public Bitmap[] bmps_cut;
  333. public Bitmap[] bmps_resize;
  334. //预处理模型
  335. public Tensor<float>[] tensors;
  336. //==结果返回
  337. public List<Dictionary<int, List<string>[]>> informationList;
  338. public Bitmap[] bmps_tag;
  339. public bool isSucceed;//转换是否成功
  340. public string resultInfo = "";//成功或失败信息
  341. public long[] stopwatch = new long[5];
  342. }
  343. public void add(DefectTask task)
  344. {
  345. lock (taskList)
  346. taskList.Add(task);
  347. }
  348. private DefectTask pop()
  349. {
  350. lock (taskList)
  351. {
  352. if (taskList.Count < 1)
  353. return null;
  354. int index = 0;// taskList.FindIndex(p => { return p.isSync; });
  355. //if (index < 0) index = 0;
  356. var task = taskList[0];
  357. taskList.RemoveAt(0);
  358. return task;
  359. }
  360. }
  361. private DefectTask pop2()
  362. {
  363. lock (taskOperationList)
  364. {
  365. if (taskOperationList.Count < 1)
  366. return null;
  367. int index = 0;// taskList.FindIndex(p => { return p.isSync; });
  368. //if (index < 0) index = 0;
  369. var task = taskOperationList[0];
  370. taskOperationList.RemoveAt(0);
  371. return task;
  372. }
  373. }
  374. private DefectTask pop3()
  375. {
  376. lock (taskTagList)
  377. {
  378. if (taskTagList.Count < 1)
  379. return null;
  380. int index = 0;// taskList.FindIndex(p => { return p.isSync; });
  381. //if (index < 0) index = 0;
  382. var task = taskTagList[0];
  383. taskTagList.RemoveAt(0);
  384. return task;
  385. }
  386. }
  387. public void Dispose()
  388. {
  389. stop();
  390. }
  391. }
  392. }