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

409 lines
20 KiB

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