版博士V2.0程序
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.
 
 
 
 

436 lines
21 KiB

  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[23];
  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. /////
  142. ///
  143. //string directory = Config.LogPath + "\\" + DateTime.Now.ToString("yyyyMM") + "\\";
  144. //if (!System.IO.Directory.Exists(directory))
  145. // System.IO.Directory.CreateDirectory(directory);
  146. //File.AppendAllText(directory + "sizeData.log", "data:" + string.Join(",", posarray) + "\r\n");
  147. }
  148. else if (task.AdapterPos != null)
  149. {
  150. ProcCall1_PI_PT.SetInputCtrlParamTuple("Adapter", task.Adapter);
  151. ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", task.AdapterPos);
  152. }
  153. else
  154. {
  155. double[] posarray = new double[23];
  156. task.Adapter = new int[9] { 5, 18 ,0,0,0,0,0,0,0};
  157. ProcCall1_PI_PT.SetInputCtrlParamTuple("Adapter", task.Adapter);
  158. ProcCall1_PI_PT.SetInputCtrlParamTuple("UserPose", posarray);
  159. }
  160. }
  161. if (task.index == 777)
  162. {
  163. ProcCall1_PI_PT.SetInputIconicParamObject("ContoursAffineTrans1", task.ContoursAffineTrans1_Out);
  164. }
  165. else
  166. {
  167. HObject ContoursAffineTrans1;
  168. HOperatorSet.GenEmptyObj(out ContoursAffineTrans1);
  169. ProcCall1_PI_PT.SetInputIconicParamObject("ContoursAffineTrans1", ContoursAffineTrans1);
  170. }
  171. step = 3;
  172. ProcCall1_PI_PT.Execute();//执行外部函数
  173. step = 4;
  174. //获取外部函数输出
  175. switch (task.index)
  176. {
  177. case 777://比对结果
  178. step = 10;
  179. task.CompResult = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("RES") == 1;//结果,1为true,0为false
  180. step = 11;
  181. if (!task.CompResult)
  182. {
  183. var Defects_X = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_X");
  184. var Defects_Y = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_Y");
  185. var Defects_LeftTop_X = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_LeftTop_X");
  186. var Defects_LeftTop_Y = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_LeftTop_Y");
  187. var Defects_RightBottom_X = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_RightBottom_X");
  188. var Defects_RightBottom_Y = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_RightBottom_Y");
  189. var Contour_Image = ProcCall1_PI_PT.GetOutputIconicParamObject("Contour_Image");
  190. //var Zoom_Image = ProcCall1_PI_PT.GetOutputIconicParamObject("Zoom_Image");
  191. var Defects_Type = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_Type");
  192. var Defects_Index = ProcCall1_PI_PT.GetOutputCtrlParamTuple("Defects_Index");
  193. step = 12;
  194. //对比打标图:显示在UI上,以后修复台用
  195. //task.Zoom_Image_mat = yolo5.DrawContour_Opencv(Contour_Image, Zoom_Image, Defects_LeftTop_X, Defects_LeftTop_Y, Defects_RightBottom_X, Defects_RightBottom_Y);
  196. //新YOLO.DLL
  197. task.defectInfor2RestorationDesk = new List<List<string>>();
  198. task.Zoom_Image_mat = yolo5.DrawContour_Opencv(Contour_Image, image, Defects_LeftTop_X, Defects_LeftTop_Y,
  199. Defects_RightBottom_X, Defects_RightBottom_Y, Defects_Type, Defects_Index, Defects_X, Defects_Y, out task.defectInfor2RestorationDesk);
  200. //WarningEvent?.Invoke(WarningEnum.Normal, $"SizeLib 777 call DrawContour_Opencv(),Defects_LeftTop_X={Defects_LeftTop_X}," +
  201. // $"Defects_LeftTop_Y={Defects_LeftTop_Y},Defects_RightBottom_X={Defects_RightBottom_X},Defects_RightBottom_Y={Defects_RightBottom_Y}," +
  202. // $"Defects_Type={Defects_Type},Defects_Index={Defects_Index},Defects_X={Defects_X},Defects_Y={Defects_Y}," +
  203. // $"defectInfor2RestorationDesk={JsonConvert.SerializeObject(task.defectInfor2RestorationDesk)}");
  204. step = 13;
  205. task.Zoom_Image_mat = yolo5.ResizesMat_4(task.Zoom_Image_mat);
  206. if (ConfMgr.Instance.SysConfigParams.OpenFlawDistribution)
  207. {
  208. //大图缺陷坐标转换到图纸坐标
  209. step = 14;
  210. if (!string.IsNullOrWhiteSpace(task.drawingPagePath) && task.defectInfor2RestorationDesk != null && task.defectInfor2RestorationDesk.Count > 0)
  211. task.defectInfor2RestorationDeskPage = yolo5.DefectDrawGerberImage(task.drawingPagePath, task.defectInfor2RestorationDesk);
  212. }
  213. }
  214. break;
  215. case 111:
  216. task.MarkPointList[0] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_1");
  217. task.MarkPointList[1] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_1");
  218. break;
  219. case 222:
  220. task.MarkPointList[2] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_2");
  221. task.MarkPointList[3] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_2");
  222. break;
  223. case 333:
  224. task.MarkPointList[4] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_3");
  225. task.MarkPointList[5] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_3");//ContoursAffineTrans1
  226. task.ContoursAffineTrans1_Out = ProcCall1_PI_PT.GetOutputIconicParamObject("ContoursAffineTrans1_Out");
  227. break;
  228. case 444:
  229. task.MarkPointList[6] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkX_4");
  230. task.MarkPointList[7] = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("PoseMarkY_4");
  231. break;
  232. case 3333: //Tag使用,同时继续获取使用default时时校正和其它值
  233. step = 80;
  234. if (!string.IsNullOrWhiteSpace( task.sizeTag))
  235. task.posePT= ProcCall1_PI_PT.GetOutputCtrlParamTuple("posePT").DArr;
  236. goto default;
  237. default:
  238. step = 90;
  239. task.PT1 = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("DistancePT1");//index=8 PT1=PT2
  240. task.PT2 = ProcCall1_PI_PT.GetOutputCtrlParamTuple("DistancePT2");
  241. task.Shanxian = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Distance3Median");
  242. //task.RowP = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("RowP");
  243. task.Circle_Ymm = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Circle_Ymm");
  244. task.Circle_Xmm = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("Circle_Xmm");
  245. task.offsetX = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("offsetX");
  246. task.offsetY = (double)ProcCall1_PI_PT.GetOutputCtrlParamTuple("offsetY");
  247. break;
  248. }
  249. step = 5;
  250. //尺寸标注
  251. if (task.index != 3333)
  252. {
  253. try
  254. {
  255. step = 6;
  256. var posePT = ProcCall1_PI_PT.GetOutputCtrlParamTuple("posePT").DArr;
  257. step = 7;
  258. //Yolo_Class yolo = new Yolo_Class();
  259. step = 8;
  260. var mat = CamDev.HImageToMat(image);
  261. step = 9;
  262. //task.SaveMat = yolo.DisplayLines(mat, posePT, task.index).Clone();
  263. task.SaveMat = yolo5.DisplayLines(mat, posePT, task.index);
  264. }
  265. catch (Exception ex)
  266. {
  267. //WarningEvent?.Invoke(WarningEnum.Low, $"SizeLib task err({step}) index({task.index}):" + ex.Message);
  268. task.SaveMat = null;
  269. }
  270. }
  271. step = 100;
  272. ProcCall1_PI_PT.Dispose();
  273. Program1.Dispose();
  274. step = 101;
  275. task.isSucceed = true;
  276. task.resultInfo = "成功";
  277. callback(task);
  278. step = 102;
  279. }
  280. Thread.Sleep(5);
  281. }
  282. catch (Exception ex)
  283. {
  284. WarningEvent?.Invoke(WarningEnum.Low, $"SizeLib task err({step}) index({task.index}):"+ ex.Message);
  285. task.isSucceed = false;
  286. task.resultInfo = $"(errcode:{step}):{ex.Message}";
  287. callback(task);
  288. }
  289. }
  290. }
  291. private void callback(SizeTask task)
  292. {
  293. //返回成功/失败,异步调用
  294. if (task.finishEvent != null || (task.finishEvent = finishEvent) != null)
  295. //task.finishEvent.BeginInvoke(result, errInfo, res => task.finishEvent.EndInvoke(res), null);
  296. System.Threading.ThreadPool.QueueUserWorkItem(waitCallback, task);
  297. }
  298. //异步回调
  299. WaitCallback waitCallback = new WaitCallback(o => {
  300. var task = (SizeTask)o;
  301. task.finishEvent(task);
  302. });
  303. //=======task list
  304. private List<SizeTask> taskList = new List<SizeTask>();
  305. public class SizeTask
  306. {
  307. public int stepIndex;//只为回调记录当前工序信息
  308. public string processName;//只为回调记录当前工序信息
  309. public string engineName,sizeTag;
  310. /// <summary>
  311. /// 源文件
  312. /// </summary>
  313. public string file_path;
  314. public double posX,posY;
  315. public HObject Himage;
  316. public string drawingPagePath = "";//.gbx图纸路径
  317. //2023-10-27 新增图纸选择pt点位与线宽点位
  318. public int[] Adapter;
  319. public double[] PTandLinePos;
  320. public double[] AdapterPos;
  321. /// <summary>
  322. /// 比对(index=777); 计算Mark(111/222/333/444); 尺寸(1-9); 轴偏移调整(10,20,30...)
  323. /// </summary>
  324. public int index; //index=8 PT1=PT2
  325. /// <summary>
  326. /// 完成后回调
  327. /// </summary>
  328. public Action<SizeTask> finishEvent;
  329. public long createTime = DateTime.Now.Ticks;
  330. //==结果返回
  331. /// <summary>
  332. /// 比对结果(index=777)
  333. /// </summary>
  334. public bool CompResult;
  335. public Mat Zoom_Image_mat;//对比打标图:777比对失败时计算得出,后面显示到UI 以后修复台用
  336. public List<List<string>> defectInfor2RestorationDesk, defectInfor2RestorationDeskPage;//对比未通过坐标信息,合并到缺陷检测中的 //打标缺陷转为图纸的坐标;
  337. //MARK点
  338. public double[] MarkPointList = { 0, 0, 0, 0, 0, 0, 0, 0 };
  339. public HObject ContoursAffineTrans1_Out;//index=333时输出,供后面多个777比对时输入使用
  340. public double[] posePT;//index=3333 && !isEmpty(sizeTag) 才取此数组值,len为0时急停
  341. //
  342. public double PT1,PT2, Shanxian, Circle_Ymm, Circle_Xmm, offsetX, offsetY;
  343. public bool isSucceed;//转换是否成功
  344. public string resultInfo = "";//成功或失败信息
  345. public Mat SaveMat;
  346. }
  347. public void add(SizeTask task)
  348. {
  349. lock (taskList)
  350. taskList.Add(task);
  351. }
  352. private SizeTask pop()
  353. {
  354. lock (taskList)
  355. {
  356. if (taskList.Count < 1)
  357. return null;
  358. var task = taskList[0];
  359. taskList.RemoveAt(0);
  360. return task;
  361. }
  362. }
  363. public void Dispose()
  364. {
  365. stop();
  366. }
  367. /// <summary>
  368. /// Bitmap转HObject灰度图
  369. /// </summary>
  370. /// <param name="bmp">Bitmap图像</param>
  371. /// <param name="image">HObject图像</param>
  372. private void Bitmap2HObjectBpp8( out HObject image,Bitmap bmp)
  373. {
  374. try
  375. {
  376. Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
  377. BitmapData srcBmpData = bmp.LockBits(rect, ImageLockMode.ReadOnly, PixelFormat.Format8bppIndexed);
  378. HOperatorSet.GenImage1(out image, "byte", bmp.Width, bmp.Height, srcBmpData.Scan0);
  379. bmp.UnlockBits(srcBmpData);
  380. }
  381. catch (Exception)
  382. {
  383. image = null;
  384. }
  385. }
  386. public void Bitmap2HObjectBpp24( 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.Format24bppRgb);
  392. HOperatorSet.GenImageInterleaved(out image, srcBmpData.Scan0, "bgr", bmp.Width, bmp.Height, 0, "byte", 0, 0, 0, 0, -1, 0);
  393. bmp.UnlockBits(srcBmpData);
  394. }
  395. catch (Exception ex)
  396. {
  397. image = null;
  398. }
  399. }
  400. }
  401. }