版博士V2.0程序
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

790 regels
33 KiB

  1. //#define Defect3
  2. //#define OpenSizeDefectComp
  3. using System;
  4. using System.Collections.Generic;
  5. using System.ComponentModel;
  6. using System.Diagnostics;
  7. using System.Drawing;
  8. using System.Drawing.Imaging;
  9. using System.IO;
  10. using System.Linq;
  11. using System.Reflection;
  12. using System.Threading;
  13. using System.Threading.Tasks;
  14. using System.Windows.Forms;
  15. using Microsoft.ML.OnnxRuntime;
  16. using Microsoft.ML.OnnxRuntime.Tensors;
  17. using Newtonsoft.Json;
  18. using OpenCvSharp;
  19. using Yolo5;
  20. namespace MaiMuAOI.ImageProcessing
  21. {
  22. public enum WarningEnum
  23. {
  24. [Description("正常")]
  25. Normal,
  26. [Description("低(可继续)")]
  27. Low,
  28. [Description("严重")]
  29. High
  30. }
  31. public class DefectLib : IDisposable
  32. {
  33. public Action<WarningEnum, string> WarningEvent;
  34. /// <summary>
  35. /// 检测结果JSON(原图,结果)
  36. /// </summary>
  37. public Action<DefectTask> finishEvent;
  38. /// <summary>
  39. /// 是否打开设备成功
  40. /// </summary>
  41. public bool IsInit { get; private set; } = false;
  42. //private System.Timers.Timer timer = new System.Timers.Timer();
  43. private Yolo_Class yolo1;
  44. private InferenceSession _onnxSession;
  45. private Yolo_Class yolo2;
  46. private InferenceSession _onnxSession2;
  47. private Yolo_Class yolo3;
  48. private InferenceSession _onnxSession3;
  49. //
  50. private Thread t_task, t_task_operation, t_task_operation2, t_task_operation3, t_task_tag;
  51. //=======task list
  52. private List<DefectTask> taskList = new List<DefectTask>();
  53. private List<DefectTask> taskOperationList = new List<DefectTask>();
  54. private List<DefectTask> taskTagList = new List<DefectTask>();
  55. public DefectLib()
  56. {
  57. }
  58. public bool start()
  59. {
  60. try
  61. {
  62. yolo1 = new Yolo_Class();
  63. yolo2 = new Yolo_Class();
  64. #if Defect3
  65. yolo3 = new Yolo_Class();
  66. #endif
  67. //加载模型(只加载一次即可)
  68. //string modelFilePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\DevCfg\\best.onnx";
  69. //_onnxSession = yolo1.LoadModel(modelFilePath, true);//false-CPU true-显卡
  70. IsInit = true;
  71. //timer.Elapsed += Timer_Elapsed;
  72. //timer.Interval = 100;
  73. //timer.Enabled = true;
  74. taskList.Clear();
  75. taskOperationList.Clear();
  76. taskTagList.Clear();
  77. //MessageBox.Show("11");
  78. t_task = new System.Threading.Thread(runStep);
  79. t_task.IsBackground = true;
  80. t_task.Start();
  81. //MessageBox.Show("22");
  82. t_task_operation = new System.Threading.Thread(run2);
  83. t_task_operation.IsBackground = true;
  84. t_task_operation.Start();
  85. //MessageBox.Show("33");
  86. t_task_operation2 = new System.Threading.Thread(run3);
  87. t_task_operation2.IsBackground = true;
  88. t_task_operation2.Start();
  89. //MessageBox.Show("44");
  90. #if Defect3
  91. t_task_operation3 = new System.Threading.Thread(run4);
  92. t_task_operation3.IsBackground = true;
  93. t_task_operation3.Start();
  94. #endif
  95. //MessageBox.Show("55");
  96. return true;
  97. }
  98. catch (Exception ex)
  99. {
  100. WarningEvent?.Invoke(WarningEnum.High, ex.Message);
  101. return false;
  102. }
  103. }
  104. public void stop()
  105. {
  106. if (!IsInit) return;
  107. try
  108. {
  109. IsInit = false;
  110. //timer.Elapsed -= Timer_Elapsed;
  111. //释放模型
  112. if (_onnxSession != null)
  113. {
  114. _onnxSession.Dispose();
  115. _onnxSession = null;
  116. }
  117. if (_onnxSession2 != null)
  118. {
  119. _onnxSession2.Dispose();
  120. _onnxSession2 = null;
  121. }
  122. #if Defect3
  123. if (_onnxSession3 != null)
  124. {
  125. _onnxSession3.Dispose();
  126. _onnxSession3 = null;
  127. }
  128. #endif
  129. _preLoadONNXFilePath = null;
  130. if (t_task != null)
  131. {
  132. bool b = t_task.Join(5000);
  133. if (!b) t_task.Abort();
  134. t_task = null;
  135. }
  136. if (t_task_operation != null)
  137. {
  138. bool b = t_task_operation.Join(5000);
  139. if (!b) t_task_operation.Abort();
  140. t_task_operation = null;
  141. }
  142. if (t_task_operation2 != null)
  143. {
  144. bool b = t_task_operation2.Join(5000);
  145. if (!b) t_task_operation2.Abort();
  146. t_task_operation2 = null;
  147. }
  148. #if Defect3
  149. if (t_task_operation3 != null)
  150. {
  151. bool b = t_task_operation3.Join(5000);
  152. if (!b) t_task_operation3.Abort();
  153. t_task_operation3 = null;
  154. }
  155. #endif
  156. if (t_task_tag != null)
  157. {
  158. bool b = t_task_tag.Join(5000);
  159. if (!b) t_task_tag.Abort();
  160. t_task_tag = null;
  161. }
  162. taskList.Clear();
  163. taskOperationList.Clear();
  164. taskTagList.Clear();
  165. }
  166. catch { }
  167. }
  168. private string _preLoadONNXFilePath;//记录上次成功加载的模型,不重复加载
  169. public void loadModelFile(string onnxFilePath, bool UseGPU)
  170. {
  171. try
  172. {
  173. //string modelFilePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\DevCfg\\best.onnx";
  174. //不重复加载
  175. if (!string.IsNullOrWhiteSpace(_preLoadONNXFilePath) && _preLoadONNXFilePath.ToLower() == onnxFilePath.ToLower())
  176. return;
  177. //MessageBox.Show("1");
  178. //Task.Run(async () =>
  179. //{
  180. // if (_onnxSession != null)
  181. // {
  182. // _onnxSession.Dispose();
  183. // _onnxSession = null;
  184. // }
  185. // _onnxSession = yolo1.LoadModel(onnxFilePath, true);//false-CPU true-显卡
  186. // _preLoadONNXFilePath = onnxFilePath;
  187. //});
  188. if (_onnxSession != null)
  189. {
  190. _onnxSession.Dispose();
  191. _onnxSession = null;
  192. }
  193. _onnxSession = yolo1.LoadModel(onnxFilePath, UseGPU);//false-CPU true-显卡
  194. //MessageBox.Show("2");
  195. if (_onnxSession2 != null)
  196. {
  197. _onnxSession2.Dispose();
  198. _onnxSession2 = null;
  199. }
  200. _onnxSession2 = yolo2.LoadModel(onnxFilePath, UseGPU);//false-CPU true-显卡
  201. #if Defect3
  202. //MessageBox.Show("3");
  203. if (_onnxSession3 != null)
  204. {
  205. _onnxSession3.Dispose();
  206. _onnxSession3 = null;
  207. }
  208. _onnxSession3 = yolo3.LoadModel(onnxFilePath, true);//false-CPU true-显卡
  209. #endif
  210. //MessageBox.Show("4");
  211. _preLoadONNXFilePath = onnxFilePath;
  212. }
  213. catch (Exception ex)
  214. {
  215. MessageBox.Show(ex.Message);
  216. }
  217. }
  218. /// <summary>
  219. /// 保存图片
  220. /// </summary>
  221. /// <param name="Img"></param>图片
  222. /// <param name="pictureUrl"></param>保存路径
  223. /// <param name="pictureName"></param>保存名称
  224. private void SaveImage(Bitmap Img, string pictureUrl, string pictureName)
  225. {
  226. if (!Directory.Exists(pictureUrl))
  227. {
  228. Directory.CreateDirectory(pictureUrl);
  229. }
  230. FileInfo FileUrl = new FileInfo(pictureUrl);//防止路径中有日期导致路径错误
  231. try
  232. {
  233. using (Bitmap bitmap = new Bitmap(Img))
  234. {
  235. using (MemoryStream stream = new MemoryStream())
  236. {
  237. bitmap.Save(stream, ImageFormat.Bmp);
  238. System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
  239. //img.Save(FileUrl +"\\"+ pictureName);
  240. //img.Dispose();
  241. string szURL = FileUrl + "\\" + pictureName;
  242. img.Save(szURL, ImageFormat.Bmp);
  243. img.Dispose();
  244. }
  245. }
  246. }
  247. catch (Exception)
  248. {
  249. if (Img != null)
  250. {
  251. Img.Dispose();
  252. }
  253. }
  254. }
  255. private void runStep()
  256. {
  257. while (IsInit)
  258. {
  259. if (taskList.Count < 1 || _onnxSession == null)
  260. {
  261. Thread.Sleep(5);
  262. continue;
  263. }
  264. //
  265. var task = pop();
  266. try
  267. {
  268. if (task != null)
  269. {
  270. Stopwatch stopwatch = Stopwatch.StartNew();
  271. //源图
  272. //Bitmap bmp = yolo1.Read2Bmp(file_path);
  273. //切割图像,输入图像格式14208*10640
  274. stopwatch.Start();
  275. task.bmps_cut = yolo1.OpenCVToCutsMat(task.bmp, task.cut_size.Width, task.cut_size.Height);
  276. stopwatch.Stop();
  277. task.stopwatch[0] = stopwatch.ElapsedMilliseconds;
  278. //Resize图像
  279. stopwatch.Restart();
  280. task.bmps_resize = yolo1.OpenCVToResizesMat(task.bmps_cut, task.resize.Width, task.resize.Height);
  281. stopwatch.Stop();
  282. task.stopwatch[1] = stopwatch.ElapsedMilliseconds;
  283. //预处理模型
  284. stopwatch.Restart();
  285. task.tensors = yolo1.PreprocessImageMat(task.bmps_resize);
  286. stopwatch.Stop();
  287. task.stopwatch[2] = stopwatch.ElapsedMilliseconds;
  288. lock (taskOperationList)
  289. taskOperationList.Add(task);
  290. }
  291. Thread.Sleep(5);
  292. }
  293. catch (Exception ex)
  294. {
  295. WarningEvent?.Invoke(WarningEnum.Low, "DefectLib task1 err:" + ex.Message);
  296. task.isSucceed = false;
  297. task.resultInfo = ex.Message;
  298. callback(task);
  299. }
  300. }
  301. }
  302. private void run2()
  303. {
  304. while (IsInit)
  305. {
  306. if (taskOperationList.Count < 1)
  307. {
  308. Thread.Sleep(5);
  309. continue;
  310. }
  311. //
  312. var task = pop2();
  313. int liStep = 0;
  314. try
  315. {
  316. if (task != null)
  317. {
  318. Stopwatch stopwatch = Stopwatch.StartNew();
  319. //====运行推理(必需单队列)
  320. stopwatch.Start();
  321. IDisposableReadOnlyCollection<DisposableNamedOnnxValue>[] results = yolo1.RunModlel(_onnxSession, task.tensors);
  322. liStep = 1;
  323. if (task.modelType == "rj")
  324. task.informationList = yolo1.ScreeningResults_YD_RJ(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  325. else
  326. task.informationList = yolo1.ScreeningResults_YD(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  327. liStep = 2;
  328. //当前大图上缺陷个数
  329. int currPicDefectCount = 0;
  330. for (int x = 0; x < task.informationList.Count(); x++)
  331. currPicDefectCount += task.informationList[x].Count();
  332. task.defectCount = currPicDefectCount;
  333. stopwatch.Stop();
  334. task.stopwatch[3] = stopwatch.ElapsedMilliseconds;
  335. liStep = 3;
  336. if (task.informationList.Count > 0)
  337. {
  338. liStep = 4;
  339. //lock (taskTagList)
  340. // taskTagList.Add(task);
  341. //====打标 ,有缺陷返回缺陷图片数组,没缺陷返回所有图片数组
  342. stopwatch.Restart();
  343. #if OpenSizeDefectComp
  344. task.bmps_tag = yolo1.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  345. task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk, out task.defectInfor2BigImage);
  346. #else
  347. task.bmps_tag = yolo1.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  348. task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk);
  349. #endif
  350. liStep = 5;
  351. //List<List<string>> SizedefectInfor2RestorationDesk = SysMgr.Instance.GetSizeDefectData(task.Xmm, task.Ymm);
  352. //task.defectInfor2RestorationDesk = yolo3.FilteringOverlappingDefects(task.defectInfor2RestorationDesk, SizedefectInfor2RestorationDesk);
  353. //liStep = 51;
  354. //if (ConfMgr.Instance.SysConfigParams.OpenFlawDistribution)
  355. //{
  356. // //大图缺陷坐标转换到图纸坐标
  357. // if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0)
  358. // task.defectInfor2RestorationDeskPage = yolo1.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk);
  359. //}
  360. stopwatch.Stop();
  361. task.stopwatch[4] = stopwatch.ElapsedMilliseconds;
  362. liStep = 6;
  363. task.bmpCompress = yolo1.ResizesMat_4(task.bmp);
  364. //if (!ConfMgr.Instance.SysConfigParams.OpenColorB)
  365. // task.bmpCompress = yolo1.ResizesMat_4(task.bmp);
  366. //else
  367. // task.bmpCompress = yolo1.ResizesMat_4(task.srcbmp);
  368. task.isSucceed = true;
  369. callback(task);
  370. }
  371. else
  372. {
  373. task.isSucceed = true;
  374. callback(task);
  375. }
  376. }
  377. Thread.Sleep(5);
  378. }
  379. catch (Exception ex)
  380. {
  381. WarningEvent?.Invoke(WarningEnum.Low, $"DefectLib task2 err({liStep}):" + ex.Message + $"||{task.modelType}-{task.thresholds}, {task.thresholdsClass}, {JsonConvert.SerializeObject(task.recAreaThreshold)}");
  382. task.isSucceed = false;
  383. task.resultInfo = ex.Message;
  384. callback(task);
  385. }
  386. }
  387. }
  388. private void run3()
  389. {
  390. while (IsInit)
  391. {
  392. if (taskOperationList.Count < 1)
  393. {
  394. Thread.Sleep(5);
  395. continue;
  396. }
  397. //
  398. var task = pop2();
  399. int liStep = 0;
  400. try
  401. {
  402. if (task != null)
  403. {
  404. Stopwatch stopwatch = Stopwatch.StartNew();
  405. //====运行推理(必需单队列)
  406. stopwatch.Start();
  407. IDisposableReadOnlyCollection<DisposableNamedOnnxValue>[] results = yolo2.RunModlel(_onnxSession2, task.tensors);
  408. liStep = 1;
  409. if (task.modelType == "rj")
  410. task.informationList = yolo2.ScreeningResults_YD_RJ(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  411. else
  412. task.informationList = yolo2.ScreeningResults_YD(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  413. liStep = 2;
  414. //当前大图上缺陷个数
  415. int currPicDefectCount = 0;
  416. for (int x = 0; x < task.informationList.Count(); x++)
  417. currPicDefectCount += task.informationList[x].Count();
  418. task.defectCount = currPicDefectCount;
  419. stopwatch.Stop();
  420. task.stopwatch[3] = stopwatch.ElapsedMilliseconds;
  421. liStep = 3;
  422. if (task.informationList.Count > 0)
  423. {
  424. liStep = 4;
  425. //lock (taskTagList)
  426. // taskTagList.Add(task);
  427. //====打标 ,有缺陷返回缺陷图片数组,没缺陷返回所有图片数组
  428. stopwatch.Restart();
  429. #if OpenSizeDefectComp
  430. task.bmps_tag = yolo2.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  431. task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk, out task.defectInfor2BigImage);
  432. #else
  433. task.bmps_tag = yolo2.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  434. task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk);
  435. #endif
  436. liStep = 5;
  437. //List<List<string>> SizedefectInfor2RestorationDesk = SysMgr.Instance.GetSizeDefectData(task.Xmm, task.Ymm);
  438. //task.defectInfor2RestorationDesk = yolo3.FilteringOverlappingDefects(task.defectInfor2RestorationDesk, SizedefectInfor2RestorationDesk);
  439. //liStep = 51;
  440. //if (ConfMgr.Instance.SysConfigParams.OpenFlawDistribution)
  441. //{
  442. // //大图缺陷坐标转换到图纸坐标
  443. // if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0)
  444. // task.defectInfor2RestorationDeskPage = yolo2.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk);
  445. //}
  446. stopwatch.Stop();
  447. task.stopwatch[4] = stopwatch.ElapsedMilliseconds;
  448. liStep = 6;
  449. task.bmpCompress = yolo2.ResizesMat_4(task.bmp);
  450. task.isSucceed = true;
  451. callback(task);
  452. }
  453. else
  454. {
  455. task.isSucceed = true;
  456. callback(task);
  457. }
  458. }
  459. Thread.Sleep(5);
  460. }
  461. catch (Exception ex)
  462. {
  463. WarningEvent?.Invoke(WarningEnum.Low, $"DefectLib task3 err({liStep}):" + ex.Message + $"||{task.modelType}-{task.thresholds}, {task.thresholdsClass}, {JsonConvert.SerializeObject(task.recAreaThreshold)}");
  464. task.isSucceed = false;
  465. task.resultInfo = ex.Message;
  466. callback(task);
  467. }
  468. }
  469. }
  470. private void run4()
  471. {
  472. while (IsInit)
  473. {
  474. if (taskOperationList.Count < 1)
  475. {
  476. Thread.Sleep(5);
  477. continue;
  478. }
  479. //
  480. var task = pop2();
  481. int liStep = 0;
  482. try
  483. {
  484. if (task != null)
  485. {
  486. Stopwatch stopwatch = Stopwatch.StartNew();
  487. //====运行推理(必需单队列)
  488. stopwatch.Start();
  489. IDisposableReadOnlyCollection<DisposableNamedOnnxValue>[] results = yolo3.RunModlel(_onnxSession3, task.tensors);
  490. liStep = 1;
  491. if(task.modelType == "rj")
  492. task.informationList = yolo3.ScreeningResults_YD_RJ(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  493. else
  494. task.informationList = yolo3.ScreeningResults_YD(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  495. liStep = 2;
  496. //当前大图上缺陷个数
  497. int currPicDefectCount = 0;
  498. for (int x = 0; x < task.informationList.Count(); x++)
  499. currPicDefectCount += task.informationList[x].Count();
  500. task.defectCount = currPicDefectCount;
  501. stopwatch.Stop();
  502. task.stopwatch[3] = stopwatch.ElapsedMilliseconds;
  503. liStep = 3;
  504. if (task.informationList.Count > 0)
  505. {
  506. liStep = 4;
  507. //lock (taskTagList)
  508. // taskTagList.Add(task);
  509. //====打标 ,有缺陷返回缺陷图片数组,没缺陷返回所有图片数组
  510. stopwatch.Restart();
  511. #if OpenSizeDefectComp
  512. task.bmps_tag = yolo3.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  513. task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk, out task.defectInfor2BigImage);
  514. #else
  515. task.bmps_tag = yolo3.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  516. task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk);
  517. #endif
  518. liStep = 5;
  519. //List<List<string>> SizedefectInfor2RestorationDesk = SysMgr.Instance.GetSizeDefectData(task.Xmm, task.Ymm);
  520. //task.defectInfor2RestorationDesk = yolo3.FilteringOverlappingDefects(task.defectInfor2RestorationDesk, SizedefectInfor2RestorationDesk);
  521. //liStep = 51;
  522. //if (ConfMgr.Instance.SysConfigParams.OpenFlawDistribution)
  523. //{
  524. // //大图缺陷坐标转换到图纸坐标
  525. // if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0)
  526. // task.defectInfor2RestorationDeskPage = yolo3.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk);
  527. //}
  528. stopwatch.Stop();
  529. task.stopwatch[4] = stopwatch.ElapsedMilliseconds;
  530. liStep = 6;
  531. task.bmpCompress = yolo3.ResizesMat_4(task.bmp);
  532. task.isSucceed = true;
  533. callback(task);
  534. }
  535. else
  536. {
  537. task.isSucceed = true;
  538. callback(task);
  539. }
  540. }
  541. Thread.Sleep(5);
  542. }
  543. catch (Exception ex)
  544. {
  545. WarningEvent?.Invoke(WarningEnum.Low, $"DefectLib task4 err({liStep}):" + ex.Message);
  546. task.isSucceed = false;
  547. task.resultInfo = ex.Message;
  548. callback(task);
  549. }
  550. }
  551. }
  552. /// <summary>
  553. /// 已不用
  554. /// </summary>
  555. private void run5()
  556. {
  557. while (IsInit)
  558. {
  559. if (taskTagList.Count < 1)
  560. {
  561. Thread.Sleep(0);
  562. continue;
  563. }
  564. //
  565. var task = pop3();
  566. try
  567. {
  568. if (task != null)
  569. {
  570. Stopwatch stopwatch = Stopwatch.StartNew();
  571. //====打标 ,有缺陷返回缺陷图片数组,没缺陷返回所有图片数组
  572. stopwatch.Start();
  573. task.bmps_tag = yolo1.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  574. task.Xmm,task.Ymm,out task.defectInfor2RestorationDesk);
  575. stopwatch.Stop();
  576. task.stopwatch[4] = stopwatch.ElapsedMilliseconds;
  577. task.isSucceed = true;
  578. callback(task);
  579. }
  580. }
  581. catch (Exception ex)
  582. {
  583. WarningEvent?.Invoke(WarningEnum.Low, "DefectLib task3 err:" + ex.Message);
  584. task.isSucceed = false;
  585. task.resultInfo = ex.Message;
  586. callback(task);
  587. }
  588. }
  589. }
  590. private void callback(DefectTask task)
  591. {
  592. //返回成功/失败,异步调用
  593. if (task.finishEvent != null || (task.finishEvent = finishEvent) != null)
  594. //task.finishEvent.BeginInvoke(result, errInfo, res => task.finishEvent.EndInvoke(res), null);
  595. System.Threading.ThreadPool.QueueUserWorkItem(waitCallback, task);
  596. }
  597. //异步回调
  598. WaitCallback waitCallback = new WaitCallback(o =>
  599. {
  600. var task = (DefectTask)o;
  601. task.finishEvent(task);
  602. });
  603. public class DefectTask
  604. {
  605. public int stepIndex;
  606. public string processName;
  607. //2024 03 22 加入模型类型 rj pt;
  608. public string modelType;
  609. public string drawingPagePath;//图纸路径bmp
  610. //图索引
  611. public int index = 0;
  612. /// <summary>
  613. /// 绝对位置-----X2轴
  614. /// </summary>
  615. public double Xmm;
  616. /// <summary>
  617. /// 绝对位置-----Y轴
  618. /// </summary>
  619. public double Ymm;
  620. /// <summary>
  621. /// 源文件
  622. /// </summary>
  623. public Mat bmp;
  624. public Mat srcbmp;
  625. public Mat bmpCompress;//压缩有缺陷大图
  626. public System.Drawing.Size cut_size = new System.Drawing.Size(592, 532);
  627. public System.Drawing.Size resize = new System.Drawing.Size(224, 224);
  628. /// <summary>
  629. /// 阈值
  630. /// </summary>
  631. public float thresholds = 0.4f;
  632. /// <summary>
  633. /// 种类阈值
  634. /// </summary>
  635. public string thresholdsClass;
  636. /// <summary>
  637. /// 缺陷在面积内数量
  638. /// </summary>
  639. public Dictionary<string, float> recAreaThreshold;
  640. /// <summary>
  641. /// 完成后回调
  642. /// </summary>
  643. public Action<DefectTask> finishEvent;
  644. //
  645. public long createTime = DateTime.Now.Ticks;
  646. public DateTime nowTime;
  647. //中间变量,供step2使用
  648. public Mat[] bmps_cut;
  649. public Mat[] bmps_resize;
  650. //预处理模型
  651. public Tensor<float>[] tensors;
  652. //==结果返回
  653. public List<Dictionary<int, List<string>[]>> informationList;
  654. public int defectCount;//informationList中的缺陷数
  655. public List<List<string>> defectInfor2RestorationDesk, defectInfor2RestorationDeskPage;//打标缺陷转为图纸的坐标
  656. public Bitmap[] bmps_tag; //打标小图 //bmps_tag.count<=bmps_cut.count bmps_tag.count=informationList.count
  657. public bool isSucceed;//转换是否成功
  658. public string resultInfo = "";//成功或失败信息
  659. public long[] stopwatch = new long[5];
  660. public List<List<string>> defectInfor2BigImage;
  661. }
  662. public void add(DefectTask task)
  663. {
  664. lock (taskList)
  665. taskList.Add(task);
  666. }
  667. /// <summary>
  668. /// 打标 返回每张图的绝对位置X,Y
  669. /// </summary>
  670. /// <param name="defectBmpIndex">缺陷小图索引</param>
  671. /// <param name="X">拍照位绝对位置-----X2轴</param>
  672. /// <param name="Y">拍照位绝对位置-----Y轴</param>
  673. /// <param name="imagewidth">裁剪小图的宽592</param>
  674. /// <param name="imageheight">裁剪小图的高532</param>
  675. public List<double> makeTag(int defectBmpIndex, double X, double Y, int imagewidth, int imageheight)
  676. {
  677. return yolo1.ImageXY(defectBmpIndex, X, Y, imagewidth, imageheight);
  678. }
  679. /// <summary>
  680. /// 用相机1查看缺陷点
  681. /// </summary>
  682. /// <param name="defectBmpIndex"></param>
  683. /// <param name="X"></param>
  684. /// <param name="Y"></param>
  685. /// <param name="imagewidth"></param>
  686. /// <param name="imageheight"></param>
  687. /// <returns></returns>
  688. public List<double> viewTag(int defectBmpIndex, double X, double Y, int imagewidth, int imageheight)
  689. {
  690. return yolo1.ImageXY2(defectBmpIndex, X, Y, imagewidth, imageheight);
  691. }
  692. private DefectTask pop()
  693. {
  694. lock (taskList)
  695. {
  696. if (taskList.Count < 1)
  697. return null;
  698. //int index = 0;// taskList.FindIndex(p => { return p.isSync; });
  699. //if (index < 0) index = 0;
  700. var task = taskList[0];
  701. taskList.RemoveAt(0);
  702. return task;
  703. }
  704. }
  705. private DefectTask pop2()
  706. {
  707. lock (taskOperationList)
  708. {
  709. if (taskOperationList.Count < 1)
  710. return null;
  711. //int index = 0;// taskList.FindIndex(p => { return p.isSync; });
  712. //if (index < 0) index = 0;
  713. var task = taskOperationList[0];
  714. taskOperationList.RemoveAt(0);
  715. return task;
  716. }
  717. }
  718. private DefectTask pop3()
  719. {
  720. lock (taskTagList)
  721. {
  722. if (taskTagList.Count < 1)
  723. return null;
  724. //int index = 0;// taskList.FindIndex(p => { return p.isSync; });
  725. //if (index < 0) index = 0;
  726. var task = taskTagList[0];
  727. taskTagList.RemoveAt(0);
  728. return task;
  729. }
  730. }
  731. public void Dispose()
  732. {
  733. stop();
  734. }
  735. }
  736. }