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.

SizeLib.cs 25 KiB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. #define JB
  2. #define SmallPic //比对小图
  3. using HalconDotNet;
  4. using MaiMuAOI.SysCtrl;
  5. using MaiMuControl.Device;
  6. using MaiMuControl.Device.CamDev;
  7. using Newtonsoft.Json;
  8. using Newtonsoft.Json.Linq;
  9. using OpenCvSharp;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Drawing;
  13. using System.Drawing.Imaging;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Reflection;
  17. using System.Text;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. using Yolo5;
  21. namespace MaiMuAOI.ImageProcessing
  22. {
  23. public class SizeLib : IDisposable
  24. {
  25. public Action<WarningEnum, string> WarningEvent;
  26. /// <summary>
  27. /// 检测结果JSON(原图,结果)
  28. /// </summary>
  29. public Action<SizeTask> 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. //配置
  36. HDevEngine MyEngine = new HDevEngine();
  37. //777时用
  38. Yolo_Class yolo5 =new Yolo_Class();
  39. private Thread t_task;
  40. public SizeLib()
  41. {
  42. }
  43. public bool start(string enginePath)
  44. {
  45. try
  46. {
  47. IsInit = true;
  48. taskList.Clear();
  49. MyEngine.SetProcedurePath(enginePath);
  50. t_task = new System.Threading.Thread(run);
  51. t_task.IsBackground = true;
  52. t_task.Start();
  53. return true;
  54. }
  55. catch (Exception ex)
  56. {
  57. WarningEvent?.Invoke(WarningEnum.High,ex.Message);
  58. return false;
  59. }
  60. }
  61. public void stop()
  62. {
  63. if (!IsInit) return;
  64. try
  65. {
  66. IsInit = false;
  67. //timer.Elapsed -= Timer_Elapsed;
  68. MyEngine.Dispose();
  69. }
  70. catch { }
  71. }
  72. private bool _debug = false;
  73. public bool setDebug {
  74. get { return _debug; }
  75. set {
  76. if (!IsInit) return;
  77. _debug=value;
  78. if (_debug)
  79. MyEngine.StartDebugServer();
  80. else
  81. MyEngine.StopDebugServer();
  82. }
  83. }
  84. //流程:111,222,444,333,777,777,777,。。。
  85. private void run()
  86. {
  87. int taskCount;
  88. while (IsInit)
  89. {
  90. lock (taskList)
  91. {
  92. taskCount = taskList.Count;
  93. }
  94. if (taskCount < 1)
  95. {
  96. Thread.Sleep(10);
  97. continue;
  98. }
  99. ////
  100. int step = 0;
  101. var task = pop();
  102. try
  103. {
  104. if (task != null)
  105. {
  106. var Program1 = new HDevProcedure(task.engineName);
  107. HDevProcedureCall ProcCall1_PI_PT = new HDevProcedureCall(Program1);
  108. step = 1;
  109. //
  110. HObject image;
  111. if (task.Himage != null)
  112. image = task.Himage.Clone();
  113. //Bitmap2HObjectBpp24(out image, task.bmp);
  114. else
  115. HOperatorSet.ReadImage(out image, task.file_path);
  116. step = 2;
  117. //设置外部函数输入
  118. //if (task.index < 100)
  119. {
  120. ProcCall1_PI_PT.SetInputIconicParamObject("Image1", image.Clone());
  121. ProcCall1_PI_PT.SetInputCtrlParamTuple("index", task.index);//参数1-9
  122. ProcCall1_PI_PT.SetInputCtrlParamTuple("posX", task.posX);
  123. ProcCall1_PI_PT.SetInputCtrlParamTuple("posY", task.posY);
  124. ProcCall1_PI_PT.SetInputCtrlParamTuple("GerberPath",new HTuple( task.drawingPagePath));//美尚没有
  125. //设置外部函数输入
  126. if ((task.PTandLinePos != null) && (task.PTandLinePos[0] != 0))
  127. {
  128. double[] posarray = new double[23];
  129. posarray[0] = task.PTandLinePos[0];
  130. posarray[1] = task.PTandLinePos[2];
  131. posarray[2] = task.PTandLinePos[4];
  132. posarray[3] = task.PTandLinePos[6];
  133. posarray[4] = task.PTandLinePos[8];
  134. for (int i = 0; i < 18; i++)
  135. {
  136. posarray[5 + i] = task.PTandLinePos[10 + i];
  137. }
  138. //ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", posarray);
  139. ProcCall1_PI_PT.SetInputCtrlParamTuple("Adapter", task.Adapter);
  140. if (task.AdapterPos != null)
  141. {
  142. WarningEvent?.Invoke(WarningEnum.Normal, $"PTandLinePos1:" + $",{JsonConvert.SerializeObject(task.PTandLinePos)},||{JsonConvert.SerializeObject(task.Adapter)},||{JsonConvert.SerializeObject(task.AdapterPos)}");
  143. ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", task.AdapterPos);
  144. }
  145. else
  146. {
  147. WarningEvent?.Invoke(WarningEnum.Normal, $"PTandLinePos2:" + $",{JsonConvert.SerializeObject(task.PTandLinePos)},||{JsonConvert.SerializeObject(task.Adapter)},||{JsonConvert.SerializeObject(task.AdapterPos)}");
  148. //ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", task.AdapterPos);
  149. ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", posarray);
  150. }
  151. /////
  152. ///
  153. //string directory = Config.LogPath + "\\" + DateTime.Now.ToString("yyyyMM") + "\\";
  154. //if (!System.IO.Directory.Exists(directory))
  155. // System.IO.Directory.CreateDirectory(directory);
  156. //File.AppendAllText(directory + "sizeData.log", "data:" + string.Join(",", posarray) + "\r\n");
  157. }
  158. else if (task.AdapterPos != null)
  159. {
  160. WarningEvent?.Invoke(WarningEnum.Normal, $"PTandLinePos3:" + $",{JsonConvert.SerializeObject(task.PTandLinePos)},||{JsonConvert.SerializeObject(task.Adapter)},||{JsonConvert.SerializeObject(task.AdapterPos)}");
  161. ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", task.AdapterPos);
  162. ProcCall1_PI_PT.SetInputCtrlParamTuple("Adapter", task.Adapter);
  163. ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", task.AdapterPos);
  164. }
  165. else
  166. {
  167. WarningEvent?.Invoke(WarningEnum.Normal, $"PTandLinePos4:" + $",{JsonConvert.SerializeObject(task.PTandLinePos)},||{JsonConvert.SerializeObject(task.Adapter)},||{JsonConvert.SerializeObject(task.AdapterPos)}");
  168. ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", task.AdapterPos);
  169. double[] posarray = new double[23];
  170. task.Adapter = new int[ConfMgr.Instance.SizeItemParamsList.Count];
  171. task.Adapter[0] = 5;
  172. task.Adapter[1] = 18;
  173. ProcCall1_PI_PT.SetInputCtrlParamTuple("Adapter", task.Adapter);
  174. ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", posarray);
  175. }
  176. }
  177. if (task.index == 777)
  178. {
  179. if(task.ContoursAffineTrans1_Out != null)
  180. ProcCall1_PI_PT.SetInputIconicParamObject("ContoursAffineTrans1", task.ContoursAffineTrans1_Out);
  181. }
  182. else if (task.index == 77777)
  183. {
  184. ProcCall1_PI_PT.SetInputIconicParamObject("ContoursAffineTrans1", task.ContoursAffineTrans1_Out);
  185. }
  186. else
  187. {
  188. HObject ContoursAffineTrans1;
  189. HOperatorSet.GenEmptyObj(out ContoursAffineTrans1);
  190. ProcCall1_PI_PT.SetInputIconicParamObject("ContoursAffineTrans1", ContoursAffineTrans1);
  191. }
  192. step = 3;
  193. ProcCall1_PI_PT.Execute();//执行外部函数
  194. step = 4;
  195. //获取外部函数输出
  196. switch (task.index)
  197. {
  198. case 77777:
  199. case 777://比对结果
  200. step = 10;
  201. task.CompResult = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("RES") == 1;//结果,1为true,0为false
  202. task.ResSts = (int)ProcCall1_PI_PT.GetOutputCtrlParamTuple("RES"); step = 11;
  203. if (!task.CompResult)
  204. {
  205. var Defects_X = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_X");
  206. var Defects_Y = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_Y");
  207. var Defects_LeftTop_X = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_LeftTop_X");
  208. var Defects_LeftTop_Y = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_LeftTop_Y");
  209. var Defects_RightBottom_X = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_RightBottom_X");
  210. var Defects_RightBottom_Y = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_RightBottom_Y");
  211. var Contour_Image = ProcCall1_PI_PT.GetOutputIconicParamObject("Contour_Image");
  212. //var Zoom_Image = ProcCall1_PI_PT.GetOutputIconicParamObject("Zoom_Image");
  213. var Defects_Type = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_Type");
  214. var Defects_Index = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_Index");
  215. step = 12;
  216. //对比打标图:显示在UI上,以后修复台用
  217. //task.Zoom_Image_mat = yolo5.DrawContour_Opencv(Contour_Image, Zoom_Image, Defects_LeftTop_X, Defects_LeftTop_Y, Defects_RightBottom_X, Defects_RightBottom_Y);
  218. //新YOLO.DLL
  219. task.defectInfor2RestorationDesk = new List<List<string>>();
  220. #if SmallPic
  221. task.DB_Image_mat = yolo5.DrawContour_Opencv(Contour_Image, image, Defects_LeftTop_X, Defects_LeftTop_Y,
  222. Defects_RightBottom_X, Defects_RightBottom_Y, Defects_Type, Defects_Index, Defects_X, Defects_Y, out task.defectInfor2RestorationDesk, out task.CompareDefectInfo2BigImage);
  223. //获取打标小图
  224. task.DB_Image_Smallmat = yolo5.CropCompareImage(task.DB_Image_mat, task.CompareDefectInfo2BigImage);
  225. #else
  226. task.DB_Image_mat = yolo5.DrawContour_Opencv(Contour_Image, image, Defects_LeftTop_X, Defects_LeftTop_Y,
  227. Defects_RightBottom_X, Defects_RightBottom_Y, Defects_Type, Defects_Index, Defects_X, Defects_Y, out task.defectInfor2RestorationDesk);
  228. #endif
  229. //SysMgr.Instance.AddSizeDefectData(task.posX, task.posY, task.defectInfor2RestorationDesk);
  230. //WarningEvent?.Invoke(WarningEnum.Normal, $"SizeLib 777 call DrawContour_Opencv(),Defects_LeftTop_X={Defects_LeftTop_X}," +
  231. // $"Defects_LeftTop_Y={Defects_LeftTop_Y},Defects_RightBottom_X={Defects_RightBottom_X},Defects_RightBottom_Y={Defects_RightBottom_Y}," +
  232. // $"Defects_Type={Defects_Type},Defects_Index={Defects_Index},Defects_X={Defects_X},Defects_Y={Defects_Y}," +
  233. // $"defectInfor2RestorationDesk={JsonConvert.SerializeObject(task.defectInfor2RestorationDesk)}");
  234. step = 13;
  235. task.Zoom_Image_mat = yolo5.ResizesMat_4(task.DB_Image_mat);
  236. if (!task.CompResult)
  237. {
  238. if (ConfMgr.Instance.SysConfigParams.OpenFlawDistribution)
  239. {
  240. //大图缺陷坐标转换到图纸坐标
  241. step = 14;
  242. if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0)
  243. task.defectInfor2RestorationDeskPage = yolo5.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk);
  244. }
  245. }
  246. }
  247. #if JB
  248. var shanxian = ProcCall1_PI_PT.GetOutputIconicParamObject("Image_shanxian");
  249. task.JB_Mat = yolo5.HImageToMat(shanxian);
  250. #endif
  251. break;
  252. case 111:
  253. task.MarkPointList[0] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_1");
  254. task.MarkPointList[1] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_1");
  255. break;
  256. case 222:
  257. task.MarkPointList[2] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_2");
  258. task.MarkPointList[3] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_2");
  259. break;
  260. case 333:
  261. task.MarkPointList[4] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_3");
  262. task.MarkPointList[5] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_3");//ContoursAffineTrans1
  263. task.ContoursAffineTrans1_Out = ProcCall1_PI_PT.GetOutputIconicParamObject("ContoursAffineTrans1_Out");
  264. break;
  265. case 444:
  266. task.MarkPointList[6] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_4");
  267. task.MarkPointList[7] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_4");
  268. break;
  269. case 3333: //Tag使用,同时继续获取使用default时时校正和其它值
  270. step = 80;
  271. if (!string.IsNullOrWhiteSpace( task.sizeTag))
  272. task.posePT= ProcCall1_PI_PT.GetOutputCtrlParamTuple("posePT").DArr;
  273. goto default;
  274. default:
  275. step = 90;
  276. task.PT1 = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("DistancePT1");//index=8 PT1=PT2
  277. task.PT2 = ProcCall1_PI_PT.GetOutputCtrlParamTuple("DistancePT2");
  278. task.Shanxian = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Distance3Median");
  279. //task.RowP = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("RowP");
  280. task.Circle_Ymm = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Circle_Ymm");
  281. task.Circle_Xmm = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Circle_Xmm");
  282. task.offsetX = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("offsetX");
  283. task.offsetY = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("offsetY");
  284. break;
  285. }
  286. step = 5;
  287. //尺寸标注
  288. if (task.index != 3333)
  289. {
  290. try
  291. {
  292. step = 6;
  293. double[] posePTarr;
  294. try
  295. {
  296. if (ProcCall1_PI_PT.GetOutputCtrlParamTuple("posePT") != null &&
  297. ProcCall1_PI_PT.GetOutputCtrlParamTuple("posePT").DArr != null)
  298. posePTarr = ProcCall1_PI_PT.GetOutputCtrlParamTuple("posePT").DArr;
  299. else
  300. posePTarr = null;
  301. }
  302. catch
  303. {
  304. posePTarr = null;
  305. }
  306. step = 7;
  307. //Yolo_Class yolo = new Yolo_Class();
  308. step = 8;
  309. var mat = CamDev.HImageToMat(image);
  310. step = 9;
  311. //task.SaveMat = yolo.DisplayLines(mat, posePT, task.index).Clone();
  312. task.SaveMat = yolo5.DisplayLines(mat, posePTarr, task.index);
  313. }
  314. catch (Exception ex)
  315. {
  316. WarningEvent?.Invoke(WarningEnum.Low, $"SizeLib task err({step}) index({task.index}):" + ex.Message);
  317. task.SaveMat = null;
  318. }
  319. }
  320. step = 100;
  321. ProcCall1_PI_PT.Dispose();
  322. Program1.Dispose();
  323. step = 101;
  324. task.isSucceed = true;
  325. task.resultInfo = "成功";
  326. callback(task);
  327. step = 102;
  328. }
  329. Thread.Sleep(5);
  330. }
  331. catch (Exception ex)
  332. {
  333. WarningEvent?.Invoke(WarningEnum.Low, $"SizeLib task err({step}) index({task.index}):"+ ex.Message + $",{task.PTandLinePos},{task.Adapter},{task.AdapterPos}");
  334. task.isSucceed = false;
  335. task.resultInfo = $"(errcode:{step}):{ex.Message}";
  336. callback(task);
  337. }
  338. }
  339. }
  340. private void callback(SizeTask task)
  341. {
  342. //返回成功/失败,异步调用
  343. if (task.finishEvent != null || (task.finishEvent = finishEvent) != null)
  344. //task.finishEvent.BeginInvoke(result, errInfo, res => task.finishEvent.EndInvoke(res), null);
  345. System.Threading.ThreadPool.QueueUserWorkItem(waitCallback, task);
  346. }
  347. //异步回调
  348. WaitCallback waitCallback = new WaitCallback(o => {
  349. var task = (SizeTask)o;
  350. task.finishEvent(task);
  351. });
  352. //=======task list
  353. private List<SizeTask> taskList = new List<SizeTask>();
  354. public class SizeTask
  355. {
  356. public int stepIndex;//只为回调记录当前工序信息
  357. public string processName;//只为回调记录当前工序信息
  358. public string engineName,sizeTag;
  359. /// <summary>
  360. /// 源文件
  361. /// </summary>
  362. public string file_path;
  363. public double posX,posY;
  364. public HObject Himage;
  365. public HObject Himage_src;
  366. public string drawingPagePath = "";//.gbx图纸路径
  367. //2023-10-27 新增图纸选择pt点位与线宽点位
  368. public int[] Adapter;
  369. public double[] PTandLinePos;
  370. public double[] AdapterPos;
  371. /// <summary>
  372. /// 比对(index=777); 计算Mark(111/222/333/444); 尺寸(1-9); 轴偏移调整(10,20,30...)
  373. /// </summary>
  374. public int index; //index=8 PT1=PT2
  375. /// <summary>
  376. /// 完成后回调
  377. /// </summary>
  378. public Action<SizeTask> finishEvent;
  379. public long createTime = DateTime.Now.Ticks;
  380. //==结果返回
  381. /// <summary>
  382. /// 比对结果(index=777)
  383. /// </summary>
  384. public bool CompResult;
  385. public Mat Zoom_Image_mat;//对比打标图:777比对失败时计算得出,后面显示到UI 以后修复台用
  386. public Mat DB_Image_mat;//打标原图,显示使用
  387. public List<List<string>> defectInfor2RestorationDesk, defectInfor2RestorationDeskPage;//对比未通过坐标信息,合并到缺陷检测中的 //打标缺陷转为图纸的坐标;
  388. public List<List<int>> CompareDefectInfo2BigImage;//比对小图序号
  389. public Mat[] DB_Image_Smallmat;//打标小图,显示使用
  390. //MARK点
  391. public double[] MarkPointList = { 0, 0, 0, 0, 0, 0, 0, 0 };
  392. public HObject ContoursAffineTrans1_Out;//index=333时输出,供后面多个777比对时输入使用
  393. public double[] posePT;//index=3333 && !isEmpty(sizeTag) 才取此数组值,len为0时急停
  394. //
  395. public double PT1,PT2, Shanxian, Circle_Ymm, Circle_Xmm, offsetX, offsetY;
  396. public bool isSucceed;//转换是否成功
  397. public string resultInfo = "";//成功或失败信息
  398. public Mat SaveMat;
  399. public Mat JB_Mat;//晶宝使用
  400. public int ResSts;
  401. public int lightCh;
  402. public int lightVal;
  403. public int camexc;
  404. }
  405. public void add(SizeTask task)
  406. {
  407. lock (taskList)
  408. taskList.Add(task);
  409. }
  410. private SizeTask pop()
  411. {
  412. lock (taskList)
  413. {
  414. if (taskList.Count < 1)
  415. return null;
  416. var task = taskList[0];
  417. taskList.RemoveAt(0);
  418. return task;
  419. }
  420. }
  421. public void Dispose()
  422. {
  423. stop();
  424. }
  425. /// <summary>
  426. /// Bitmap转HObject灰度图
  427. /// </summary>
  428. /// <param name="bmp">Bitmap图像</param>
  429. /// <param name="image">HObject图像</param>
  430. private void Bitmap2HObjectBpp8( out HObject image,Bitmap bmp)
  431. {
  432. try
  433. {
  434. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
  435. BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
  436. HOperatorSet.GenImage1(out image, "byte", bmp.Width, bmp.Height, srcBmpData.Scan0);
  437. bmp.UnlockBits(srcBmpData);
  438. }
  439. catch (Exception)
  440. {
  441. image = null;
  442. }
  443. }
  444. public void Bitmap2HObjectBpp24( out HObject image, Bitmap bmp)
  445. {
  446. try
  447. {
  448. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
  449. BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
  450. HOperatorSet.GenImageInterleaved(out image, srcBmpData.Scan0, "bgr", bmp.Width, bmp.Height, 0, "byte", 0, 0, 0, 0, -1, 0);
  451. bmp.UnlockBits(srcBmpData);
  452. }
  453. catch (Exception ex)
  454. {
  455. image = null;
  456. }
  457. }
  458. }
  459. }