OTSImageDisHelp.cs 38 KB

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