OTSImageDisHelp.cs 41 KB

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