Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 

510 rader
20 KiB

  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.Linq;
  8. using System.Reflection;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Microsoft.ML.OnnxRuntime;
  12. using Microsoft.ML.OnnxRuntime.Tensors;
  13. using OpenCvSharp;
  14. using Yolo5;
  15. namespace ProductionControl.Device
  16. {
  17. public class DefectLib : IDisposable
  18. {
  19. public Action<WarningEnum, string> WarningEvent;
  20. /// <summary>
  21. /// 检测结果JSON(原图,结果)
  22. /// </summary>
  23. public Action<DefectTask> finishEvent;
  24. /// <summary>
  25. /// 是否打开设备成功
  26. /// </summary>
  27. public bool IsInit { get; private set; } = false;
  28. //private System.Timers.Timer timer = new System.Timers.Timer();
  29. private Yolo_Class yolo1;
  30. private InferenceSession _onnxSession;
  31. //
  32. private Thread t_task, t_task_operation, t_task_operation2, t_task_tag;
  33. //=======task list
  34. private List<DefectTask> taskList = new List<DefectTask>();
  35. private List<DefectTask> taskOperationList = new List<DefectTask>();
  36. private List<DefectTask> taskTagList = new List<DefectTask>();
  37. public DefectLib()
  38. {
  39. }
  40. public bool start()
  41. {
  42. try
  43. {
  44. yolo1 = new Yolo_Class();
  45. //加载模型(只加载一次即可)
  46. //string modelFilePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\DevCfg\\best.onnx";
  47. //_onnxSession = yolo1.LoadModel(modelFilePath, true);//false-CPU true-显卡
  48. IsInit = true;
  49. //timer.Elapsed += Timer_Elapsed;
  50. //timer.Interval = 100;
  51. //timer.Enabled = true;
  52. taskList.Clear();
  53. taskOperationList.Clear();
  54. taskTagList.Clear();
  55. t_task = new System.Threading.Thread(runStep);
  56. t_task.IsBackground = true;
  57. t_task.Start();
  58. t_task_operation = new System.Threading.Thread(run2);
  59. t_task_operation.IsBackground = true;
  60. t_task_operation.Start();
  61. t_task_operation2 = new System.Threading.Thread(run2);
  62. t_task_operation2.IsBackground = true;
  63. t_task_operation2.Start();
  64. //t_task_tag = new System.Threading.Thread(run3);
  65. //t_task_tag.IsBackground = true;
  66. //t_task_tag.Start();
  67. return true;
  68. }
  69. catch (Exception ex)
  70. {
  71. WarningEvent?.Invoke(WarningEnum.High, ex.Message);
  72. return false;
  73. }
  74. }
  75. public void stop()
  76. {
  77. if (!IsInit) return;
  78. try
  79. {
  80. IsInit = false;
  81. //timer.Elapsed -= Timer_Elapsed;
  82. //释放模型
  83. if (_onnxSession != null)
  84. {
  85. _onnxSession.Dispose();
  86. _onnxSession = null;
  87. }
  88. _preLoadONNXFilePath = null;
  89. if (t_task != null)
  90. {
  91. bool b = t_task.Join(5000);
  92. if (!b) t_task.Abort();
  93. t_task = null;
  94. }
  95. if (t_task_operation != null)
  96. {
  97. bool b = t_task_operation.Join(5000);
  98. if (!b) t_task_operation.Abort();
  99. t_task_operation = null;
  100. }
  101. if (t_task_operation2 != null)
  102. {
  103. bool b = t_task_operation2.Join(5000);
  104. if (!b) t_task_operation2.Abort();
  105. t_task_operation2 = null;
  106. }
  107. if (t_task_tag != null)
  108. {
  109. bool b = t_task_tag.Join(5000);
  110. if (!b) t_task_tag.Abort();
  111. t_task_tag = null;
  112. }
  113. taskList.Clear();
  114. taskOperationList.Clear();
  115. taskTagList.Clear();
  116. }
  117. catch { }
  118. }
  119. private string _preLoadONNXFilePath;//记录上次成功加载的模型,不重复加载
  120. public void loadModelFile(string onnxFilePath)
  121. {
  122. //string modelFilePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\DevCfg\\best.onnx";
  123. //不重复加载
  124. if (!string.IsNullOrWhiteSpace(_preLoadONNXFilePath) && _preLoadONNXFilePath.ToLower() == onnxFilePath.ToLower())
  125. return;
  126. Task.Run(async () =>
  127. {
  128. if (_onnxSession != null)
  129. {
  130. _onnxSession.Dispose();
  131. _onnxSession = null;
  132. }
  133. _onnxSession = yolo1.LoadModel(onnxFilePath, true);//false-CPU true-显卡
  134. _preLoadONNXFilePath = onnxFilePath;
  135. });
  136. }
  137. /// <summary>
  138. /// 保存图片
  139. /// </summary>
  140. /// <param name="Img"></param>图片
  141. /// <param name="pictureUrl"></param>保存路径
  142. /// <param name="pictureName"></param>保存名称
  143. private void SaveImage(Bitmap Img, string pictureUrl, string pictureName)
  144. {
  145. if (!Directory.Exists(pictureUrl))
  146. {
  147. Directory.CreateDirectory(pictureUrl);
  148. }
  149. FileInfo FileUrl = new FileInfo(pictureUrl);//防止路径中有日期导致路径错误
  150. try
  151. {
  152. using (Bitmap bitmap = new Bitmap(Img))
  153. {
  154. using (MemoryStream stream = new MemoryStream())
  155. {
  156. bitmap.Save(stream, ImageFormat.Bmp);
  157. System.Drawing.Image img = System.Drawing.Image.FromStream(stream);
  158. //img.Save(FileUrl +"\\"+ pictureName);
  159. //img.Dispose();
  160. string szURL = FileUrl + "\\" + pictureName;
  161. img.Save(szURL, ImageFormat.Bmp);
  162. img.Dispose();
  163. }
  164. }
  165. }
  166. catch (Exception)
  167. {
  168. if (Img != null)
  169. {
  170. Img.Dispose();
  171. }
  172. }
  173. }
  174. private void runStep()
  175. {
  176. while (IsInit)
  177. {
  178. if (taskList.Count < 1 || _onnxSession == null)
  179. {
  180. Thread.Sleep(5);
  181. continue;
  182. }
  183. //
  184. var task = pop();
  185. try
  186. {
  187. if (task != null)
  188. {
  189. Stopwatch stopwatch = Stopwatch.StartNew();
  190. //源图
  191. //Bitmap bmp = yolo1.Read2Bmp(file_path);
  192. //切割图像,输入图像格式14208*10640
  193. stopwatch.Start();
  194. task.bmps_cut = yolo1.OpenCVToCutsMat(task.bmp, task.cut_size.Width, task.cut_size.Height);
  195. stopwatch.Stop();
  196. task.stopwatch[0] = stopwatch.ElapsedMilliseconds;
  197. //Resize图像
  198. stopwatch.Restart();
  199. task.bmps_resize = yolo1.OpenCVToResizesMat(task.bmps_cut, task.resize.Width, task.resize.Height);
  200. stopwatch.Stop();
  201. task.stopwatch[1] = stopwatch.ElapsedMilliseconds;
  202. //预处理模型
  203. stopwatch.Restart();
  204. task.tensors = yolo1.PreprocessImageMat(task.bmps_resize);
  205. stopwatch.Stop();
  206. task.stopwatch[2] = stopwatch.ElapsedMilliseconds;
  207. lock (taskOperationList)
  208. taskOperationList.Add(task);
  209. }
  210. Thread.Sleep(5);
  211. }
  212. catch (Exception ex)
  213. {
  214. WarningEvent?.Invoke(WarningEnum.Low, "DefectLib task1 err:" + ex.Message);
  215. task.isSucceed = false;
  216. task.resultInfo = ex.Message;
  217. callback(task);
  218. }
  219. }
  220. }
  221. private void run2()
  222. {
  223. while (IsInit)
  224. {
  225. if (taskOperationList.Count < 1)
  226. {
  227. Thread.Sleep(5);
  228. continue;
  229. }
  230. //
  231. var task = pop2();
  232. int liStep = 0;
  233. try
  234. {
  235. if (task != null)
  236. {
  237. Stopwatch stopwatch = Stopwatch.StartNew();
  238. //====运行推理(必需单队列)
  239. stopwatch.Start();
  240. IDisposableReadOnlyCollection<DisposableNamedOnnxValue>[] results = yolo1.RunModlel(_onnxSession, task.tensors);
  241. liStep = 1;
  242. if(task.ModelType == "pt")
  243. task.informationList = yolo1.ScreeningResults_YD(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  244. else
  245. task.informationList = yolo1.ScreeningResults_YD_RJ(results, task.bmps_resize, task.thresholds, task.thresholdsClass, task.recAreaThreshold);
  246. liStep = 2;
  247. //当前大图上缺陷个数
  248. int currPicDefectCount = 0;
  249. for (int x = 0; x < task.informationList.Count(); x++)
  250. currPicDefectCount += task.informationList[x].Count();
  251. task.defectCount = currPicDefectCount;
  252. stopwatch.Stop();
  253. task.stopwatch[3] = stopwatch.ElapsedMilliseconds;
  254. liStep = 3;
  255. if (task.informationList.Count > 0)
  256. {
  257. liStep = 4;
  258. //lock (taskTagList)
  259. // taskTagList.Add(task);
  260. //====打标 ,有缺陷返回缺陷图片数组,没缺陷返回所有图片数组
  261. stopwatch.Restart();
  262. task.bmps_tag = yolo1.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  263. task.Xmm, task.Ymm, out task.defectInfor2RestorationDesk);
  264. liStep = 5;
  265. if (Config.OpenFlawDistribution)
  266. {
  267. //大图缺陷坐标转换到图纸坐标
  268. if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0)
  269. task.defectInfor2RestorationDeskPage = yolo1.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk);
  270. }
  271. stopwatch.Stop();
  272. task.stopwatch[4] = stopwatch.ElapsedMilliseconds;
  273. liStep = 6;
  274. task.bmpCompress = yolo1.ResizesMat_4(task.bmp);
  275. task.isSucceed = true;
  276. callback(task);
  277. }
  278. else
  279. {
  280. task.isSucceed = true;
  281. callback(task);
  282. }
  283. }
  284. Thread.Sleep(5);
  285. }
  286. catch (Exception ex)
  287. {
  288. WarningEvent?.Invoke(WarningEnum.Low, $"DefectLib task2 err({liStep}):" + ex.Message);
  289. task.isSucceed = false;
  290. task.resultInfo = ex.Message;
  291. callback(task);
  292. }
  293. }
  294. }
  295. /// <summary>
  296. /// 已不用
  297. /// </summary>
  298. private void run3()
  299. {
  300. while (IsInit)
  301. {
  302. if (taskTagList.Count < 1)
  303. {
  304. Thread.Sleep(0);
  305. continue;
  306. }
  307. //
  308. var task = pop3();
  309. try
  310. {
  311. if (task != null)
  312. {
  313. Stopwatch stopwatch = Stopwatch.StartNew();
  314. //====打标 ,有缺陷返回缺陷图片数组,没缺陷返回所有图片数组
  315. stopwatch.Start();
  316. task.bmps_tag = yolo1.DrawYoloPrediction2Mat(task.bmps_cut, task.informationList, 27, SixLabors.ImageSharp.Color.OrangeRed, task.resize.Width,
  317. task.Xmm,task.Ymm,out task.defectInfor2RestorationDesk);
  318. stopwatch.Stop();
  319. task.stopwatch[4] = stopwatch.ElapsedMilliseconds;
  320. task.isSucceed = true;
  321. callback(task);
  322. }
  323. }
  324. catch (Exception ex)
  325. {
  326. WarningEvent?.Invoke(WarningEnum.Low, "DefectLib task3 err:" + ex.Message);
  327. task.isSucceed = false;
  328. task.resultInfo = ex.Message;
  329. callback(task);
  330. }
  331. }
  332. }
  333. private void callback(DefectTask task)
  334. {
  335. //返回成功/失败,异步调用
  336. if (task.finishEvent != null || (task.finishEvent = finishEvent) != null)
  337. //task.finishEvent.BeginInvoke(result, errInfo, res => task.finishEvent.EndInvoke(res), null);
  338. System.Threading.ThreadPool.QueueUserWorkItem(waitCallback, task);
  339. }
  340. //异步回调
  341. WaitCallback waitCallback = new WaitCallback(o =>
  342. {
  343. var task = (DefectTask)o;
  344. task.finishEvent(task);
  345. });
  346. public class DefectTask
  347. {
  348. public int stepIndex;
  349. public string processName;
  350. public string drawingPagePath;//图纸路径bmp
  351. //图索引
  352. public int index = 0;
  353. /// <summary>
  354. /// 绝对位置-----X2轴
  355. /// </summary>
  356. public double Xmm;
  357. /// <summary>
  358. /// 绝对位置-----Y轴
  359. /// </summary>
  360. public double Ymm;
  361. /// <summary>
  362. /// 源文件
  363. /// </summary>
  364. public Mat bmp;
  365. public Mat bmpCompress;//压缩有缺陷大图
  366. public System.Drawing.Size cut_size = new System.Drawing.Size(592, 532);
  367. public System.Drawing.Size resize = new System.Drawing.Size(224, 224);
  368. /// <summary>
  369. /// 阈值
  370. /// </summary>
  371. public float thresholds = 0.4f;
  372. /// <summary>
  373. /// 种类阈值
  374. /// </summary>
  375. public string thresholdsClass;
  376. /// <summary>
  377. /// 缺陷在面积内数量
  378. /// </summary>
  379. public Dictionary<string, float> recAreaThreshold;
  380. /// <summary>
  381. /// 完成后回调
  382. /// </summary>
  383. public Action<DefectTask> finishEvent;
  384. //
  385. public long createTime = DateTime.Now.Ticks;
  386. public DateTime nowTime;
  387. //中间变量,供step2使用
  388. public Mat[] bmps_cut;
  389. public Mat[] bmps_resize;
  390. //预处理模型
  391. public Tensor<float>[] tensors;
  392. //==结果返回
  393. public List<Dictionary<int, List<string>[]>> informationList;
  394. public int defectCount;//informationList中的缺陷数
  395. public List<List<string>> defectInfor2RestorationDesk, defectInfor2RestorationDeskPage;//打标缺陷转为图纸的坐标
  396. public Bitmap[] bmps_tag; //打标小图 //bmps_tag.count<=bmps_cut.count bmps_tag.count=informationList.count
  397. public bool isSucceed;//转换是否成功
  398. public string resultInfo = "";//成功或失败信息
  399. public long[] stopwatch = new long[5];
  400. public string ModelType = "";
  401. }
  402. public void add(DefectTask task)
  403. {
  404. lock (taskList)
  405. taskList.Add(task);
  406. }
  407. /// <summary>
  408. /// 打标 返回每张图的绝对位置X,Y
  409. /// </summary>
  410. /// <param name="defectBmpIndex">缺陷小图索引</param>
  411. /// <param name="X">拍照位绝对位置-----X2轴</param>
  412. /// <param name="Y">拍照位绝对位置-----Y轴</param>
  413. /// <param name="imagewidth">裁剪小图的宽592</param>
  414. /// <param name="imageheight">裁剪小图的高532</param>
  415. public List<double> makeTag(int defectBmpIndex, double X, double Y, int imagewidth, int imageheight)
  416. {
  417. return yolo1.ImageXY(defectBmpIndex, X, Y, imagewidth, imageheight);
  418. }
  419. /// <summary>
  420. /// 用相机1查看缺陷点
  421. /// </summary>
  422. /// <param name="defectBmpIndex"></param>
  423. /// <param name="X"></param>
  424. /// <param name="Y"></param>
  425. /// <param name="imagewidth"></param>
  426. /// <param name="imageheight"></param>
  427. /// <returns></returns>
  428. public List<double> viewTag(int defectBmpIndex, double X, double Y, int imagewidth, int imageheight)
  429. {
  430. return yolo1.ImageXY2(defectBmpIndex, X, Y, imagewidth, imageheight);
  431. }
  432. private DefectTask pop()
  433. {
  434. lock (taskList)
  435. {
  436. if (taskList.Count < 1)
  437. return null;
  438. //int index = 0;// taskList.FindIndex(p => { return p.isSync; });
  439. //if (index < 0) index = 0;
  440. var task = taskList[0];
  441. taskList.RemoveAt(0);
  442. return task;
  443. }
  444. }
  445. private DefectTask pop2()
  446. {
  447. lock (taskOperationList)
  448. {
  449. if (taskOperationList.Count < 1)
  450. return null;
  451. //int index = 0;// taskList.FindIndex(p => { return p.isSync; });
  452. //if (index < 0) index = 0;
  453. var task = taskOperationList[0];
  454. taskOperationList.RemoveAt(0);
  455. return task;
  456. }
  457. }
  458. private DefectTask pop3()
  459. {
  460. lock (taskTagList)
  461. {
  462. if (taskTagList.Count < 1)
  463. return null;
  464. //int index = 0;// taskList.FindIndex(p => { return p.isSync; });
  465. //if (index < 0) index = 0;
  466. var task = taskTagList[0];
  467. taskTagList.RemoveAt(0);
  468. return task;
  469. }
  470. }
  471. public void Dispose()
  472. {
  473. stop();
  474. }
  475. }
  476. }