版博士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.
 
 
 
 

783 line
33 KiB

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