OTSImageDisHelp.cs 43 KB

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