版博士V2.0程序
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

SizeLib.cs 22 KiB

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