版博士V2.0程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 

782 строки
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. MessageBox.Show(ex.Message);
  208. }
  209. }
  210. /// <summary>
  211. /// 保存图片
  212. /// </summary>
  213. /// <param name="Img"></param>图片
  214. /// <param name="pictureUrl"></param>保存路径
  215. /// <param name="pictureName"></param>保存名称
  216. private void SaveImage(Bitmap Img, string pictureUrl, string pictureName)
  217. {
  218. if (!Directory.Exists(pictureUrl))
  219. {
  220. Directory.CreateDirectory(pictureUrl);
  221. }
  222. FileInfo FileUrl = new FileInfo(pictureUrl);//防止路径中有日期导致路径错误
  223. try
  224. {
  225. using (Bitmap bitmap = new Bitmap(Img))
  226. {
  227. using (MemoryStream stream = new MemoryStream())
  228. {
  229. bitmap.Save(stream, ImageFormat.Bmp);
  230. System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
  231. //img.Save(FileUrl +"\\"+ pictureName);
  232. //img.Dispose();
  233. string szURL = FileUrl + "\\" + pictureName;
  234. img.Save(szURL, ImageFormat.Bmp);
  235. img.Dispose();
  236. }
  237. }
  238. }
  239. catch (Exception)
  240. {
  241. if (Img != null)
  242. {
  243. Img.Dispose();
  244. }
  245. }
  246. }
  247. private void runStep()
  248. {
  249. while (IsInit)
  250. {
  251. if (taskList.Count < 1 || _onnxSession == null)
  252. {
  253. Thread.Sleep(5);
  254. continue;
  255. }
  256. //
  257. var task = pop();
  258. try
  259. {
  260. if (task != null)
  261. {
  262. Stopwatch stopwatch = Stopwatch.StartNew();
  263. //源图
  264. //Bitmap bmp = yolo1.Read2Bmp(file_path);
  265. //切割图像,输入图像格式14208*10640
  266. stopwatch.Start();
  267. task.bmps_cut = yolo1.OpenCVToCutsMat(task.bmp, task.cut_size.Width, task.cut_size.Height);
  268. stopwatch.Stop();
  269. task.stopwatch[0] = stopwatch.ElapsedMilliseconds;
  270. //Resize图像
  271. stopwatch.Restart();
  272. task.bmps_resize = yolo1.OpenCVToResizesMat(task.bmps_cut, task.resize.Width, task.resize.Height);
  273. stopwatch.Stop();
  274. task.stopwatch[1] = stopwatch.ElapsedMilliseconds;
  275. //预处理模型
  276. stopwatch.Restart();
  277. task.tensors = yolo1.PreprocessImageMat(task.bmps_resize);
  278. stopwatch.Stop();
  279. task.stopwatch[2] = stopwatch.ElapsedMilliseconds;
  280. lock (taskOperationList)
  281. taskOperationList.Add(task);
  282. }
  283. Thread.Sleep(5);
  284. }
  285. catch (Exception ex)
  286. {
  287. WarningEvent?.Invoke(WarningEnum.Low, "DefectLib task1 err:" + ex.Message);
  288. task.isSucceed = false;
  289. task.resultInfo = ex.Message;
  290. callback(task);
  291. }
  292. }
  293. }
  294. private void run2()
  295. {
  296. while (IsInit)
  297. {
  298. if (taskOperationList.Count < 1)
  299. {
  300. Thread.Sleep(5);
  301. continue;
  302. }
  303. //
  304. var task = pop2();
  305. int liStep = 0;
  306. try
  307. {
  308. if (task != null)
  309. {
  310. Stopwatch stopwatch = Stopwatch.StartNew();
  311. //====运行推理(必需单队列)
  312. stopwatch.Start();
  313. IDisposableReadOnlyCollection<DisposableNamedOnnxValue>[] results = yolo1.RunModlel(_onnxSession, task.tensors);
  314. liStep = 1;
  315. if (task.modelType == "rj")
  316. task.informationList = yolo1.ScreeningResults_YD_RJ(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  317. else
  318. task.informationList = yolo1.ScreeningResults_YD(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  319. liStep = 2;
  320. //当前大图上缺陷个数
  321. int currPicDefectCount = 0;
  322. for (int x = 0; x < task.informationList.Count(); x++)
  323. currPicDefectCount += task.informationList[x].Count();
  324. task.defectCount = currPicDefectCount;
  325. stopwatch.Stop();
  326. task.stopwatch[3] = stopwatch.ElapsedMilliseconds;
  327. liStep = 3;
  328. if (task.informationList.Count > 0)
  329. {
  330. liStep = 4;
  331. //lock (taskTagList)
  332. // taskTagList.Add(task);
  333. //====打标 ,有缺陷返回缺陷图片数组,没缺陷返回所有图片数组
  334. stopwatch.Restart();
  335. #if OpenSizeDefectComp
  336. task.bmps_tag = yolo1.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  337. task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk, out task.defectInfor2BigImage);
  338. #else
  339. task.bmps_tag = yolo1.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  340. task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk);
  341. #endif
  342. liStep = 5;
  343. //List<List<string>> SizedefectInfor2RestorationDesk = SysMgr.Instance.GetSizeDefectData(task.Xmm, task.Ymm);
  344. //task.defectInfor2RestorationDesk = yolo3.FilteringOverlappingDefects(task.defectInfor2RestorationDesk, SizedefectInfor2RestorationDesk);
  345. //liStep = 51;
  346. if (ConfMgr.Instance.SysConfigParams.OpenFlawDistribution)
  347. {
  348. //大图缺陷坐标转换到图纸坐标
  349. if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0)
  350. task.defectInfor2RestorationDeskPage = yolo1.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk);
  351. }
  352. stopwatch.Stop();
  353. task.stopwatch[4] = stopwatch.ElapsedMilliseconds;
  354. liStep = 6;
  355. task.bmpCompress = yolo1.ResizesMat_4(task.bmp);
  356. //if (!ConfMgr.Instance.SysConfigParams.OpenColorB)
  357. // task.bmpCompress = yolo1.ResizesMat_4(task.bmp);
  358. //else
  359. // task.bmpCompress = yolo1.ResizesMat_4(task.srcbmp);
  360. task.isSucceed = true;
  361. callback(task);
  362. }
  363. else
  364. {
  365. task.isSucceed = true;
  366. callback(task);
  367. }
  368. }
  369. Thread.Sleep(5);
  370. }
  371. catch (Exception ex)
  372. {
  373. WarningEvent?.Invoke(WarningEnum.Low, $"DefectLib task2 err({liStep}):" + ex.Message + $"||{task.modelType}-{task.thresholds}, {task.thresholdsClass}, {JsonConvert.SerializeObject(task.recAreaThreshold)}");
  374. task.isSucceed = false;
  375. task.resultInfo = ex.Message;
  376. callback(task);
  377. }
  378. }
  379. }
  380. private void run3()
  381. {
  382. while (IsInit)
  383. {
  384. if (taskOperationList.Count < 1)
  385. {
  386. Thread.Sleep(5);
  387. continue;
  388. }
  389. //
  390. var task = pop2();
  391. int liStep = 0;
  392. try
  393. {
  394. if (task != null)
  395. {
  396. Stopwatch stopwatch = Stopwatch.StartNew();
  397. //====运行推理(必需单队列)
  398. stopwatch.Start();
  399. IDisposableReadOnlyCollection<DisposableNamedOnnxValue>[] results = yolo2.RunModlel(_onnxSession2, task.tensors);
  400. liStep = 1;
  401. if (task.modelType == "rj")
  402. task.informationList = yolo2.ScreeningResults_YD_RJ(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  403. else
  404. task.informationList = yolo2.ScreeningResults_YD(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  405. liStep = 2;
  406. //当前大图上缺陷个数
  407. int currPicDefectCount = 0;
  408. for (int x = 0; x < task.informationList.Count(); x++)
  409. currPicDefectCount += task.informationList[x].Count();
  410. task.defectCount = currPicDefectCount;
  411. stopwatch.Stop();
  412. task.stopwatch[3] = stopwatch.ElapsedMilliseconds;
  413. liStep = 3;
  414. if (task.informationList.Count > 0)
  415. {
  416. liStep = 4;
  417. //lock (taskTagList)
  418. // taskTagList.Add(task);
  419. //====打标 ,有缺陷返回缺陷图片数组,没缺陷返回所有图片数组
  420. stopwatch.Restart();
  421. #if OpenSizeDefectComp
  422. task.bmps_tag = yolo2.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  423. task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk, out task.defectInfor2BigImage);
  424. #else
  425. task.bmps_tag = yolo2.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  426. task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk);
  427. #endif
  428. liStep = 5;
  429. //List<List<string>> SizedefectInfor2RestorationDesk = SysMgr.Instance.GetSizeDefectData(task.Xmm, task.Ymm);
  430. //task.defectInfor2RestorationDesk = yolo3.FilteringOverlappingDefects(task.defectInfor2RestorationDesk, SizedefectInfor2RestorationDesk);
  431. //liStep = 51;
  432. if (ConfMgr.Instance.SysConfigParams.OpenFlawDistribution)
  433. {
  434. //大图缺陷坐标转换到图纸坐标
  435. if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0)
  436. task.defectInfor2RestorationDeskPage = yolo2.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk);
  437. }
  438. stopwatch.Stop();
  439. task.stopwatch[4] = stopwatch.ElapsedMilliseconds;
  440. liStep = 6;
  441. task.bmpCompress = yolo2.ResizesMat_4(task.bmp);
  442. task.isSucceed = true;
  443. callback(task);
  444. }
  445. else
  446. {
  447. task.isSucceed = true;
  448. callback(task);
  449. }
  450. }
  451. Thread.Sleep(5);
  452. }
  453. catch (Exception ex)
  454. {
  455. WarningEvent?.Invoke(WarningEnum.Low, $"DefectLib task3 err({liStep}):" + ex.Message + $"||{task.modelType}-{task.thresholds}, {task.thresholdsClass}, {JsonConvert.SerializeObject(task.recAreaThreshold)}");
  456. task.isSucceed = false;
  457. task.resultInfo = ex.Message;
  458. callback(task);
  459. }
  460. }
  461. }
  462. private void run4()
  463. {
  464. while (IsInit)
  465. {
  466. if (taskOperationList.Count < 1)
  467. {
  468. Thread.Sleep(5);
  469. continue;
  470. }
  471. //
  472. var task = pop2();
  473. int liStep = 0;
  474. try
  475. {
  476. if (task != null)
  477. {
  478. Stopwatch stopwatch = Stopwatch.StartNew();
  479. //====运行推理(必需单队列)
  480. stopwatch.Start();
  481. IDisposableReadOnlyCollection<DisposableNamedOnnxValue>[] results = yolo3.RunModlel(_onnxSession3, task.tensors);
  482. liStep = 1;
  483. if(task.modelType == "rj")
  484. task.informationList = yolo3.ScreeningResults_YD_RJ(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  485. else
  486. task.informationList = yolo3.ScreeningResults_YD(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  487. liStep = 2;
  488. //当前大图上缺陷个数
  489. int currPicDefectCount = 0;
  490. for (int x = 0; x < task.informationList.Count(); x++)
  491. currPicDefectCount += task.informationList[x].Count();
  492. task.defectCount = currPicDefectCount;
  493. stopwatch.Stop();
  494. task.stopwatch[3] = stopwatch.ElapsedMilliseconds;
  495. liStep = 3;
  496. if (task.informationList.Count > 0)
  497. {
  498. liStep = 4;
  499. //lock (taskTagList)
  500. // taskTagList.Add(task);
  501. //====打标 ,有缺陷返回缺陷图片数组,没缺陷返回所有图片数组
  502. stopwatch.Restart();
  503. #if OpenSizeDefectComp
  504. task.bmps_tag = yolo3.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  505. task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk, out task.defectInfor2BigImage);
  506. #else
  507. task.bmps_tag = yolo3.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  508. task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk);
  509. #endif
  510. liStep = 5;
  511. //List<List<string>> SizedefectInfor2RestorationDesk = SysMgr.Instance.GetSizeDefectData(task.Xmm, task.Ymm);
  512. //task.defectInfor2RestorationDesk = yolo3.FilteringOverlappingDefects(task.defectInfor2RestorationDesk, SizedefectInfor2RestorationDesk);
  513. //liStep = 51;
  514. if (ConfMgr.Instance.SysConfigParams.OpenFlawDistribution)
  515. {
  516. //大图缺陷坐标转换到图纸坐标
  517. if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0)
  518. task.defectInfor2RestorationDeskPage = yolo3.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk);
  519. }
  520. stopwatch.Stop();
  521. task.stopwatch[4] = stopwatch.ElapsedMilliseconds;
  522. liStep = 6;
  523. task.bmpCompress = yolo3.ResizesMat_4(task.bmp);
  524. task.isSucceed = true;
  525. callback(task);
  526. }
  527. else
  528. {
  529. task.isSucceed = true;
  530. callback(task);
  531. }
  532. }
  533. Thread.Sleep(5);
  534. }
  535. catch (Exception ex)
  536. {
  537. WarningEvent?.Invoke(WarningEnum.Low, $"DefectLib task4 err({liStep}):" + ex.Message);
  538. task.isSucceed = false;
  539. task.resultInfo = ex.Message;
  540. callback(task);
  541. }
  542. }
  543. }
  544. /// <summary>
  545. /// 已不用
  546. /// </summary>
  547. private void run5()
  548. {
  549. while (IsInit)
  550. {
  551. if (taskTagList.Count < 1)
  552. {
  553. Thread.Sleep(0);
  554. continue;
  555. }
  556. //
  557. var task = pop3();
  558. try
  559. {
  560. if (task != null)
  561. {
  562. Stopwatch stopwatch = Stopwatch.StartNew();
  563. //====打标 ,有缺陷返回缺陷图片数组,没缺陷返回所有图片数组
  564. stopwatch.Start();
  565. task.bmps_tag = yolo1.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  566. task.Xmm,task.Ymm,out task.defectInfor2RestorationDesk);
  567. stopwatch.Stop();
  568. task.stopwatch[4] = stopwatch.ElapsedMilliseconds;
  569. task.isSucceed = true;
  570. callback(task);
  571. }
  572. }
  573. catch (Exception ex)
  574. {
  575. WarningEvent?.Invoke(WarningEnum.Low, "DefectLib task3 err:" + ex.Message);
  576. task.isSucceed = false;
  577. task.resultInfo = ex.Message;
  578. callback(task);
  579. }
  580. }
  581. }
  582. private void callback(DefectTask task)
  583. {
  584. //返回成功/失败,异步调用
  585. if (task.finishEvent != null || (task.finishEvent = finishEvent) != null)
  586. //task.finishEvent.BeginInvoke(result, errInfo, res => task.finishEvent.EndInvoke(res), null);
  587. System.Threading.ThreadPool.QueueUserWorkItem(waitCallback, task);
  588. }
  589. //异步回调
  590. WaitCallback waitCallback = new WaitCallback(o =>
  591. {
  592. var task = (DefectTask)o;
  593. task.finishEvent(task);
  594. });
  595. public class DefectTask
  596. {
  597. public int stepIndex;
  598. public string processName;
  599. //2024 03 22 加入模型类型 rj pt;
  600. public string modelType;
  601. public string drawingPagePath;//图纸路径bmp
  602. //图索引
  603. public int index = 0;
  604. /// <summary>
  605. /// 绝对位置-----X2轴
  606. /// </summary>
  607. public double Xmm;
  608. /// <summary>
  609. /// 绝对位置-----Y轴
  610. /// </summary>
  611. public double Ymm;
  612. /// <summary>
  613. /// 源文件
  614. /// </summary>
  615. public Mat bmp;
  616. public Mat srcbmp;
  617. public Mat bmpCompress;//压缩有缺陷大图
  618. public System.Drawing.Size cut_size = new System.Drawing.Size(592, 532);
  619. public System.Drawing.Size resize = new System.Drawing.Size(224, 224);
  620. /// <summary>
  621. /// 阈值
  622. /// </summary>
  623. public float thresholds = 0.4f;
  624. /// <summary>
  625. /// 种类阈值
  626. /// </summary>
  627. public string thresholdsClass;
  628. /// <summary>
  629. /// 缺陷在面积内数量
  630. /// </summary>
  631. public Dictionary<string, float> recAreaThreshold;
  632. /// <summary>
  633. /// 完成后回调
  634. /// </summary>
  635. public Action<DefectTask> finishEvent;
  636. //
  637. public long createTime = DateTime.Now.Ticks;
  638. public DateTime nowTime;
  639. //中间变量,供step2使用
  640. public Mat[] bmps_cut;
  641. public Mat[] bmps_resize;
  642. //预处理模型
  643. public Tensor<float>[] tensors;
  644. //==结果返回
  645. public List<Dictionary<int, List<string>[]>> informationList;
  646. public int defectCount;//informationList中的缺陷数
  647. public List<List<string>> defectInfor2RestorationDesk, defectInfor2RestorationDeskPage;//打标缺陷转为图纸的坐标
  648. public Bitmap[] bmps_tag; //打标小图 //bmps_tag.count<=bmps_cut.count bmps_tag.count=informationList.count
  649. public bool isSucceed;//转换是否成功
  650. public string resultInfo = "";//成功或失败信息
  651. public long[] stopwatch = new long[5];
  652. public List<List<string>> defectInfor2BigImage;
  653. //裁切原图
  654. public Mat CutSrcbmp;
  655. }
  656. public void add(DefectTask task)
  657. {
  658. lock (taskList)
  659. taskList.Add(task);
  660. }
  661. /// <summary>
  662. /// 打标 返回每张图的绝对位置X,Y
  663. /// </summary>
  664. /// <param name="defectBmpIndex">缺陷小图索引</param>
  665. /// <param name="X">拍照位绝对位置-----X2轴</param>
  666. /// <param name="Y">拍照位绝对位置-----Y轴</param>
  667. /// <param name="imagewidth">裁剪小图的宽592</param>
  668. /// <param name="imageheight">裁剪小图的高532</param>
  669. public List<double> makeTag(int defectBmpIndex, double X, double Y, int imagewidth, int imageheight)
  670. {
  671. return yolo1.ImageXY(defectBmpIndex, X, Y, imagewidth, imageheight);
  672. }
  673. /// <summary>
  674. /// 用相机1查看缺陷点
  675. /// </summary>
  676. /// <param name="defectBmpIndex"></param>
  677. /// <param name="X"></param>
  678. /// <param name="Y"></param>
  679. /// <param name="imagewidth"></param>
  680. /// <param name="imageheight"></param>
  681. /// <returns></returns>
  682. public List<double> viewTag(int defectBmpIndex, double X, double Y, int imagewidth, int imageheight)
  683. {
  684. return yolo1.ImageXY2(defectBmpIndex, X, Y, imagewidth, imageheight);
  685. }
  686. private DefectTask pop()
  687. {
  688. lock (taskList)
  689. {
  690. if (taskList.Count < 1)
  691. return null;
  692. //int index = 0;// taskList.FindIndex(p => { return p.isSync; });
  693. //if (index < 0) index = 0;
  694. var task = taskList[0];
  695. taskList.RemoveAt(0);
  696. return task;
  697. }
  698. }
  699. private DefectTask pop2()
  700. {
  701. lock (taskOperationList)
  702. {
  703. if (taskOperationList.Count < 1)
  704. return null;
  705. //int index = 0;// taskList.FindIndex(p => { return p.isSync; });
  706. //if (index < 0) index = 0;
  707. var task = taskOperationList[0];
  708. taskOperationList.RemoveAt(0);
  709. return task;
  710. }
  711. }
  712. private DefectTask pop3()
  713. {
  714. lock (taskTagList)
  715. {
  716. if (taskTagList.Count < 1)
  717. return null;
  718. //int index = 0;// taskList.FindIndex(p => { return p.isSync; });
  719. //if (index < 0) index = 0;
  720. var task = taskTagList[0];
  721. taskTagList.RemoveAt(0);
  722. return task;
  723. }
  724. }
  725. public void Dispose()
  726. {
  727. stop();
  728. }
  729. }
  730. }