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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449
  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. task.Zoom_Image_mat = yolo5.ResizesMat_4(task.Zoom_Image_mat);
  207. if (ConfMgr.Instance.SysConfigParams.OpenFlawDistribution)
  208. {
  209. //大图缺陷坐标转换到图纸坐标
  210. step = 14;
  211. if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0)
  212. task.defectInfor2RestorationDeskPage = yolo5.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk);
  213. }
  214. }
  215. break;
  216. case 111:
  217. task.MarkPointList[0] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_1");
  218. task.MarkPointList[1] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_1");
  219. break;
  220. case 222:
  221. task.MarkPointList[2] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_2");
  222. task.MarkPointList[3] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_2");
  223. break;
  224. case 333:
  225. task.MarkPointList[4] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_3");
  226. task.MarkPointList[5] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_3");//ContoursAffineTrans1
  227. task.ContoursAffineTrans1_Out = ProcCall1_PI_PT.GetOutputIconicParamObject("ContoursAffineTrans1_Out");
  228. break;
  229. case 444:
  230. task.MarkPointList[6] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_4");
  231. task.MarkPointList[7] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_4");
  232. break;
  233. case 3333: //Tag使用,同时继续获取使用default时时校正和其它值
  234. step = 80;
  235. if (!string.IsNullOrWhiteSpace( task.sizeTag))
  236. task.posePT= ProcCall1_PI_PT.GetOutputCtrlParamTuple("posePT").DArr;
  237. goto default;
  238. default:
  239. step = 90;
  240. task.PT1 = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("DistancePT1");//index=8 PT1=PT2
  241. task.PT2 = ProcCall1_PI_PT.GetOutputCtrlParamTuple("DistancePT2");
  242. task.Shanxian = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Distance3Median");
  243. //task.RowP = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("RowP");
  244. task.Circle_Ymm = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Circle_Ymm");
  245. task.Circle_Xmm = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Circle_Xmm");
  246. task.offsetX = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("offsetX");
  247. task.offsetY = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("offsetY");
  248. break;
  249. }
  250. step = 5;
  251. //尺寸标注
  252. if (task.index != 3333)
  253. {
  254. try
  255. {
  256. step = 6;
  257. double[] posePTarr;
  258. try
  259. {
  260. if (ProcCall1_PI_PT.GetOutputCtrlParamTuple("posePT") != null &&
  261. ProcCall1_PI_PT.GetOutputCtrlParamTuple("posePT").DArr != null)
  262. posePTarr = ProcCall1_PI_PT.GetOutputCtrlParamTuple("posePT").DArr;
  263. else
  264. posePTarr = null;
  265. }
  266. catch {
  267. posePTarr = null;
  268. }
  269. step = 7;
  270. //Yolo_Class yolo = new Yolo_Class();
  271. step = 8;
  272. var mat = CamDev.HImageToMat(image);
  273. step = 9;
  274. //task.SaveMat = yolo.DisplayLines(mat, posePT, task.index).Clone();
  275. task.SaveMat = yolo5.DisplayLines(mat, posePTarr, task.index);
  276. }
  277. catch (Exception ex)
  278. {
  279. WarningEvent?.Invoke(WarningEnum.Low, $"SizeLib task err({step}) index({task.index}):" + ex.Message);
  280. task.SaveMat = null;
  281. }
  282. }
  283. step = 100;
  284. ProcCall1_PI_PT.Dispose();
  285. Program1.Dispose();
  286. step = 101;
  287. task.isSucceed = true;
  288. task.resultInfo = "成功";
  289. callback(task);
  290. step = 102;
  291. }
  292. Thread.Sleep(5);
  293. }
  294. catch (Exception ex)
  295. {
  296. WarningEvent?.Invoke(WarningEnum.Low, $"SizeLib task err({step}) index({task.index}):"+ ex.Message);
  297. task.isSucceed = false;
  298. task.resultInfo = $"(errcode:{step}):{ex.Message}";
  299. callback(task);
  300. }
  301. }
  302. }
  303. private void callback(SizeTask task)
  304. {
  305. //返回成功/失败,异步调用
  306. if (task.finishEvent != null || (task.finishEvent = finishEvent) != null)
  307. //task.finishEvent.BeginInvoke(result, errInfo, res => task.finishEvent.EndInvoke(res), null);
  308. System.Threading.ThreadPool.QueueUserWorkItem(waitCallback, task);
  309. }
  310. //异步回调
  311. WaitCallback waitCallback = new WaitCallback(o => {
  312. var task = (SizeTask)o;
  313. task.finishEvent(task);
  314. });
  315. //=======task list
  316. private List<SizeTask> taskList = new List<SizeTask>();
  317. public class SizeTask
  318. {
  319. public int stepIndex;//只为回调记录当前工序信息
  320. public string processName;//只为回调记录当前工序信息
  321. public string engineName,sizeTag;
  322. /// <summary>
  323. /// 源文件
  324. /// </summary>
  325. public string file_path;
  326. public double posX,posY;
  327. public HObject Himage;
  328. public string drawingPagePath = "";//.gbx图纸路径
  329. //2023-10-27 新增图纸选择pt点位与线宽点位
  330. public int[] Adapter;
  331. public double[] PTandLinePos;
  332. public double[] AdapterPos;
  333. /// <summary>
  334. /// 比对(index=777); 计算Mark(111/222/333/444); 尺寸(1-9); 轴偏移调整(10,20,30...)
  335. /// </summary>
  336. public int index; //index=8 PT1=PT2
  337. /// <summary>
  338. /// 完成后回调
  339. /// </summary>
  340. public Action<SizeTask> finishEvent;
  341. public long createTime = DateTime.Now.Ticks;
  342. //==结果返回
  343. /// <summary>
  344. /// 比对结果(index=777)
  345. /// </summary>
  346. public bool CompResult;
  347. public Mat Zoom_Image_mat;//对比打标图:777比对失败时计算得出,后面显示到UI 以后修复台用
  348. public List<List<string>> defectInfor2RestorationDesk, defectInfor2RestorationDeskPage;//对比未通过坐标信息,合并到缺陷检测中的 //打标缺陷转为图纸的坐标;
  349. //MARK点
  350. public double[] MarkPointList = { 0, 0, 0, 0, 0, 0, 0, 0 };
  351. public HObject ContoursAffineTrans1_Out;//index=333时输出,供后面多个777比对时输入使用
  352. public double[] posePT;//index=3333 && !isEmpty(sizeTag) 才取此数组值,len为0时急停
  353. //
  354. public double PT1,PT2, Shanxian, Circle_Ymm, Circle_Xmm, offsetX, offsetY;
  355. public bool isSucceed;//转换是否成功
  356. public string resultInfo = "";//成功或失败信息
  357. public Mat SaveMat;
  358. }
  359. public void add(SizeTask task)
  360. {
  361. lock (taskList)
  362. taskList.Add(task);
  363. }
  364. private SizeTask pop()
  365. {
  366. lock (taskList)
  367. {
  368. if (taskList.Count < 1)
  369. return null;
  370. var task = taskList[0];
  371. taskList.RemoveAt(0);
  372. return task;
  373. }
  374. }
  375. public void Dispose()
  376. {
  377. stop();
  378. }
  379. /// <summary>
  380. /// Bitmap转HObject灰度图
  381. /// </summary>
  382. /// <param name="bmp">Bitmap图像</param>
  383. /// <param name="image">HObject图像</param>
  384. private void Bitmap2HObjectBpp8( out HObject image,Bitmap bmp)
  385. {
  386. try
  387. {
  388. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
  389. BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
  390. HOperatorSet.GenImage1(out image, "byte", bmp.Width, bmp.Height, srcBmpData.Scan0);
  391. bmp.UnlockBits(srcBmpData);
  392. }
  393. catch (Exception)
  394. {
  395. image = null;
  396. }
  397. }
  398. public void Bitmap2HObjectBpp24( out HObject image, Bitmap bmp)
  399. {
  400. try
  401. {
  402. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
  403. BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format24bppRgb);
  404. HOperatorSet.GenImageInterleaved(out image, srcBmpData.Scan0, "bgr", bmp.Width, bmp.Height, 0, "byte", 0, 0, 0, 0, -1, 0);
  405. bmp.UnlockBits(srcBmpData);
  406. }
  407. catch (Exception ex)
  408. {
  409. image = null;
  410. }
  411. }
  412. }
  413. }