OTSImageDisHelp.cs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  1. using OpenCvSharp;
  2. using OTSCLRINTERFACE;
  3. using OTSCommon.Model;
  4. using OTSIncAReportApp.DataOperation.DataAccess;
  5. using OTSIncAReportApp.SysMgrTools;
  6. using OTSIncAReportGraph.Class;
  7. using OTSIncAReportGraph.Controls;
  8. using OTSModelSharp.DTLBase;
  9. using OTSModelSharp.ServiceCenter;
  10. using System;
  11. using System.Collections;
  12. using System.Collections.Generic;
  13. using System.Data;
  14. using System.Diagnostics;
  15. using System.Drawing;
  16. using System.Drawing.Drawing2D;
  17. using System.IO;
  18. using System.Linq;
  19. using System.Runtime.Serialization.Formatters.Binary;
  20. using Point = System.Drawing.Point;
  21. namespace OTSIncAReportGraph.OTSIncAReportGraphFuncation
  22. {
  23. public class OTSImageDisHelp
  24. {
  25. #region 枚举定义
  26. /// <summary>
  27. /// 样品台X轴方向
  28. /// </summary>
  29. enum OTS_X_AXIS_DIRECTION
  30. {
  31. LEFT_TOWARD = 0,
  32. RIGHT_TOWARD = 1
  33. }
  34. /// <summary>
  35. /// 样品台Y轴方向
  36. /// </summary>
  37. enum OTS_Y_AXIS_DIRECTION
  38. {
  39. UP_TOWARD = 0,
  40. DOWN_TOWARD = 1
  41. }
  42. #endregion
  43. #region 定义变量
  44. private ResultFile resultFile = null;
  45. public ParticleSegmentation m_ParticleSegmentation;
  46. //记录field列表的原值
  47. public List<DisplayField> m_original_list_dfield = null;
  48. //记录原值,颗粒和线段
  49. public List<BaseObject> m_original_list_baseobject = null;
  50. NLog.Logger log;
  51. //field的数量
  52. public int m_field_count = 0;
  53. //particle的数量
  54. public int m_particle_count = 0;
  55. //加载使用的时间
  56. public string m_time_str = "";
  57. //加载使用时间计算时间段2
  58. public string m_time_str2 = "";
  59. //电镜设置对象
  60. public ServiceInterface.HardwareController m_cfun = null;
  61. //是否已经连接到了电镜
  62. //public bool m_SEMConnectionState = false;
  63. //连接到电镜的ID号
  64. public int m_SEM_ID = 0;
  65. #endregion
  66. #region 构造函数
  67. public OTSImageDisHelp( ResultFile result)
  68. {
  69. m_original_list_dfield = new List<DisplayField>();
  70. m_original_list_baseobject = new List<BaseObject>();
  71. resultFile = result;
  72. m_cfun = ServiceInterface.HardwareController.GetSemController();
  73. log = NLog.LogManager.GetCurrentClassLogger();
  74. }
  75. #endregion
  76. #region 封装自定义方法
  77. public Point GetOTSCoordLeftBottomPoint(List<Point> allFldPos)
  78. {
  79. //the ots coordinate system is always positive on the right and up direction.So the leftbottom point would be the smallest point.
  80. //找出最小的x,y用来做偏移运算
  81. int i_offset_x = 1000000000;
  82. int i_offset_y = 1000000000;
  83. //先取出最小的x,y
  84. for (int i = 0; i < allFldPos.Count; i++)
  85. {
  86. if (i_offset_x > allFldPos[i].X)
  87. {
  88. i_offset_x = allFldPos[i].X;
  89. }
  90. if (i_offset_y > allFldPos[i].Y)
  91. {
  92. i_offset_y = allFldPos[i].Y;
  93. }
  94. }
  95. return new Point(i_offset_x, i_offset_y);
  96. }
  97. public Point ConvertOTSCoordinateToScreenCoord(Point otsleftBottomPoint,double pixelSize, Point currenFldPos,RectangleF wholeImageRec,RectangleF singleImgRec)//
  98. {
  99. var OTSPoint=new Point(currenFldPos.X - otsleftBottomPoint.X, currenFldPos.Y - otsleftBottomPoint.Y);
  100. int screenHeight =(int) wholeImageRec.Height + (0 - (int)(Convert.ToDouble(OTSPoint.Y) / pixelSize));//because the screen coordinate is downward rightward positive,so we need to translate the Y coordinate of the OTS system which is upward rightward positive.
  101. screenHeight = screenHeight -(int) singleImgRec.Height;
  102. var screenPoint = new Point((int)(Convert.ToDouble(OTSPoint.X)/pixelSize), (int)screenHeight);
  103. return screenPoint;
  104. }
  105. public Rectangle ConvertAndGetMaxRect(List<Point> inPoints, int in_width, int in_height)
  106. {
  107. //首先要能确定下来,单个物理坐标的宽和高--------------------------------
  108. int i_wl_width = 0;
  109. int i_wl_height = 0;
  110. RectangleF ls_r = GetPhysicalFieldWidthAndHeight(inPoints,in_width,in_height);
  111. i_wl_width = (int)ls_r.Width;
  112. i_wl_height = (int)ls_r.Height;
  113. //-----------------------------------------------------------------------------
  114. double point_x_min = 10000000;
  115. double point_x_max = -10000000;
  116. double point_y_min = 10000000;
  117. double point_y_max = -10000000;
  118. for (int i = 0; i < inPoints.Count(); i++)
  119. {
  120. Point ls_point = inPoints[i];
  121. //取出正数最大x
  122. if (ls_point.X > point_x_max)
  123. point_x_max = ls_point.X;
  124. if (ls_point.Y > point_y_max)
  125. point_y_max = ls_point.Y;
  126. if (ls_point.X < point_x_min)
  127. point_x_min = ls_point.X;
  128. if (ls_point.Y < point_y_min)
  129. point_y_min = ls_point.Y;
  130. }
  131. //然后分别用最大值+abs(最小值),就是x,和y轴的总长值
  132. double x_max = point_x_max - point_x_min+ i_wl_width;
  133. double y_max = point_y_max - point_y_min+ i_wl_height;
  134. //将物理宽高,变换成分辨率宽高
  135. double xPixel=0;
  136. double yPixel=0;
  137. if (i_wl_width != 0) xPixel = (x_max / i_wl_width) * in_width;
  138. if (i_wl_height != 0) yPixel = (y_max / i_wl_height) * in_height;
  139. Rectangle ret_rectangle = new Rectangle(0, 0, 0, 0);
  140. if (inPoints.Count > 0)
  141. {
  142. ret_rectangle = new Rectangle(0, 0, (int)(xPixel), (int)(yPixel));
  143. }
  144. return ret_rectangle;
  145. }
  146. /// <summary>
  147. /// 计算单个field的物理大小 传入field的list,还有测量结果管理类对象,在无法计算出单field的物理大小的情况下,到这里取再计算得出
  148. /// </summary>
  149. /// <returns></returns>
  150. public RectangleF GetPhysicalFieldWidthAndHeight(List<Point> points,int imageWidth,int imageHeight)
  151. {
  152. RectangleF ret_rect = new RectangleF(0, 0, 0, 0);
  153. Dictionary<string, object> sampleMembers = ((Dictionary<string, object>)((Dictionary<string, object>)resultFile.ResultInfo["Sample"])["Members"]);
  154. Dictionary<string, object> SEMDataMsr = (Dictionary<string, object>)sampleMembers["SEMDataMsr"];
  155. string scanfeldsize = SEMDataMsr["ScanFieldSize"].ToString();
  156. double d_scanFieldSize_width = Convert.ToDouble(scanfeldsize);
  157. double d_scanFieldSize_height = 0;
  158. if (d_scanFieldSize_width != 0)
  159. d_scanFieldSize_height = (d_scanFieldSize_width / Convert.ToDouble(imageWidth)) * imageHeight;
  160. ret_rect.Width = (int)d_scanFieldSize_width;
  161. ret_rect.Height = (int)d_scanFieldSize_height;
  162. return ret_rect;
  163. }
  164. #endregion
  165. #region 电镜操作相关方法
  166. /// <summary>
  167. /// 连接电镜,分布图使用
  168. /// </summary>
  169. public bool ConnectToIpcSvr()
  170. {
  171. //和电镜建立通讯连接
  172. return m_cfun.ConnectToIpcSvr();
  173. }
  174. /// <summary>
  175. /// 移动电镜到指定的X,Y坐标上,R坐标使用原先的值进行移动
  176. /// </summary>
  177. /// <param name="PositionX"></param>
  178. /// <param name="PositionY"></param>
  179. public void MoveSemToPointXY(double in_PositionX, double in_PositionY)
  180. {
  181. log.Trace("Begin MoveSemToPointXY:(" +in_PositionX.ToString()+","+in_PositionY.ToString()+")");
  182. //首先获取电镜当前的位置,并记录原R值
  183. double ls_PositionX = 0;
  184. double ls_PositionY = 0;
  185. double ls_PositionR = 0;
  186. if (m_cfun.ConnectToIpcSvr())
  187. {
  188. m_cfun.GetSemPositionXY(ref ls_PositionX, ref ls_PositionY, ref ls_PositionR);
  189. }
  190. else
  191. {
  192. log.Error("Failed to GetSemPositionXY");
  193. return;
  194. }
  195. if (m_cfun.ConnectToIpcSvr())
  196. {
  197. m_cfun.MoveSEMToPoint(new Point((int)in_PositionX, (int)in_PositionY), ls_PositionR);
  198. }
  199. }
  200. #endregion
  201. #region //--------------------------------------颗粒分布图相关部份---------------------------------------------------------------------
  202. /// <summary>
  203. /// 传入颗粒的tagid和fieldid,来获取该颗粒下对应的xray数据
  204. /// </summary>
  205. /// <param name="in_clr_tagid"></param>
  206. /// <param name="in_clr_fieldid"></param>
  207. /// <param name="Search_xray"></param>
  208. /// <param name="Analysis_xray"></param>
  209. public void GetXrayByParticleTagIDAndFieldID_ForDrawDistrbutionImageAndBSE(int in_clr_tagid, int in_clr_fieldid, out uint[] Search_xray, out uint[] Analysis_xray, out int xray_id, out List<Element> list_celementchemistryclr)
  210. {
  211. Search_xray = new uint[2000];
  212. Analysis_xray = new uint[2000];
  213. xray_id = 0;
  214. list_celementchemistryclr = new List<Element>();
  215. //防止为空校验判断
  216. if (resultFile.List_OTSField == null)
  217. return;
  218. Particle particle = resultFile.List_OTSField.Find(x => x.FieldID == in_clr_fieldid).ParticleList.Find(x => x.ParticleId == in_clr_tagid);
  219. var tmpPart = new ParticleData(resultFile.FilePath).GetParticleXrayDataByFidAndPid(Convert.ToString(particle.FieldId), Convert.ToString(particle.XrayId));
  220. if (tmpPart != null)
  221. {
  222. particle.XRayData = tmpPart.XRayData;
  223. if (particle.XrayId > -1)
  224. {
  225. for (int i = 0; i < 2000; i++)
  226. {
  227. Analysis_xray[i] = BitConverter.ToUInt32(particle.XRayData, i * 4);
  228. }
  229. Search_xray = Analysis_xray;
  230. xray_id = particle.XrayId;
  231. list_celementchemistryclr = particle.ElementList;
  232. }
  233. }
  234. }
  235. /// <summary>
  236. /// 传入所有的物理field坐标点,和单个物理field的宽高,返回所有field的左上角位置,和整个field组成的rect大小
  237. /// </summary>
  238. /// <param name="in_list_point"></param>
  239. /// <param name="in_width"></param>
  240. /// <param name="in_height"></param>
  241. /// <returns></returns>
  242. public Rectangle GetWlRectTopLeftAndRect(List<Point> in_list_point, int in_width, int in_height)
  243. {
  244. //分别获取整个rect的xy最小值和最大值
  245. int i_rect_x_min = 100000000;
  246. int i_rect_y_min = 100000000;
  247. int i_rect_x_max = -100000000;
  248. int i_rect_y_max = -100000000;
  249. for (int i = 0; i < in_list_point.Count; i++)
  250. {
  251. if (i_rect_x_min > in_list_point[i].X)
  252. i_rect_x_min = in_list_point[i].X;
  253. if (i_rect_y_min > in_list_point[i].Y)
  254. i_rect_y_min = in_list_point[i].Y;
  255. if (i_rect_x_max < in_list_point[i].X)
  256. i_rect_x_max = in_list_point[i].X;
  257. if (i_rect_y_max < in_list_point[i].Y)
  258. i_rect_y_max = in_list_point[i].Y;
  259. }
  260. Rectangle ret_rect = new Rectangle(i_rect_x_min, i_rect_y_min,
  261. i_rect_x_max - i_rect_x_min, i_rect_y_max - i_rect_y_min);
  262. return ret_rect;
  263. }
  264. /// <summary>
  265. /// 根据Field的ID,来获取Field列表中对应FIeld的OTS 坐标
  266. /// </summary>
  267. /// <param name="in_fieldid"></param>
  268. /// <returns></returns>
  269. public Point GetOTSPointByFieldID(List<DisplayField> in_list_dfield, int in_fieldid)
  270. {
  271. Point ret_point = new Point(0, 0);
  272. for (int i = 0; i < in_list_dfield.Count; i++)
  273. {
  274. //这里TagID先代表的是底层返回的ID
  275. if (in_list_dfield[i].FieldID == in_fieldid.ToString())
  276. {
  277. ret_point = new Point(Convert.ToInt32(in_list_dfield[i].OTSCoordinatePos.X), Convert.ToInt32(in_list_dfield[i].OTSCoordinatePos.Y));
  278. }
  279. }
  280. return ret_point;
  281. }
  282. /// <summary>
  283. /// 将OTS坐标转换为Sem 坐标
  284. /// </summary>
  285. /// <param name="POTSCoord"></param>
  286. /// <returns></returns>
  287. public Point ChangeOTSToSemCoord(Point POTSCoord)
  288. {
  289. //first if m_semstagedata is null to get stage inforation
  290. Convert.ToDouble(((Dictionary<string, object>)resultFile.ResultInfo["SEMStageData"])["scanFieldSize"]);
  291. //after obtaining stage info,calc stage point data
  292. Point ret_SEM_point = new Point();
  293. // get center point, um
  294. long xStart = Convert.ToInt64(((Dictionary<string, object>)((Dictionary<string, object>)((Dictionary<string, object>)resultFile.ResultInfo["SEMStageData"])["Members"])["XAxis"])["start"]);
  295. long xEnd = Convert.ToInt64(((Dictionary<string, object>)((Dictionary<string, object>)((Dictionary<string, object>)resultFile.ResultInfo["SEMStageData"])["Members"])["XAxis"])["end"]);
  296. long xCenter = (xStart + xEnd) / 2;
  297. long yStart = Convert.ToInt64(((Dictionary<string, object>)((Dictionary<string, object>)((Dictionary<string, object>)resultFile.ResultInfo["SEMStageData"])["Members"])["YAxis"])["start"]);
  298. long yEnd = Convert.ToInt64(((Dictionary<string, object>)((Dictionary<string, object>)((Dictionary<string, object>)resultFile.ResultInfo["SEMStageData"])["Members"])["YAxis"])["end"]);
  299. long yCenter = (yStart + yEnd) / 2;
  300. // delte = SEM - OTSa
  301. long deltex = xCenter - 0;
  302. long deltey = yCenter - 0;
  303. int xdir = Convert.ToInt32(((Dictionary<string, object>)resultFile.ResultInfo["SEMStageData"])["xAxisDir"]);
  304. int ydir = Convert.ToInt32(((Dictionary<string, object>)resultFile.ResultInfo["SEMStageData"])["yAxisDir"]);
  305. if (xdir == (int)OTS_X_AXIS_DIRECTION.LEFT_TOWARD)
  306. {
  307. ret_SEM_point.X = -1 * (POTSCoord.X - Convert.ToInt32(deltex));
  308. }
  309. else if (xdir == (int)OTS_X_AXIS_DIRECTION.RIGHT_TOWARD)
  310. {
  311. ret_SEM_point.X = POTSCoord.X + Convert.ToInt32(deltex);
  312. }
  313. if (ydir == (int)OTS_Y_AXIS_DIRECTION.UP_TOWARD)
  314. {
  315. ret_SEM_point.Y = POTSCoord.Y + Convert.ToInt32(deltey);
  316. }
  317. else if (ydir == (int)OTS_Y_AXIS_DIRECTION.DOWN_TOWARD)
  318. {
  319. ret_SEM_point.Y = -1 * (POTSCoord.Y - Convert.ToInt32(deltey));
  320. }
  321. return ret_SEM_point;
  322. }
  323. #endregion
  324. /// <summary>
  325. /// 判断该点是否在多边形的范围内
  326. /// </summary>
  327. /// <param name="inPoints"></param>
  328. /// <param name="WhetherPoint"></param>
  329. /// <returns></returns>
  330. public bool WhetherInRange(DisplayParticle Part,/*PointF[] inPoints,*/ Point WhetherPoint)
  331. {
  332. var rect = Part.Rect;
  333. if ((rect.Left < WhetherPoint.X && WhetherPoint.X < rect.Right) && (rect.Top < WhetherPoint.Y && WhetherPoint.Y < rect.Bottom))
  334. {
  335. var itm = (BaseObject)Part;
  336. itm.GPath = Part.GetRegionFromDSegments();
  337. PointF[] inPoints = itm.GPath.PathPoints;
  338. bool b_inrange = false;
  339. GraphicsPath myGraphicsPath = new GraphicsPath();
  340. Region myRegion = new Region();
  341. myGraphicsPath.Reset();
  342. myGraphicsPath.AddPolygon(inPoints);
  343. myRegion.MakeEmpty();
  344. myRegion.Union(myGraphicsPath);
  345. //返回判断点是否在多边形里
  346. b_inrange = myRegion.IsVisible(WhetherPoint);
  347. return b_inrange;
  348. }
  349. else
  350. {
  351. return false;
  352. }
  353. }
  354. public bool WhetherInRange(RectangleF rec,PointF[] inPoints, Point WhetherPoint)
  355. {
  356. var rect = rec;
  357. if ((rect.Left < WhetherPoint.X && WhetherPoint.X < rect.Right) && (rect.Top < WhetherPoint.Y && WhetherPoint.Y < rect.Bottom))
  358. {
  359. //var itm = (BaseObject)Part;
  360. //PointF[] inPoints = itm.GPath.PathPoints;
  361. bool b_inrange = false;
  362. GraphicsPath myGraphicsPath = new GraphicsPath();
  363. Region myRegion = new Region();
  364. myGraphicsPath.Reset();
  365. myGraphicsPath.AddPolygon(inPoints);
  366. myRegion.MakeEmpty();
  367. myRegion.Union(myGraphicsPath);
  368. //返回判断点是否在多边形里
  369. b_inrange = myRegion.IsVisible(WhetherPoint);
  370. return b_inrange;
  371. }
  372. else
  373. {
  374. return false;
  375. }
  376. }
  377. /// <summary>
  378. /// 判断该点是否在多边形的范围内的float版本重载
  379. /// </summary>
  380. /// <param name="inPoints"></param>
  381. /// <param name="WhetherPoint"></param>
  382. /// <returns></returns>
  383. public bool WhetherInRange(DisplayParticle Part,/* PointF[] inPoints, */PointF WhetherPoint)
  384. {
  385. var rect = Part.Rect;
  386. if ((rect.Left < WhetherPoint.X && WhetherPoint.X < rect.Right) && (rect.Top < WhetherPoint.Y && WhetherPoint.Y < rect.Bottom))
  387. {
  388. var itm = (BaseObject)Part;
  389. PointF[] inPoints = itm.GPath.PathPoints;
  390. bool b_inrange = false;
  391. GraphicsPath myGraphicsPath = new GraphicsPath();
  392. Region myRegion = new Region();
  393. myGraphicsPath.Reset();
  394. myGraphicsPath.AddPolygon(inPoints);
  395. myRegion.MakeEmpty();
  396. myRegion.Union(myGraphicsPath);
  397. //返回判断点是否在多边形里
  398. b_inrange = myRegion.IsVisible(WhetherPoint);
  399. return b_inrange;
  400. }
  401. else
  402. {
  403. return false;
  404. }
  405. }
  406. #region 颗粒分割功能方法
  407. /// <summary>
  408. /// 获取线段与矩形的两个交点
  409. /// </summary>
  410. /// <param name="line1S"></param>
  411. /// <param name="line1E"></param>
  412. /// <param name="rectangle"></param>
  413. /// <param name="pointList"></param>
  414. /// <returns></returns>
  415. public bool GetInterBetweenLinesAndRect(Point line1S, Point line1E, RectangleF rectangle, ref List<Point> pointList)
  416. {
  417. try
  418. {
  419. PointF pointF = new PointF(-1, -1);
  420. Rect rect = new Rect();
  421. rect.X = m_ParticleSegmentation.ParticleData.RectLeft;
  422. rect.Y = m_ParticleSegmentation.ParticleData.RectTop;
  423. rect.Width = m_ParticleSegmentation.ParticleData.RectWidth;
  424. rect.Height = m_ParticleSegmentation.ParticleData.RectHeight;
  425. float border = 0;
  426. if (GetInterBetweenTwoLines(line1S, line1E, new PointF(rectangle.Left, rectangle.Top), new PointF(rectangle.Right, rectangle.Top), ref pointF))
  427. {
  428. border = (pointF.X - rectangle.Left) / (rectangle.Right - rectangle.Left);
  429. pointList.Add(new Point((int)(rect.X + rect.Width * border), rect.Y));
  430. }
  431. if (GetInterBetweenTwoLines(line1S, line1E,
  432. new PointF(rectangle.Left, rectangle.Bottom), new PointF(rectangle.Right, rectangle.Bottom), ref pointF))
  433. {
  434. border = (pointF.X - rectangle.Left) / (rectangle.Right - rectangle.Left);
  435. pointList.Add(new Point((int)(rect.X + rect.Width * border), rect.Y + rect.Height));
  436. }
  437. if (GetInterBetweenTwoLines(line1S, line1E,
  438. new PointF(rectangle.Left, rectangle.Top), new PointF(rectangle.Left, rectangle.Bottom), ref pointF))
  439. {
  440. border = (pointF.Y - rectangle.Top) / (rectangle.Bottom - rectangle.Top);
  441. pointList.Add(new Point(rect.X, (int)(rect.Y + rect.Height * border)));
  442. }
  443. if (GetInterBetweenTwoLines(line1S, line1E,
  444. new PointF(rectangle.Right, rectangle.Top), new PointF(rectangle.Right, rectangle.Bottom), ref pointF))
  445. {
  446. border = (pointF.Y - rectangle.Top) / (rectangle.Bottom - rectangle.Top);
  447. pointList.Add(new Point(rect.X + rect.Width, (int)(rect.Y + rect.Height * border)));
  448. }
  449. if (pointList.Count == 2)
  450. {
  451. return true;
  452. }
  453. else
  454. {
  455. return false;
  456. }
  457. }
  458. catch (Exception ex)
  459. {
  460. log.Trace("(GetSplitPartFun)" + ex);
  461. return false;
  462. }
  463. }
  464. /// <summary>
  465. /// 获取分离颗粒方法
  466. /// </summary>
  467. /// <param name="startPoint"></param>
  468. /// <param name="endPoint"></param>
  469. /// <returns></returns>
  470. public bool GetSplitPartFun(Point startPoint, Point endPoint)
  471. {
  472. try
  473. {
  474. CImageHandler m_ImagePro = new CImageHandler();
  475. Particle particle1 = (Particle)CloneObject(m_ParticleSegmentation.ParticleData);
  476. Particle particle2 = (Particle)CloneObject(m_ParticleSegmentation.ParticleData);
  477. Dictionary<string, object> sampleMembers = ((Dictionary<string, object>)((Dictionary<string, object>)resultFile.ResultInfo["Sample"])["Members"]);
  478. Dictionary<string, object> imageScanParam = (Dictionary<string, object>)((Dictionary<string, object>)((Dictionary<string, object>)sampleMembers["MsrParams"])["Members"])["ImageScanParam"];
  479. double d_scanFieldSize_width = Convert.ToDouble(((Dictionary<string, object>)resultFile.ResultInfo["SEMStageData"])["scanFieldSize"]);
  480. string ImageResolution = imageScanParam["ImageResolution"].ToString();
  481. int width = int.Parse(ImageResolution.Split('_')[1]);
  482. int height = int.Parse(ImageResolution.Split('_')[2]);
  483. double dPixelSize = d_scanFieldSize_width / width;
  484. using (Mat mat = new Mat(height, width, MatType.CV_8UC1, Scalar.Black))//黑色底图
  485. using (Mat labelMat = new Mat())
  486. using (Mat stats = new Mat())
  487. using (Mat centroids = new Mat())
  488. using (Mat matBse = new Mat(resultFile.List_OTSField[particle1.FieldId].FieldImage, ImreadModes.Grayscale))
  489. {
  490. foreach (Segment segment in m_ParticleSegmentation.ParticleData.SegmentList)
  491. {
  492. Cv2.Line(mat, new OpenCvSharp.Point(segment.Start, segment.Height), new OpenCvSharp.Point(segment.Start + segment.Length, segment.Height), Scalar.White, 1, LineTypes.AntiAlias);
  493. }
  494. //寻找坐标点
  495. List<Point> points1 = new List<Point>();
  496. List<Point> points2 = new List<Point>();
  497. List<int> aveGray1 = new List<int>();
  498. List<int> aveGray2 = new List<int>();
  499. for (int k = 0; k < mat.Height; k++)
  500. {
  501. for (int j = 0; j < mat.Width; j++)
  502. {
  503. if (mat.Get<int>(k, j) != 0)
  504. {
  505. int side = (startPoint.X - j) * (endPoint.Y - k) - (startPoint.Y - k) * (endPoint.X - j);
  506. if (side >= 0)//区分像素位置
  507. {
  508. points1.Add(new Point(j, k));
  509. aveGray1.Add(matBse.Get<byte>(k, j));
  510. }
  511. else
  512. {
  513. points2.Add(new Point(j, k));
  514. aveGray2.Add(matBse.Get<byte>(k, j));
  515. }
  516. }
  517. }
  518. }
  519. //处理Segment
  520. List<COTSSegmentClr> SegmentClrList1 = new List<COTSSegmentClr>();
  521. List<COTSSegmentClr> SegmentClrList2 = new List<COTSSegmentClr>();
  522. List<Segment> SegmentList1 = new List<Segment>();
  523. List<Segment> SegmentList2 = new List<Segment>();
  524. GetSegment(points1, SegmentClrList1, ref SegmentList1);
  525. GetSegment(points2, SegmentClrList2, ref SegmentList2);
  526. //颗粒一
  527. Cv2.Threshold(mat, mat, 0, 0, ThresholdTypes.Binary);
  528. foreach (Segment segment in SegmentList1)
  529. {
  530. Cv2.Line(mat, new OpenCvSharp.Point(segment.Start, segment.Height), new OpenCvSharp.Point(segment.Start + segment.Length, segment.Height), Scalar.White, 1, LineTypes.AntiAlias);
  531. }
  532. Cv2.ConnectedComponentsWithStats(mat, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
  533. CopyToPart(particle1, SegmentList1, SegmentClrList1, aveGray1, stats, centroids, dPixelSize);
  534. //颗粒二
  535. Cv2.Threshold(mat, mat, 0, 0, ThresholdTypes.Binary);
  536. foreach (Segment segment in SegmentList2)
  537. {
  538. Cv2.Line(mat, new OpenCvSharp.Point(segment.Start, segment.Height), new OpenCvSharp.Point(segment.Start + segment.Length, segment.Height), Scalar.White, 1, LineTypes.AntiAlias);
  539. }
  540. Cv2.ConnectedComponentsWithStats(mat, labelMat, stats, centroids, PixelConnectivity.Connectivity8);
  541. CopyToPart(particle2, SegmentList2, SegmentClrList2, aveGray2, stats, centroids, dPixelSize);
  542. if (!SaveToDb(particle1, particle2))
  543. {
  544. log.Trace("(GetSplitPartFun) SaveToDb Faild");
  545. return false;
  546. }
  547. }
  548. return true;
  549. }
  550. catch (Exception ex)
  551. {
  552. log.Trace("(GetSplitPartFun)" + ex);
  553. return false;
  554. }
  555. }
  556. /// <summary>
  557. /// 拷贝颗粒数据
  558. /// </summary>
  559. /// <param name="particle"></param>
  560. /// <param name="segments"></param>
  561. /// <param name="SegmentClrList"></param>
  562. /// <param name="aveGray"></param>
  563. /// <param name="stats"></param>
  564. /// <param name="centroids"></param>
  565. /// <param name="dPixelSize"></param>
  566. private void CopyToPart(Particle particle, List<Segment> segments, List<COTSSegmentClr> SegmentClrList, List<int> aveGray, Mat stats, Mat centroids, double dPixelSize)
  567. {
  568. CImageHandler m_ImagePro = new CImageHandler();
  569. COTSParticleClr part = new COTSParticleClr();
  570. part.SetArea(stats.At<int>(1, 4) * dPixelSize * dPixelSize);
  571. part.SetParticleRect(new Rectangle(stats.At<int>(1, 0), stats.At<int>(1, 1), stats.At<int>(1, 2), stats.At<int>(1, 3)));
  572. part.GetFeature().SetSegmentsList(SegmentClrList, false);
  573. m_ImagePro.CalParticleImageProp(part, dPixelSize);
  574. particle.SegmentList = segments;
  575. particle.SegmentNum = segments.Count;
  576. particle.AveGray = (int)aveGray.Average();
  577. particle.RectLeft = stats.At<int>(1, 0);
  578. particle.RectTop = stats.At<int>(1, 1);
  579. particle.RectWidth = stats.At<int>(1, 2);
  580. particle.RectHeight = stats.At<int>(1, 3);
  581. particle.Area = stats.At<int>(1, 4) * dPixelSize * dPixelSize;
  582. particle.PosX = (int)centroids.At<double>(1, 0);
  583. particle.PosY = (int)centroids.At<double>(1, 1);
  584. particle.DFERET = part.GetFeretDiameter();
  585. particle.DMAX = part.GetDMAX();
  586. particle.DMIN = part.GetDMIN();
  587. particle.DPERP = part.GetDMPERP();
  588. particle.PERIMETER = part.GetDPRIMETER();
  589. particle.ORIENTATION = part.GetORIENTATION();
  590. particle.DINSCR = part.GetDINSCR();
  591. particle.DMEAN = part.GetDMEAN();
  592. particle.DELONG = part.GetDELONG();
  593. }
  594. /// <summary>
  595. /// 保存数据库
  596. /// </summary>
  597. /// <param name="particle1"></param>
  598. /// <param name="particle2"></param>
  599. /// <returns></returns>
  600. public bool SaveToDb(Particle particle1, Particle particle2)
  601. {
  602. //初始化
  603. SQLiteHelper sQLiteHelper = new SQLiteHelper(resultFile.FilePath + "\\FIELD_FILES\\Inclusion.db");
  604. sQLiteHelper.GetDBConnection();
  605. sQLiteHelper.BeginTransaction();
  606. //修改Segment表
  607. if (particle1.SegmentList.Count == 0 || particle2.SegmentList.Count == 0)
  608. {
  609. return false;
  610. }
  611. int SegmentCount = sQLiteHelper.ExecuteNewPartIdForTransaction() + 1;
  612. if (!sQLiteHelper.ExecuteSegmentForTransaction(particle1, particle2, SegmentCount))//修改Segment表
  613. {
  614. return false;
  615. }
  616. if (!sQLiteHelper.ExecuteXrayForTransaction(particle1, particle2, SegmentCount))//修改XRayData和PoxXrayInfo表
  617. {
  618. return false;
  619. }
  620. if (!sQLiteHelper.ExecuteIncAForTransaction(particle1, particle2, SegmentCount))//修改IncAData表
  621. {
  622. return false;
  623. }
  624. sQLiteHelper.CommitTransaction();
  625. return true;
  626. }
  627. /// <summary>
  628. /// 线段与矩形是否相交
  629. /// </summary>
  630. /// <param name="linePointX1"></param>
  631. /// <param name="linePointY1"></param>
  632. /// <param name="linePointX2"></param>
  633. /// <param name="linePointY2"></param>
  634. /// <param name="rectangleLeftTopX"></param>
  635. /// <param name="rectangleLeftTopY"></param>
  636. /// <param name="rectangleRightBottomX"></param>
  637. /// <param name="rectangleRightBottomY"></param>
  638. /// <returns></returns>
  639. public bool isLineIntersectRectangle(float linePointX1,
  640. float linePointY1,
  641. float linePointX2,
  642. float linePointY2,
  643. float rectangleLeftTopX,
  644. float rectangleLeftTopY,
  645. float rectangleRightBottomX,
  646. float rectangleRightBottomY)
  647. {
  648. float lineHeight = linePointY1 - linePointY2;
  649. float lineWidth = linePointX2 - linePointX1; // 计算叉乘
  650. float c = linePointX1 * linePointY2 - linePointX2 * linePointY1;
  651. if ((lineHeight * rectangleLeftTopX + lineWidth * rectangleLeftTopY + c >= 0 && lineHeight * rectangleRightBottomX + lineWidth * rectangleRightBottomY + c <= 0)
  652. || (lineHeight * rectangleLeftTopX + lineWidth * rectangleLeftTopY + c <= 0 && lineHeight * rectangleRightBottomX + lineWidth * rectangleRightBottomY + c >= 0)
  653. || (lineHeight * rectangleLeftTopX + lineWidth * rectangleRightBottomY + c >= 0 && lineHeight * rectangleRightBottomX + lineWidth * rectangleLeftTopY + c <= 0)
  654. || (lineHeight * rectangleLeftTopX + lineWidth * rectangleRightBottomY + c <= 0 && lineHeight * rectangleRightBottomX + lineWidth * rectangleLeftTopY + c >= 0))
  655. {
  656. if (rectangleLeftTopX > rectangleRightBottomX)
  657. {
  658. float temp = rectangleLeftTopX;
  659. rectangleLeftTopX = rectangleRightBottomX;
  660. rectangleRightBottomX = temp;
  661. }
  662. if (rectangleLeftTopY < rectangleRightBottomY)
  663. {
  664. float temp1 = rectangleLeftTopY;
  665. rectangleLeftTopY = rectangleRightBottomY;
  666. rectangleRightBottomY = temp1;
  667. }
  668. if ((linePointX1 < rectangleLeftTopX && linePointX2 < rectangleLeftTopX)
  669. || (linePointX1 > rectangleRightBottomX && linePointX2 > rectangleRightBottomX)
  670. || (linePointY1 > rectangleLeftTopY && linePointY2 > rectangleLeftTopY)
  671. || (linePointY1 < rectangleRightBottomY && linePointY2 < rectangleRightBottomY))
  672. {
  673. return false;
  674. }
  675. else
  676. {
  677. return true;
  678. }
  679. }
  680. else
  681. {
  682. return false;
  683. }
  684. }
  685. /// <summary>
  686. /// 求一个线段与另一个线段的交点
  687. /// </summary>
  688. /// <param name="line1S"></param>
  689. /// <param name="line1E"></param>
  690. /// <param name="line2S"></param>
  691. /// <param name="line2E"></param>
  692. /// <param name="interPoint"></param>
  693. /// <returns>-1:不存在交点;1:存在一个交点;2:存在无穷多个交点(重合或部分重合)</returns>
  694. public bool GetInterBetweenTwoLines(PointF line1S, PointF line1E,
  695. PointF line2S, PointF line2E, ref PointF interPoint)
  696. {
  697. int status = -1;
  698. // 判断两条直线各自的矩形包围盒的X与Y的值范围
  699. float line1Xmin = line1S.X < line1E.X ? line1S.X : line1E.X,
  700. line1Xmax = line1S.X > line1E.X ? line1S.X : line1E.X,
  701. line1Ymin = line1S.Y < line1E.Y ? line1S.Y : line1E.Y,
  702. line1Ymax = line1S.Y > line1E.Y ? line1S.Y : line1E.Y,
  703. line2Xmin = line2S.X < line2E.X ? line2S.X : line2E.X,
  704. line2Xmax = line2S.X > line2E.X ? line2S.X : line2E.X,
  705. line2Ymin = line2S.Y < line2E.Y ? line2S.Y : line2E.Y,
  706. line2Ymax = line2S.Y > line2E.Y ? line2S.Y : line2E.Y;
  707. if (line1S.X - line1E.X == 0)
  708. {
  709. // 两条线都垂直于X轴
  710. if (line2S.X - line2E.X == 0)
  711. {
  712. if (line1S.X != line2S.X) status = -1;
  713. else if ((line1Ymin > line2Ymax) || (line1Ymax < line2Ymin)) status = -1;
  714. else if (line1Ymin == line2Ymax)
  715. {
  716. interPoint = new PointF(line1S.X, line1Ymin); status = 1;
  717. }
  718. else if (line1Ymax == line2Ymin)
  719. {
  720. interPoint = new PointF(line1S.X, line1Ymax); status = 1;
  721. }
  722. else status = 2;
  723. }
  724. // line1垂直于X轴,line2不垂直于X轴
  725. else
  726. {
  727. float slope = (line2S.Y - line2E.Y) / (line2S.X - line2E.X);
  728. float offset = line2S.Y - slope * line2S.X;
  729. float newX = line1S.X, newY = slope * newX + offset;
  730. if (newX >= line2Xmin && newX <= line2Xmax && newY >= line1Ymin && newY <= line1Ymax
  731. && newY >= line2Ymin && newY <= line2Ymax)
  732. {
  733. interPoint = new PointF(newX, newY); status = 1;
  734. }
  735. }
  736. }
  737. else
  738. {
  739. // line1不垂直于X轴,line2垂直于X轴
  740. if (line2S.X - line2E.X == 0)
  741. {
  742. float slope = (line1S.Y - line1E.Y) / (line1S.X - line1E.X);
  743. float offset = line1S.Y - slope * line1S.X;
  744. float newX = line2S.X, newY = slope * newX + offset;
  745. if (newX >= line1Xmin && newX <= line1Xmax && newY >= line1Ymin && newY <= line1Ymax
  746. && newY >= line2Ymin && newY <= line2Ymax)
  747. {
  748. interPoint = new PointF(newX, newY); status = 1;
  749. }
  750. }
  751. // line1和line2都不垂直于X轴
  752. else
  753. {
  754. float slope1 = (line1S.Y - line1E.Y) / (line1S.X - line1E.X);
  755. float offset1 = line1S.Y - slope1 * line1S.X;
  756. float slope2 = (line2S.Y - line2E.Y) / (line2S.X - line2E.X);
  757. float offset2 = line2S.Y - slope2 * line2S.X;
  758. // 如果两条直线平行
  759. if (slope1 == slope2)
  760. {
  761. if (offset1 != offset2) status = -1;
  762. else if (line1Xmax == line2Xmin)
  763. {
  764. interPoint = new PointF(line1Xmax, line1Xmax * slope1 + offset1); status = 1;
  765. }
  766. else if (line1Xmin == line2Xmax)
  767. {
  768. interPoint = new PointF(line1Xmin, line1Xmin * slope1 + offset1); status = 1;
  769. }
  770. else if (line1Xmax < line2Xmin || line1Xmin > line2Xmax) status = -1;
  771. else status = 2;
  772. }
  773. else
  774. {
  775. float newX = (offset2 - offset1) / (slope1 - slope2), newY = newX * slope1 + offset1;
  776. if (newX >= line1Xmin && newX <= line1Xmax && newX >= line2Xmin && newX <= line2Xmax)
  777. {
  778. interPoint = new PointF(newX, newY); status = 1;
  779. }
  780. }
  781. }
  782. }
  783. if (status == 1)
  784. {
  785. return true;
  786. }
  787. else
  788. {
  789. return false;
  790. }
  791. }
  792. /// <summary>
  793. /// 获取Segment信息
  794. /// </summary>
  795. /// <param name="points"></param>
  796. /// <param name="SegmentClrList"></param>
  797. /// <param name="SegmentList"></param>
  798. public void GetSegment(List<Point> points, List<COTSSegmentClr> SegmentClrList, ref List<Segment> SegmentList)
  799. {
  800. List<int> segmentStart = new List<int>();
  801. List<int> segmentHeight = new List<int>();
  802. List<int> segmentLength = new List<int>();
  803. FindSegment(points, ref segmentStart, ref segmentHeight, ref segmentLength);
  804. for (int i = 0; i < segmentLength.Count; i++)
  805. {
  806. COTSSegmentClr seg = new COTSSegmentClr();
  807. seg.SetStart(segmentStart[i]);
  808. seg.SetHeight(segmentHeight[i]);
  809. seg.SetLength(segmentLength[i]);
  810. SegmentClrList.Add(seg);
  811. Segment segment = new Segment();
  812. segment.Start = segmentStart[i];
  813. segment.Height = segmentHeight[i];
  814. segment.Length = segmentLength[i];
  815. segment.SegmentNum = segmentLength.Count;
  816. segment.SegmentId = i;
  817. segment.FieldId = m_ParticleSegmentation.ParticleData.FieldId;
  818. segment.XRayId = m_ParticleSegmentation.ParticleData.XrayId;
  819. segment.ParticleId = m_ParticleSegmentation.ParticleData.ParticleId;
  820. SegmentList.Add(segment);
  821. }
  822. }
  823. /// <summary>
  824. /// 寻找segment方法
  825. /// </summary>
  826. public void FindSegment(List<Point> point_list_final, ref List<int> segmentStart, ref List<int> segmentHeight, ref List<int> segmentLength)
  827. {
  828. int flag = 0;
  829. point_list_final.Sort(my_sort);//排序
  830. for (int k = 0; k < point_list_final.Count(); k++)
  831. {
  832. if (k == 0 && k != point_list_final.Count() - 1)//第一个颗粒
  833. {
  834. flag++;
  835. segmentStart.Add(point_list_final[k].X);
  836. segmentHeight.Add(point_list_final[k].Y);
  837. }
  838. else if (k == 0 && k == point_list_final.Count() - 1)//只有一个颗粒
  839. {
  840. segmentStart.Add(point_list_final[k].X);
  841. segmentHeight.Add(point_list_final[k].Y);
  842. segmentLength.Add(1);
  843. }
  844. else if (k == point_list_final.Count() - 1)//最后一个颗粒
  845. {
  846. flag++;
  847. segmentLength.Add(flag);
  848. }
  849. else if (point_list_final[k].Y == point_list_final[k - 1].Y && point_list_final[k].X == point_list_final[k - 1].X + 1)//同行连续
  850. {
  851. flag++;
  852. }
  853. else if (point_list_final[k].Y == point_list_final[k - 1].Y && point_list_final[k].X != point_list_final[k - 1].X + 1)//同行隔断
  854. {
  855. segmentLength.Add(flag);
  856. flag = 1;
  857. segmentStart.Add(point_list_final[k].X);
  858. segmentHeight.Add(point_list_final[k].Y);
  859. }
  860. else if (point_list_final[k].Y != point_list_final[k - 1].Y)//不同行
  861. {
  862. segmentLength.Add(flag);
  863. flag = 1;
  864. segmentStart.Add(point_list_final[k].X);
  865. segmentHeight.Add(point_list_final[k].Y);
  866. }
  867. }
  868. }
  869. /// <summary>
  870. /// 排序方法
  871. /// </summary>
  872. /// <param name="p1"></param>
  873. /// <param name="p2"></param>
  874. /// <returns></returns>
  875. private int my_sort(Point p1, Point p2)
  876. {
  877. return p1.Y == p2.Y ? p1.X.CompareTo(p2.X) : p1.Y.CompareTo(p2.Y); //升序排序
  878. }
  879. public object CloneObject(object obj)
  880. {
  881. using (MemoryStream stream = new MemoryStream())
  882. {
  883. BinaryFormatter formatter = new BinaryFormatter();
  884. stream.Position = 0;
  885. formatter.Serialize(stream, obj);
  886. stream.Position = 0;
  887. return formatter.Deserialize(stream);
  888. }
  889. }
  890. #endregion
  891. }
  892. }