BatteryCrackBallDialog.cs 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876
  1. using OpenCvSharp;
  2. using PaintDotNet.Annotation;
  3. using PaintDotNet.Annotation.Enum;
  4. using PaintDotNet.Base.CommTool;
  5. using PaintDotNet.Base.Functionodel;
  6. using PaintDotNet.Base.SettingModel;
  7. using PaintDotNet.CustomControl;
  8. using PaintDotNet.DbOpreate.DbBll;
  9. using PaintDotNet.DbOpreate.DbModel;
  10. using System;
  11. using System.Collections;
  12. using System.Collections.Generic;
  13. using System.ComponentModel;
  14. using System.Configuration;
  15. using System.Data;
  16. using System.Drawing;
  17. using System.Drawing.Drawing2D;
  18. using System.IO;
  19. using System.Linq;
  20. using System.Text;
  21. using System.Windows.Forms;
  22. namespace PaintDotNet.DedicatedAnalysis.Battery
  23. {
  24. internal partial class BatteryCrackBallDialog : PdnBaseForm
  25. {
  26. #region 属性
  27. //二值化集成1
  28. BinaryClassForB binaryClass;
  29. private int menuId;
  30. /// <summary>
  31. /// 选中图片的bitmap
  32. /// </summary>
  33. private Bitmap bitmap;
  34. /// <summary>
  35. /// 存在视场标记
  36. /// </summary>
  37. private bool existViewFlag = false;
  38. private int changeCount;
  39. /// <summary>
  40. /// 主空间
  41. /// </summary>
  42. private AppWorkspace appWorkspace;
  43. /// <summary>
  44. /// 图像面板
  45. /// </summary>
  46. private DocumentWorkspaceWindow documentWorkspace;
  47. /// <summary>
  48. /// 公共控件
  49. /// </summary>
  50. private GeneralAnalysisCommonControlButtons commonControlButtons;
  51. /// <summary>
  52. /// 图片测量记录
  53. /// </summary>
  54. private List<DataTable> pictureDataTables = new List<DataTable>();
  55. /// <summary>
  56. /// 网格Xml
  57. /// </summary>
  58. private GrainSizePointCountingMethodModel grainSizePointCountingMethodModel;
  59. /// <summary>
  60. /// 数据变化
  61. /// </summary>
  62. private bool saveSuccess = false;
  63. /// <summary>
  64. /// 0:添加 1:选择 2:删除
  65. /// </summary>
  66. private int operationK = -1;
  67. /// <summary>
  68. /// 被选择的线
  69. /// </summary>
  70. private int selected = -1;
  71. /// <summary>
  72. /// 起止点
  73. /// </summary>
  74. private System.Drawing.PointF startPoint, endPoint;
  75. /// <summary>
  76. /// 存储所有线的点集合
  77. /// </summary>
  78. private List<PointF[]> pointList1 = new List<PointF[]>();
  79. /// <summary>
  80. /// 存储当前线的点集合
  81. /// </summary>
  82. private PointF[] nowLine;
  83. /// <summary>
  84. /// 辅助计算偏移量-移动线两端的点
  85. /// </summary>
  86. private PointF lastPoint = new PointF(0, 0);
  87. /// <summary>
  88. /// 辅助计算偏移量-移动线中间的点
  89. /// </summary>
  90. private PointF tempPoint = new PointF(0, 0);
  91. /// <summary>
  92. /// 判断图形是否可移动
  93. /// </summary>
  94. private bool canMove = false;
  95. /// <summary>
  96. /// 测量点
  97. /// </summary>
  98. public List<RectangleF> rectangleFList = new List<RectangleF>();
  99. /// <summary>
  100. /// 移动线上的哪一个点
  101. /// </summary>
  102. private int movePointIndex = -1;
  103. /// <summary>
  104. /// 线的总数
  105. /// </summary>
  106. private int lineCount = 0;
  107. #endregion 属性
  108. #region 数据属性
  109. /// <summary>
  110. /// 折线点的集合
  111. /// </summary>
  112. public List<System.Drawing.Point> pointArray = new List<System.Drawing.Point>();
  113. /// <summary>
  114. /// 存储所有轮廓线的点集合
  115. /// </summary>
  116. private List<PointF> pointList = new List<PointF>();
  117. /// <summary>
  118. /// 存储所有轮廓线集合
  119. /// </summary>
  120. private List<List<PointF>> lineList = new List<List<PointF>>();
  121. /// <summary>
  122. /// 存储所有孔隙线的点集合
  123. /// </summary>
  124. private List<PointF> kongPointList = new List<PointF>();
  125. /// <summary>
  126. /// 存储所有孔隙线集合
  127. /// </summary>
  128. private List<List<PointF>> kongLineList = new List<List<PointF>>();
  129. /// <summary>
  130. /// 存储所有删除孔隙线的点集合
  131. /// </summary>
  132. private List<PointF> delPointList = new List<PointF>();
  133. /// <summary>
  134. /// 存储所有删除孔隙线集合
  135. /// </summary>
  136. private List<List<PointF>> delLineList = new List<List<PointF>>();
  137. //轮廓修改状态
  138. bool isLunKuo = false;
  139. //添加孔隙状态
  140. bool isAddKong = false;
  141. //删除孔隙状态
  142. bool isDelKong = false;
  143. private BinaryControlSmaller bc;
  144. /// <summary>
  145. /// 单位标尺
  146. /// </summary>
  147. private double unitLength = 1;
  148. #endregion
  149. /// <summary>
  150. ///
  151. /// </summary>
  152. /// <param name="appWorkspace"></param>
  153. public BatteryCrackBallDialog(AppWorkspace appWorkspace, int menuId)
  154. {
  155. this.KeyPreview = true;
  156. this.KeyDown += OnKeyDown;
  157. this.menuId = menuId;
  158. binaryClass = new BinaryClassForB(menuId);
  159. InitializeComponent();
  160. InitializeLanguageText();
  161. ColumnHeader header0 = new ColumnHeader();
  162. header0.Text = "";
  163. header0.Width = 180;
  164. this.appWorkspace = appWorkspace;
  165. this.documentWorkspace = new DocumentWorkspaceWindow(appWorkspace);
  166. this.documentWorkspace.Dock = DockStyle.Fill;
  167. this.documentWorkspace.HookMouseEvents();
  168. this.documentWorkspace.AuxiliaryLineEnabled = false;
  169. this.documentWorkspace.Visible = false;
  170. this.documentWorkspace.panel.Paint += Panel_Paint;
  171. this.documentWorkspace.panel.MouseDown += OnMouseDown;
  172. this.documentWorkspace.panel.MouseUp += OnMouseUp;
  173. this.documentWorkspace.panel.Paint += Panel_Paint;
  174. this.documentWorkspace.panel.MouseMove += onMouseMove;
  175. this.documentWorkspace.activeTool = DrawToolType.Pointer;
  176. this.groupBox7.Controls.Add(this.documentWorkspace);
  177. this.commonControlButtons = new GeneralAnalysisCommonControlButtons();
  178. this.commonControlButtons.Dock = DockStyle.Top;
  179. this.commonControlButtons.Height = 30;
  180. this.commonControlButtons.HideZoomToWindowAndActualSize();
  181. this.commonControlButtons.trackLabel.Text = "单击开始画线,右键停止。";
  182. this.commonControlButtons.trackLabel.Visible = true;
  183. this.commonControlButtons.trackLabel.Width = 300;
  184. this.commonControlButtons.Visible = false;
  185. this.groupBox7.Controls.Add(commonControlButtons);
  186. //获取
  187. //Startup.instance.rules.TryGetValue(MeasurementUnit.Micron, out ruleValue);
  188. //double ruleValue = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem.Index].GetRuler(MeasurementUnit.Micron);
  189. ////double physical_area_length_Micron = getCurrentWorkspace().GetRuler(MeasurementUnit.Micron);
  190. binaryClass.imageType = 4;
  191. //二值化集成2
  192. bc.OriginCheckedChangedAction += new EventHandler(this.bcOriginCheckedChanged);//初始化原图勾选改变事件
  193. binaryClass.createDocumentItemsSmaller(new string[] { "bp1"/*PdnResources.GetString("Menu.BinaryAction.BinaryExtraction.Text")*//*, PdnResources.GetString("Menu.Grainboundarytoreproduce.text")*/ }
  194. , this.bc, this.appWorkspace, this.documentWorkspace, this.listView1);//初始化相的工作结构
  195. //binaryClass.BinaryImplFinishAction += new EventHandler(this.bClassBinaryImplFinishAction);//二值化后续处理事件(参数改变时,重新处理图像)
  196. InitCommonButtonEvent();
  197. InitGridStyle();
  198. InitPicList();
  199. // SetAnalyzeModelFromXml(getModelName());
  200. //Action a = getball;
  201. //a.BeginInvoke(null, null);
  202. }
  203. private void ShowImgEvent(object sender, EventArgs e)
  204. {
  205. if (this.listView1.Items.Count == 0)
  206. {
  207. return;
  208. }
  209. listView1.Focus();
  210. this.listView1.Items[0].Focused = true;
  211. this.listView1.Items[0].Selected = true;
  212. }
  213. #region 二值化相关方法
  214. private void InclusionsStandardDialog_FormClosing(object sender, FormClosingEventArgs e)
  215. {
  216. binaryClass.saveParams();
  217. }
  218. private void ShownChoiseItemAndInitData(object sender, EventArgs e)
  219. {
  220. binaryClass.RefreshHistogramControl1Values();
  221. }
  222. /// <summary>
  223. /// 添加参数改变的监听
  224. /// </summary>
  225. /// <param name="sender"></param>
  226. /// <param name="e"></param>
  227. private void GrainSizePointCountingMethodDialog_Load(object sender, EventArgs e)
  228. {
  229. for (int i = 0; i < this.dataGridView1.Columns.Count; i++)
  230. {
  231. this.dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
  232. }
  233. this.dataGridView4.SortCompare += DataGridView4_SortCompare;
  234. this.binaryClass.loadParams();
  235. }
  236. private bool bcBinaryChecked()
  237. {
  238. return bc != null && bc.BinaryChecked;
  239. }
  240. private bool bcOriginChecked()
  241. {
  242. return bc != null && bc.OriginChecked;
  243. }
  244. /// <summary>
  245. /// 显示原图/原图+二值图
  246. /// </summary>
  247. /// <param name="sender"></param>
  248. /// <param name="e"></param>
  249. private void bcOriginCheckedChanged(object sender, EventArgs e)
  250. {
  251. if (!bcOriginChecked())
  252. {
  253. if (bcBinaryChecked())
  254. this.documentWorkspace.PhaseModels[0].choise = true;
  255. }
  256. else
  257. this.documentWorkspace.PhaseModels[0].choise = false;
  258. this.documentWorkspace.Refresh();
  259. }
  260. #endregion
  261. /// <summary>
  262. /// 初始化画面数据
  263. /// </summary>
  264. private void InitGridStyle()
  265. {
  266. grainSizePointCountingMethodModel = XmlSerializeHelper.DESerializer<GrainSizePointCountingMethodModel>(FileOperationHelper.ReadStringFromFile(Application.StartupPath + "\\Config\\" + Startup.instance.SettingPrefix + "\\GrainSizePointCountingMethodModel.xml", FileMode.Open));
  267. if (grainSizePointCountingMethodModel.GridStyleList != null)
  268. {
  269. ArrayList arrayList = new ArrayList();
  270. foreach (var GridStyle in grainSizePointCountingMethodModel.GridStyleList)
  271. {
  272. arrayList.Add(GridStyle.gridName);
  273. }
  274. if (grainSizePointCountingMethodModel.GridStyleList.Count == 0)
  275. {
  276. }
  277. }
  278. }
  279. /// <summary>
  280. /// 初始化图片列表数据
  281. /// </summary>
  282. public void InitPicList()
  283. {
  284. //初始化图片列表
  285. for (int i = 0; i < this.appWorkspace.DocumentWorkspaces.Length; i++)
  286. {
  287. this.imageList1.Images.Add("img" + i, this.appWorkspace.DocumentWorkspaces[i].BinarizationThumbnail);
  288. this.listView1.Items.Add("", i);
  289. this.listView1.Items[i].ImageIndex = i;
  290. this.listView1.Items[i].Text = this.appWorkspace.DocumentWorkspaces[i].GetFriendlyName();
  291. this.listView1.Items[i].Name = this.appWorkspace.DocumentWorkspaces[i].GetFriendlyName();
  292. }
  293. this.Shown += ShowImgEvent;
  294. }
  295. #region 初始化
  296. private void InitializeLanguageText()
  297. {
  298. this.bc = new PaintDotNet.CustomControl.BinaryControlSmaller();
  299. //
  300. // bc
  301. //
  302. this.bc.BinaryBackColor = System.Drawing.Color.Red;
  303. this.bc.BinaryChecked = false;
  304. this.bc.BinaryStyle = 1;
  305. this.bc.Location = new System.Drawing.Point(152, 7);
  306. this.bc.Name = "bc";
  307. this.bc.OriginChecked = false;
  308. this.bc.scope1End = 0D;
  309. this.bc.scope1Start = 0D;
  310. this.bc.scope2End = 0D;
  311. this.bc.scope2Start = 0D;
  312. this.bc.scope3End = 0D;
  313. this.bc.scope3Start = 0D;
  314. this.bc.Size = new System.Drawing.Size(360, 247);
  315. this.bc.TabIndex = 3;
  316. this.Controls.Add(this.bc);
  317. this.Controls.SetChildIndex(this.bc, 0);
  318. }
  319. #endregion
  320. #region 公共按钮
  321. private void InitCommonButtonEvent()
  322. {
  323. this.commonControlButtons.zoomInButton.Click += new EventHandler(zoomInButton_Click);
  324. this.commonControlButtons.zoomOutButton.Click += new EventHandler(zoomOutButton_Click);
  325. this.commonControlButtons.zoomToWindowButton.Click += new EventHandler(zoomToWindowButton_Click);
  326. this.commonControlButtons.actualSizeButton.Click += new EventHandler(actualSizeButton_Click);
  327. this.commonControlButtons.pointerButton.Click += new EventHandler(pointerButton_Click);
  328. this.commonControlButtons.mobileModeButton.Click += new EventHandler(mobileModeButton_Click);
  329. }
  330. private void zoomInButton_Click(object sender, EventArgs e)
  331. {
  332. this.documentWorkspace.ZoomIn();
  333. }
  334. private void zoomOutButton_Click(object sender, EventArgs e)
  335. {
  336. this.documentWorkspace.ZoomOut();
  337. }
  338. private void zoomToWindowButton_Click(object sender, EventArgs e)
  339. {
  340. this.documentWorkspace.ZoomBasis = ZoomBasis.FitToWindow;
  341. }
  342. private void actualSizeButton_Click(object sender, EventArgs e)
  343. {
  344. this.documentWorkspace.ZoomBasis = ZoomBasis.ScaleFactor;
  345. this.documentWorkspace.ScaleFactor = ScaleFactor.OneToOne;
  346. }
  347. private void pointerButton_Click(object sender, EventArgs e)
  348. {
  349. this.documentWorkspace.ActiveTool = Annotation.Enum.DrawToolType.Pointer;
  350. }
  351. private void mobileModeButton_Click(object sender, EventArgs e)
  352. {
  353. this.documentWorkspace.ActiveTool = Annotation.Enum.DrawToolType.MoveMode;
  354. }
  355. #endregion
  356. private void listView1_MouseDown(object sender, MouseEventArgs e)
  357. {
  358. this.changeCount = 0;
  359. }
  360. private void DataGridView4_SortCompare(object sender, DataGridViewSortCompareEventArgs e)
  361. {
  362. // 如果是数据的列,则按浮点数处理
  363. if (e.Column.Index != 3)//###20186
  364. {
  365. e.SortResult = (Convert.ToDouble(e.CellValue1) - Convert.ToDouble(e.CellValue2) > 0) ? 1 : (Convert.ToDouble(e.CellValue1) - Convert.ToDouble(e.CellValue2) < 0) ? -1 : 0;
  366. }
  367. //否则,按字符串比较
  368. else
  369. {
  370. e.SortResult = System.String.Compare(Convert.ToString(e.CellValue1), Convert.ToString(e.CellValue2));
  371. }
  372. e.Handled = true;//不能省掉,不然没效果
  373. }
  374. private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
  375. {
  376. bool change = false;
  377. if (this.changeCount == 0)
  378. {
  379. if (this.dataGridView1.Rows.Count > 0)
  380. {
  381. if (this.saveSuccess)
  382. {
  383. DialogResult dt = MessageBox.Show(PdnResources.GetString("Menu.Whethertosavetherrentpicture.text") + "?", PdnResources.GetString("Menu.hint.text"), MessageBoxButtons.YesNo, MessageBoxIcon.Question);
  384. if (dt == DialogResult.Yes)
  385. {
  386. string imgName = this.appWorkspace.DocumentWorkspaces[e.ItemIndex].GetFriendlyName();
  387. string tag = this.imageList1.Images.Keys[e.ItemIndex];
  388. if (this.dataGridView1.Rows.Count == 0)
  389. {
  390. MessageBox.Show(PdnResources.GetString("Menu.Pleaseaddtype.text") + "!");
  391. return;
  392. }
  393. }
  394. }
  395. }
  396. }
  397. else
  398. {
  399. if (change)
  400. SelectedIndexChanged();
  401. }
  402. this.changeCount++;
  403. }
  404. /// <summary>
  405. /// 切换图片
  406. /// </summary>
  407. /// <param name="sender"></param>
  408. /// <param name="e"></param>
  409. private void listView1_SelectedIndexChanged(object sender, EventArgs e)
  410. {
  411. SelectedIndexChanged();
  412. }
  413. List<PointF> list = new List<PointF>();
  414. /// <summary>
  415. /// 切换图片
  416. /// </summary>
  417. private void SelectedIndexChanged()
  418. {
  419. if (this.listView1.FocusedItem != null && this.listView1.FocusedItem.Selected)
  420. {
  421. existViewFlag = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem.Index].GraphicsList.IsExsitView();
  422. this.bitmap = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem.Index].CompositionSurface.CreateAliasedBitmap();
  423. lineList.Clear();
  424. pointList.Clear();
  425. kongLineList.Clear();
  426. kongPointList.Clear();
  427. delLineList.Clear();
  428. delPointList.Clear();
  429. isLunKuo = false;
  430. isAddKong = false;
  431. isDelKong = false;
  432. this.documentWorkspace.Refresh();
  433. this.dataGridView1.Rows.Clear();
  434. this.dataGridView4.Rows.Clear();
  435. Init();
  436. this.documentWorkspace.GridRectangleEnabled = false;
  437. //getimage();
  438. //getbian(bitmap);
  439. binaryClass.parent = this;
  440. //二值化集成4
  441. binaryClass.listView1_SelectedIndexChanged(this.bitmap);
  442. binaryClass.bcDefault();
  443. this.documentWorkspace.Refresh();
  444. }
  445. }
  446. #region 原始事件
  447. private void Init()
  448. {
  449. this.commonControlButtons.Visible = true;
  450. this.dataGridView1.Rows.Clear();
  451. this.dataGridView4.Rows.Clear();
  452. this.documentWorkspace.phaseModels.Clear();
  453. }
  454. /// <summary>
  455. /// 画布绘制
  456. /// </summary>
  457. /// <param name="sender"></param>
  458. /// <param name="e"></param>
  459. private void Panel_Paint(object sender, PaintEventArgs e)
  460. {
  461. if (this.documentWorkspace.CompositionSurface != null)
  462. {
  463. //
  464. // 以下是计算绘制图片的位置和大小并绘制图片
  465. //
  466. Rectangle rc = this.documentWorkspace.panel.ClientRectangle;
  467. int width = (int)(this.documentWorkspace.CompositionSurface.Width * this.documentWorkspace.ScaleFactor.Ratio);
  468. int height = (int)(this.documentWorkspace.CompositionSurface.Height * this.documentWorkspace.ScaleFactor.Ratio);
  469. int x = (rc.Width < width) ? this.documentWorkspace.panel.AutoScrollPosition.X : (rc.Width - width) / 2;
  470. int y = (rc.Height < height) ? this.documentWorkspace.panel.AutoScrollPosition.Y : (rc.Height - height) / 2;
  471. //
  472. // 以下是绘制网格、标注、测量、视场等开始
  473. //
  474. e.Graphics.TranslateTransform(x, y);
  475. e.Graphics.ScaleTransform((float)this.documentWorkspace.ScaleFactor.Ratio, (float)this.documentWorkspace.ScaleFactor.Ratio);
  476. Draw(e.Graphics);
  477. //e.Graphics.DrawLines(new Pen(this.panel1.BackColor, Convert.ToInt32(this.txt_LeftLineWeight.Text)), list.ToArray());
  478. e.Graphics.ScaleTransform(1 / (float)this.documentWorkspace.ScaleFactor.Ratio, 1 / (float)this.documentWorkspace.ScaleFactor.Ratio);
  479. e.Graphics.TranslateTransform(-x, -y);
  480. }
  481. if (bc.isedit)
  482. {
  483. bc.isedit = false;
  484. List<List<int>> CircleDate = bc.data;
  485. bindGrid(CircleDate);
  486. }
  487. }
  488. // <summary>
  489. /// 存储字号与颜色字典
  490. /// </summary>
  491. public Dictionary<string, Color> colourFont = new Dictionary<string, Color>() { { "20", Color.Black } };
  492. /// <summary>
  493. /// 绘制
  494. /// </summary>
  495. private void Draw(Graphics graphics)
  496. {
  497. //轮廓手动干预线
  498. //if (lineList.Count > 0)
  499. //{
  500. // for (int i = 0; i < lineList.Count; i++)
  501. // {
  502. // graphics.DrawLines(new Pen(Color.FromArgb(255, 0, 255), 2), lineList[i].ToArray());
  503. // }
  504. //}
  505. //if (pointList.Count > 1)
  506. //{
  507. // graphics.DrawLines(new Pen(Color.FromArgb(255, 0, 255), 2), pointList.ToArray());
  508. //}
  509. graphics.SmoothingMode = SmoothingMode.AntiAlias;
  510. Pen standardPen = new Pen(Color.FromArgb(0, 255, 0), 4);//基准线画笔
  511. Pen surfacePen = new Pen(Color.FromArgb(255, 0, 0), 4);//钢样表面画笔
  512. Pen completePen = new Pen(Color.FromArgb(0, 0, 255), 4);//完全脱碳层画笔
  513. Pen validPen = new Pen(Color.FromArgb(255, 255, 255), 4);//有效脱碳层画笔
  514. Pen partPen = new Pen(Color.FromArgb(0, 0, 0), 2);//部分脱碳层画笔
  515. Pen borderPen = new Pen(Color.Black);//填充点外圈
  516. SolidBrush insideBrush = new SolidBrush(Color.White);//填充点内圈
  517. Pen rectPen = new Pen(Color.Black);
  518. rectPen.DashStyle = DashStyle.Custom;
  519. float[] dashArray = { 2.0f, 3.0f };
  520. rectPen.DashPattern = dashArray;
  521. if (pointList1.Count > 0)
  522. {
  523. foreach (PointF[] pointFs in pointList1)
  524. {
  525. PointF[] pf = pointFs;
  526. if (pointFs.Count() > 1 && pointFs[0] != pointFs[1])
  527. {
  528. float lineLength = 12;
  529. double angle = Math.Round(BasicCalculationHelper.AngleText(pointFs[0], pointFs[1], new PointF(pointFs[0].X + lineLength, pointFs[0].Y)), 10);
  530. //判断第二个点相对于第一个点的象限
  531. int x2 = (int)(pointFs[1].X - pointFs[0].X);
  532. if (x2 == 0)
  533. x2 = 1;
  534. int y2 = (int)(pointFs[1].Y - pointFs[0].Y);
  535. if (y2 == 0)
  536. y2 = 1;
  537. int i2 = 0;
  538. if (x2 > 0 && y2 > 0) //第4象限
  539. {
  540. i2 = 4;
  541. }
  542. else if (x2 > 0 && y2 < 0) //第1象限
  543. {
  544. i2 = 1;
  545. }
  546. else if (x2 < 0 && y2 < 0) //第2象限
  547. {
  548. i2 = 2;
  549. }
  550. else if (x2 < 0 && y2 > 0) //第3象限
  551. {
  552. i2 = 3;
  553. }
  554. double sAngle1;
  555. double eAngle1;
  556. double sAngle2;
  557. double eAngle2;
  558. if (i2 == 1 || i2 == 2)
  559. {
  560. sAngle1 = 360 - angle;
  561. eAngle1 = 180 - angle;
  562. sAngle2 = 270 - angle;
  563. eAngle2 = 90 - angle;
  564. }
  565. else
  566. {
  567. sAngle1 = angle;
  568. eAngle1 = 180 + angle;
  569. sAngle2 = 270 + angle;
  570. eAngle2 = 90 + angle;
  571. }
  572. graphics.DrawLine(standardPen, pointFs[0], pointFs[1]);
  573. if (!double.IsNaN(sAngle1) && !double.IsNaN(eAngle1) && !double.IsNaN(sAngle2) && !double.IsNaN(eAngle2))
  574. {
  575. PointF assistPoint1 = BasicCalculationHelper.GetAnglePoint(new PointF((pointFs[0].X + lineLength), pointFs[0].Y), pointFs[0], sAngle2);
  576. PointF assistPoint2 = BasicCalculationHelper.GetAnglePoint(new PointF((pointFs[0].X + lineLength), pointFs[0].Y), pointFs[0], eAngle2);
  577. PointF assistPoint3 = BasicCalculationHelper.GetAnglePoint(new PointF((pointFs[1].X + lineLength), pointFs[1].Y), pointFs[1], sAngle2);
  578. PointF assistPoint4 = BasicCalculationHelper.GetAnglePoint(new PointF((pointFs[1].X + lineLength), pointFs[1].Y), pointFs[1], eAngle2);
  579. graphics.DrawLine(surfacePen, assistPoint1, assistPoint2);
  580. graphics.DrawLine(partPen, assistPoint3, assistPoint4);
  581. //PointF[] pf = pointFs;
  582. if (i2 == 1 || i2 == 2)
  583. {
  584. graphics.DrawString((BasicCalculationHelper.GetDistance(pf[1], pf[0], 4) * unitLength).ToString(), new Font("宋体", float.Parse(colourFont.Keys.First()), System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))), new SolidBrush(colourFont.Values.First()), assistPoint4.X, assistPoint4.Y - 10);
  585. }
  586. else
  587. {
  588. graphics.DrawString((BasicCalculationHelper.GetDistance(pf[1], pf[0], 4) * unitLength).ToString(), new Font("宋体", float.Parse(colourFont.Keys.First()), System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))), new SolidBrush(colourFont.Values.First()), assistPoint3.X, assistPoint3.Y - 10);
  589. }
  590. }
  591. }
  592. }
  593. if (selected > -1)
  594. {
  595. int tempLess = (int)(InvariantData.rectless * (this.documentWorkspace.ScaleFactor.Ratio < 1 ? 1 / this.documentWorkspace.ScaleFactor.Ratio : 1));
  596. int tempPlus = (int)(InvariantData.rectplus * (this.documentWorkspace.ScaleFactor.Ratio < 1 ? 1 / this.documentWorkspace.ScaleFactor.Ratio : 1));
  597. graphics.DrawRectangle(borderPen, new Rectangle((int)(pointList1[selected][0].X - tempLess), (int)(pointList1[selected][0].Y - tempLess), tempPlus, tempPlus));
  598. graphics.FillRectangle(insideBrush, new RectangleF(pointList1[selected][0].X - tempLess, pointList1[selected][0].Y - tempLess, tempPlus, tempPlus));
  599. graphics.DrawRectangle(borderPen, new Rectangle((int)(pointList1[selected][1].X - tempLess), (int)(pointList1[selected][1].Y - tempLess), tempPlus, tempPlus));
  600. graphics.FillRectangle(insideBrush, new RectangleF(pointList1[selected][1].X - tempLess, pointList1[selected][1].Y - tempLess, tempPlus, tempPlus));
  601. graphics.DrawRectangle(rectPen, rectangleFList[selected].X, rectangleFList[selected].Y, rectangleFList[selected].Width, rectangleFList[selected].Height);
  602. }
  603. }
  604. standardPen.Dispose();
  605. surfacePen.Dispose();
  606. completePen.Dispose();
  607. validPen.Dispose();
  608. partPen.Dispose();
  609. borderPen.Dispose();
  610. insideBrush.Dispose();
  611. rectPen.Dispose();
  612. }
  613. /// <summary>
  614. /// 添加测量线
  615. /// </summary>
  616. /// <param name="sender"></param>
  617. /// <param name="e"></param>
  618. private void btnAddCeliang_Click(object sender, EventArgs e)
  619. {
  620. operationK = 0;
  621. selected = -1;
  622. this.documentWorkspace.Refresh();
  623. }
  624. /// <summary>
  625. /// 选择测量线
  626. /// </summary>
  627. /// <param name="sender"></param>
  628. /// <param name="e"></param>
  629. private void btnSelCeliang_Click(object sender, EventArgs e)
  630. {
  631. operationK = 1;
  632. }
  633. /// <summary>
  634. /// 删除测量线
  635. /// </summary>
  636. /// <param name="sender"></param>
  637. /// <param name="e"></param>
  638. private void btnDelCeliang_Click(object sender, EventArgs e)
  639. {
  640. if (selected > -1)
  641. {
  642. DialogResult dr = MessageBox.Show(PdnResources.GetString("Menu.Areyousuretodmeasurementline.text") + "?", PdnResources.GetString("Menu.alert.text"), MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
  643. if (dr == DialogResult.OK)
  644. {
  645. this.pointList1.Remove(this.pointList1[selected]);
  646. this.rectangleFList.Remove(this.rectangleFList[selected]);
  647. selected = -1;
  648. lineCount--;
  649. this.documentWorkspace.Refresh();
  650. }
  651. }
  652. else
  653. MessageBox.Show("请先选择测量线");
  654. }
  655. /// <summary>
  656. /// 添加测量线按钮失去焦点
  657. /// </summary>
  658. /// <param name="sender"></param>
  659. /// <param name="e"></param>
  660. private void btnAddCeliang_LostFocus(object sender, EventArgs e)
  661. {
  662. operationK = -1;
  663. selected = -1;
  664. this.documentWorkspace.Refresh();
  665. }
  666. private void bindGrid(List<List<int>> dataList)
  667. {
  668. if (dataList.Count < 1)
  669. {
  670. return;
  671. }
  672. int areaAll = 0;
  673. int areaIsK = 0;
  674. int areaNot = 0;
  675. int numIsk = 0;
  676. int numNot = 0;
  677. double d = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem.Index].GetRuler(MeasurementUnit.Micron);
  678. //孔隙信息列表
  679. dataGridView4.Rows.Clear();
  680. foreach (var item in dataList)
  681. {
  682. string str = "普通球";
  683. if (item[5] == 1)
  684. {
  685. str = "开裂球";
  686. areaIsK += item[4];
  687. numIsk++;
  688. }
  689. else
  690. {
  691. areaNot += item[4];
  692. numNot++;
  693. }
  694. int newPo = dataGridView4.Rows.Add();
  695. double crl = (double)item[6];
  696. crl = crl *0.001;
  697. dataGridView4.Rows[newPo].Cells[0].Value = (newPo+1).ToString();
  698. dataGridView4.Rows[newPo].Cells[1].Value = item[0];
  699. dataGridView4.Rows[newPo].Cells[2].Value = item[1];
  700. dataGridView4.Rows[newPo].Cells[3].Value = str;
  701. if (item[3] < 0)
  702. {
  703. dataGridView4.Rows[newPo].Cells[4].Value = -1;
  704. dataGridView4.Rows[newPo].Cells[5].Value = -1;
  705. }
  706. else
  707. {
  708. dataGridView4.Rows[newPo].Cells[4].Value = Math.Round(item[3] * d, 2);
  709. dataGridView4.Rows[newPo].Cells[5].Value = Math.Round(item[4] * d, 2);
  710. }
  711. dataGridView4.Rows[newPo].Cells[6].Value = crl;
  712. }
  713. dataGridView1.Rows.Clear();
  714. int newrow = dataGridView1.Rows.Add();
  715. dataGridView1.Rows[newrow].Cells[0].Value = "开裂球";
  716. //dataGridView1.Rows[newrow].Cells[1].Value = areaIsK * d * d;
  717. dataGridView1.Rows[newrow].Cells[1].Value = numIsk;
  718. dataGridView1.Rows[newrow].DefaultCellStyle.ForeColor = Color.Red;
  719. newrow = dataGridView1.Rows.Add();
  720. dataGridView1.Rows[newrow].Cells[0].Value = "普通球";
  721. //dataGridView1.Rows[newrow].Cells[1].Value = areaNot * d * d;
  722. dataGridView1.Rows[newrow].Cells[1].Value = numNot;
  723. dataGridView1.Rows[newrow].DefaultCellStyle.ForeColor = Color.Blue;
  724. newrow = dataGridView1.Rows.Add();
  725. areaAll = areaIsK + areaNot;
  726. dataGridView1.Rows[newrow].Cells[0].Value = "总体";
  727. // dataGridView1.Rows[newrow].Cells[1].Value = areaAll * d * d;
  728. dataGridView1.Rows[newrow].Cells[1].Value = numIsk + numNot;
  729. newrow = dataGridView1.Rows.Add();
  730. dataGridView1.Rows[newrow].Cells[0].Value = "开裂占比";
  731. dataGridView1.Rows[newrow].Cells[1].Value = (numIsk * 100 / (numIsk + numNot)).ToString() + "%";
  732. // dataGridView1.Rows[newrow].Cells[2].Value = "";
  733. }
  734. #region 手动干预
  735. /// <summary>
  736. /// 修改轮廓
  737. /// </summary>
  738. /// <param name="sender"></param>
  739. /// <param name="e"></param>
  740. private void btnLunkuo_Click(object sender, EventArgs e)
  741. {
  742. isLunKuo = true;
  743. isAddKong = false;
  744. isDelKong = false;
  745. }
  746. /// <summary>
  747. /// 添加孔隙
  748. /// </summary>
  749. /// <param name="sender"></param>
  750. /// <param name="e"></param>
  751. private void btnAddKong_Click(object sender, EventArgs e)
  752. {
  753. isLunKuo = false;
  754. isAddKong = true;
  755. isDelKong = false;
  756. }
  757. /// <summary>
  758. /// 删除孔隙
  759. /// </summary>
  760. /// <param name="sender"></param>
  761. /// <param name="e"></param>
  762. private void btnDelKong_Click(object sender, EventArgs e)
  763. {
  764. isLunKuo = false;
  765. isAddKong = false;
  766. isDelKong = true;
  767. }
  768. /// <summary>
  769. /// 重新统计
  770. /// </summary>
  771. /// <param name="sender"></param>
  772. /// <param name="e"></param>
  773. private void btnReDrw_Click(object sender, EventArgs e)
  774. {
  775. isLunKuo = false;
  776. isAddKong = false;
  777. isDelKong = false;
  778. if (pointList.Count > 1)
  779. {
  780. List<PointF> pointFs = new List<PointF>(pointList.ToArray());
  781. lineList.Add(pointFs);
  782. pointList.Clear();
  783. }
  784. if (kongPointList.Count > 1)
  785. {
  786. //List<PointF> pointFs = new List<PointF>(kongPointList.ToArray());
  787. //kongLineList.Add(pointFs);
  788. //kongPointList.Clear();
  789. }
  790. if (delPointList.Count > 1)
  791. {
  792. //List<PointF> pointFs = new List<PointF>(delPointList.ToArray());
  793. //delLineList.Add(pointFs);
  794. //delPointList.Clear();
  795. }
  796. List<List<int>> CircleDate = binaryClass.DrwLunKuoLie(lineList, kongPointList, delPointList);
  797. bindGrid(CircleDate);
  798. }
  799. /// <summary>
  800. /// 移动
  801. /// </summary>
  802. /// <param name="sender"></param>
  803. /// <param name="e"></param>
  804. private void onMouseMove(object sender, MouseEventArgs e)
  805. {
  806. this.documentWorkspace.panel.Cursor = Cursors.Default;
  807. if (operationK >= 0 && e.Button == MouseButtons.Left)
  808. {
  809. PointF movePoint = this.documentWorkspace.GetScalePoint(e.Location);
  810. if (operationK == 0)
  811. {
  812. this.endPoint = movePoint;
  813. pointList1[lineCount][1] = endPoint;
  814. }
  815. else if (operationK == 1 && selected > -1 && canMove)
  816. {
  817. float dx = movePoint.X - lastPoint.X;
  818. float dy = movePoint.Y - lastPoint.Y;
  819. float dxTemp = movePoint.X - tempPoint.X;
  820. float dyTemp = movePoint.Y - tempPoint.Y;
  821. lastPoint.X = movePoint.X;
  822. lastPoint.Y = movePoint.Y;
  823. if (movePointIndex == -1)
  824. {
  825. RectangleF rectangleF = new RectangleF();
  826. rectangleF = rectangleFList[selected];
  827. if (rectangleF.Contains(movePoint))
  828. this.documentWorkspace.panel.Cursor = Cursors.SizeAll;
  829. rectangleF.X += dx;
  830. rectangleF.Y += dy;
  831. rectangleFList[selected] = rectangleF;
  832. for (int i = 0; i < pointList1[selected].Count(); i++)
  833. {
  834. if (pointList1[selected][i] == PointF.Empty)
  835. continue;
  836. pointList1[selected][i].X += dx;
  837. pointList1[selected][i].Y += dy;
  838. }
  839. }
  840. else if (movePointIndex == 0)
  841. {
  842. pointList1[selected][0].X += dx;
  843. pointList1[selected][0].Y += dy;
  844. rectangleFList[selected] = CalcOtherRectangle(pointList1[selected][0], pointList1[selected][1]);
  845. }
  846. else if (movePointIndex == 1)
  847. {
  848. pointList1[selected][1].X += dx;
  849. pointList1[selected][1].Y += dy;
  850. rectangleFList[selected] = CalcOtherRectangle(pointList1[selected][0], pointList1[selected][1]);
  851. }
  852. }
  853. this.documentWorkspace.Refresh();
  854. }
  855. if (isLunKuo)
  856. {
  857. int cou = pointList.Count;
  858. if (cou > 0)
  859. { // 换算后的点
  860. PointF movePoint = this.documentWorkspace.GetScalePoint(e.Location);
  861. pointList[cou - 1] = movePoint;
  862. }
  863. }
  864. if (isAddKong)
  865. {
  866. //if (kongPointList.Count > 0)
  867. //{ // 换算后的点
  868. // PointF movePoint = this.documentWorkspace.GetScalePoint(e.Location);
  869. // kongPointList[kongPointList.Count - 1] = movePoint;
  870. //}
  871. }
  872. if (isDelKong)
  873. {
  874. //if (delPointList.Count > 0)
  875. //{ // 换算后的点
  876. // PointF movePoint = this.documentWorkspace.GetScalePoint(e.Location);
  877. // delPointList[delPointList.Count - 1] = movePoint;
  878. //}
  879. }
  880. this.documentWorkspace.Refresh();
  881. // this.documentWorkspace.Refresh();
  882. }
  883. /// <summary>
  884. /// 格式化坐标点
  885. /// </summary>
  886. /// <param name="coordinateA">参考点1</param>
  887. /// <param name="coordinateB">参考点2</param>
  888. /// <param name="basicCoordinate">需比对的点</param>
  889. /// <returns></returns>
  890. private float FormatCoordinate(float coordinateA, float coordinateB, float basicCoordinate)
  891. {
  892. float coordinate = basicCoordinate;
  893. float[] pointArr = new float[] { coordinateA, coordinateB };
  894. if (coordinate > pointArr.Max() - 3)
  895. coordinate = pointArr.Max() - 3;
  896. if (coordinate < pointArr.Min() + 3)
  897. coordinate = pointArr.Min() + 3;
  898. return coordinate;
  899. }
  900. /// <summary>
  901. /// 计算外接矩形
  902. /// </summary>
  903. private RectangleF CalcOtherRectangle(PointF p1, PointF p2)
  904. {
  905. RectangleF rectangleF = new RectangleF();
  906. if (p1.X > p2.X)
  907. rectangleF.X = p2.X;
  908. else
  909. rectangleF.X = p1.X;
  910. if (p1.Y > p2.Y)
  911. rectangleF.Y = p2.Y;
  912. else
  913. rectangleF.Y = p1.Y;
  914. rectangleF.Width = Math.Abs(p2.X - p1.X);
  915. rectangleF.Height = Math.Abs(p2.Y - p1.Y);
  916. int tempLess = (int)(InvariantData.rectless * (this.documentWorkspace.ScaleFactor.Ratio < 1 ? 1 / this.documentWorkspace.ScaleFactor.Ratio : 1)) * 5;
  917. int tempPlus = (int)(InvariantData.rectplus * (this.documentWorkspace.ScaleFactor.Ratio < 1 ? 1 / this.documentWorkspace.ScaleFactor.Ratio : 1)) * 5;
  918. return new RectangleF(rectangleF.X - tempLess, rectangleF.Y - tempLess, rectangleF.Width + tempPlus, rectangleF.Height + tempPlus);
  919. }
  920. /// <summary>
  921. /// 鼠标抬起
  922. /// </summary>
  923. /// <param name="sender"></param>
  924. /// <param name="e"></param>
  925. private void OnMouseUp(object sender, MouseEventArgs e)
  926. {
  927. if (e.Button == MouseButtons.Left)
  928. {
  929. if (operationK == 0)
  930. {
  931. if (startPoint != null && endPoint != null && startPoint != endPoint)
  932. {
  933. RectangleF rectangleF = CalcOtherRectangle(pointList1[lineCount][0], pointList1[lineCount][1]);
  934. rectangleFList.Add(rectangleF);
  935. lineCount++;
  936. // AddContentToDataGridView();
  937. }
  938. else
  939. {
  940. if (pointList1.Count > 0)
  941. {
  942. pointList1.RemoveAt(pointList1.Count - 1);
  943. this.documentWorkspace.Refresh();
  944. return;
  945. }
  946. }
  947. this.documentWorkspace.Refresh();
  948. }
  949. else if (operationK == 1)
  950. {
  951. canMove = false;
  952. movePointIndex = -1;
  953. // RefreshDataGridView1();
  954. }
  955. }
  956. if (operationK >= 0 && e.Button == MouseButtons.Left)
  957. {
  958. PointF downPoint = this.documentWorkspace.GetScalePoint(e.Location);
  959. if (operationK == 0)
  960. {
  961. pointList1[lineCount - 1][1] = downPoint;
  962. }
  963. else if (operationK == 1)
  964. {
  965. lastPoint.X = downPoint.X;
  966. lastPoint.Y = downPoint.Y;
  967. tempPoint.X = downPoint.X;
  968. tempPoint.Y = downPoint.Y;
  969. for (int i = rectangleFList.Count - 1; i >= 0; i--)
  970. {
  971. if (rectangleFList[i].Contains(downPoint))
  972. {
  973. selected = i;
  974. canMove = true;
  975. }
  976. }
  977. if (selected > -1 && pointList1 != null && pointList1.Count > 0)
  978. {
  979. int tempLess = (int)(InvariantData.rectless * (this.documentWorkspace.ScaleFactor.Ratio < 1 ? 1 / this.documentWorkspace.ScaleFactor.Ratio : 1)) * 5;
  980. int tempPlus = (int)(InvariantData.rectplus * (this.documentWorkspace.ScaleFactor.Ratio < 1 ? 1 / this.documentWorkspace.ScaleFactor.Ratio : 1)) * 5;
  981. if (new RectangleF(pointList1[selected][0].X - tempLess, pointList1[selected][0].Y - tempLess, tempPlus, tempPlus).Contains(downPoint))
  982. movePointIndex = 0;
  983. else if (new RectangleF(pointList1[selected][1].X - tempLess, pointList1[selected][1].Y - tempLess, tempPlus, tempPlus).Contains(downPoint))
  984. movePointIndex = 1;
  985. else
  986. movePointIndex = -1;
  987. this.documentWorkspace.Refresh();
  988. }
  989. if (canMove)
  990. return;
  991. selected = -1;
  992. }
  993. }
  994. }
  995. /// <summary>
  996. /// 鼠标按下
  997. /// </summary>
  998. /// <param name="drawArea"></param>
  999. /// <param name="e"></param>
  1000. private void OnMouseDown(object sender, MouseEventArgs e)
  1001. {
  1002. PointF downPoint = this.documentWorkspace.GetScalePoint(e.Location);
  1003. if (operationK >= 0 && e.Button == MouseButtons.Left)
  1004. {
  1005. if (operationK == 0)
  1006. {
  1007. startPoint = endPoint = downPoint;
  1008. nowLine = new PointF[4];
  1009. nowLine[0] = startPoint;
  1010. nowLine[1] = endPoint;
  1011. pointList1.Add(nowLine);
  1012. }
  1013. else if (operationK == 1)
  1014. {
  1015. lastPoint.X = downPoint.X;
  1016. lastPoint.Y = downPoint.Y;
  1017. tempPoint.X = downPoint.X;
  1018. tempPoint.Y = downPoint.Y;
  1019. for (int i = rectangleFList.Count - 1; i >= 0; i--)
  1020. {
  1021. if (rectangleFList[i].Contains(downPoint))
  1022. {
  1023. selected = i;
  1024. canMove = true;
  1025. }
  1026. }
  1027. if (selected > -1 && pointList1 != null && pointList1.Count > 0)
  1028. {
  1029. int tempLess = (int)(InvariantData.rectless * (this.documentWorkspace.ScaleFactor.Ratio < 1 ? 1 / this.documentWorkspace.ScaleFactor.Ratio : 1)) * 5;
  1030. int tempPlus = (int)(InvariantData.rectplus * (this.documentWorkspace.ScaleFactor.Ratio < 1 ? 1 / this.documentWorkspace.ScaleFactor.Ratio : 1)) * 5;
  1031. if (new RectangleF(pointList1[selected][0].X - tempLess, pointList1[selected][0].Y - tempLess, tempPlus, tempPlus).Contains(downPoint))
  1032. movePointIndex = 0;
  1033. else if (new RectangleF(pointList1[selected][1].X - tempLess, pointList1[selected][1].Y - tempLess, tempPlus, tempPlus).Contains(downPoint))
  1034. movePointIndex = 1;
  1035. else
  1036. movePointIndex = -1;
  1037. this.documentWorkspace.Refresh();
  1038. }
  1039. if (canMove)
  1040. return;
  1041. selected = -1;
  1042. }
  1043. }
  1044. else if (e.Button == MouseButtons.Left)
  1045. {
  1046. if (isLunKuo)//开裂球
  1047. {
  1048. pointList.Add(downPoint);
  1049. }
  1050. if (isAddKong)//忽略球
  1051. {
  1052. kongPointList.Add(downPoint);
  1053. }
  1054. if (isDelKong)//普通球
  1055. {
  1056. delPointList.Add(downPoint);
  1057. }
  1058. List<List<int>> CircleDate = binaryClass.DeleteBall(kongPointList, pointList, delPointList);
  1059. bindGrid(CircleDate);
  1060. }
  1061. if (e.Button == MouseButtons.Right)
  1062. {
  1063. if (isLunKuo)
  1064. {
  1065. if (pointList.Count > 2)
  1066. {
  1067. pointList.RemoveAt(pointList.Count - 1);
  1068. List<PointF> pointFs = new List<PointF>(pointList.ToArray());
  1069. lineList.Add(pointFs);
  1070. }
  1071. pointList.Clear();
  1072. }
  1073. if (isAddKong)
  1074. {
  1075. }
  1076. if (isDelKong)
  1077. {
  1078. }
  1079. isLunKuo = false;
  1080. isAddKong = false;
  1081. isDelKong = false;
  1082. }
  1083. }
  1084. /// <summary>
  1085. /// Ctrl+z
  1086. /// </summary>
  1087. private void OnKeyDown(object sender, KeyEventArgs e)
  1088. {
  1089. if (e.Control && e.KeyCode == Keys.Z)
  1090. {
  1091. if (isLunKuo)
  1092. {
  1093. int cou = pointList.Count;
  1094. if (cou > 0)
  1095. {
  1096. pointList.RemoveAt(cou - 1);
  1097. List<List<int>> CircleDate = binaryClass.DeleteBall(kongPointList, pointList, delPointList);
  1098. bindGrid(CircleDate);
  1099. }
  1100. }
  1101. if (isAddKong)
  1102. {
  1103. int cou = kongPointList.Count;
  1104. if (cou > 0)
  1105. {
  1106. kongPointList.RemoveAt(cou - 1);
  1107. List<List<int>> CircleDate = binaryClass.DeleteBall(kongPointList, pointList, delPointList);
  1108. bindGrid(CircleDate);
  1109. }
  1110. }
  1111. if (isDelKong)
  1112. {
  1113. int cou = delPointList.Count;
  1114. if (cou > 0)
  1115. {
  1116. delPointList.RemoveAt(cou - 1);
  1117. List<List<int>> CircleDate = binaryClass.DeleteBall(kongPointList, pointList, delPointList);
  1118. bindGrid(CircleDate);
  1119. }
  1120. }
  1121. this.documentWorkspace.Refresh();
  1122. }
  1123. }
  1124. #endregion
  1125. /// <summary>
  1126. /// 准备用来处理单个颗粒的选中事件
  1127. /// </summary>
  1128. /// <param name="sender"></param>
  1129. /// <param name="e"></param>
  1130. private void dataGridView4_CellClick(object sender, DataGridViewCellEventArgs e)
  1131. {
  1132. //当点击表头部的列时,e.RowIndex==-1
  1133. if (e.RowIndex > -1)
  1134. {
  1135. int x =Convert.ToInt32( dataGridView4.Rows[e.RowIndex].Cells[0].Value);
  1136. binaryClass.DrwLunKuoLie1Selected(x);
  1137. this.documentWorkspace.Refresh();
  1138. }
  1139. }
  1140. /// <summary>
  1141. /// 导出孔隙信息
  1142. /// </summary>
  1143. /// <param name="sender"></param>
  1144. /// <param name="e"></param>
  1145. private void button14_Click(object sender, EventArgs e)
  1146. {
  1147. SaveFileDialog exe = new SaveFileDialog();
  1148. exe.Filter = "Execl files (*.xlsx)|*.xlsx";
  1149. exe.FilterIndex = 0;
  1150. exe.RestoreDirectory = true;
  1151. //exe.CreatePrompt = true;
  1152. exe.Title = "Export Excel File";
  1153. exe.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
  1154. exe.FileName = DateTime.Now.ToString("yyyyMMddhhmmss") + "孔隙信息";
  1155. DialogResult dr = exe.ShowDialog();
  1156. if (dr != DialogResult.OK)
  1157. {
  1158. return;
  1159. }
  1160. DataTable dtb = new DataTable();
  1161. foreach (DataGridViewColumn c in this.dataGridView4.Columns)
  1162. {
  1163. dtb.Columns.Add(c.HeaderText);
  1164. }
  1165. for (int r = 0; r < this.dataGridView4.Rows.Count; r++)
  1166. {
  1167. DataRow dataRow = dtb.NewRow();
  1168. for (int c = 0; c < this.dataGridView4.Rows[r].Cells.Count; c++)
  1169. {
  1170. dataRow[this.dataGridView4.Columns[c].HeaderText] = (string)this.dataGridView4.Rows[r].Cells[c].Value.ToString();
  1171. }
  1172. dtb.Rows.Add(dataRow);
  1173. //this.dataGridView4.Rows[r].Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
  1174. }
  1175. List<DataTable> list = new List<DataTable>();
  1176. list.Add(dtb);
  1177. this.appWorkspace.ExportDataToExcelWithProgress(list, exe.FileName, true, false, true);
  1178. }
  1179. /// <summary>
  1180. /// 不可点击空白区域
  1181. /// </summary>
  1182. /// <param name="sender"></param>
  1183. /// <param name="e"></param>
  1184. private void listView1_MouseUp(object sender, MouseEventArgs e)
  1185. {
  1186. if (e.Button == MouseButtons.Left)
  1187. {
  1188. if (listView1.SelectedItems.Count > 0)
  1189. {
  1190. }
  1191. else if (listView1.SelectedItems.Count <= 0)//点击空白区
  1192. {
  1193. if (this.listView1.FocusedItem != null)
  1194. {
  1195. ListViewItem item = this.listView1.GetItemAt(e.X, e.Y);
  1196. if (item == null)
  1197. {
  1198. this.listView1.FocusedItem.Selected = true;
  1199. }
  1200. }
  1201. }
  1202. }
  1203. }
  1204. /// <summary>
  1205. /// 生成孔隙率
  1206. /// </summary>
  1207. /// <param name="sender"></param>
  1208. /// <param name="e"></param>
  1209. private void button13_Click(object sender, EventArgs e)
  1210. {
  1211. //string path = string.Empty;
  1212. //System.Windows.Forms.FolderBrowserDialog fbd = new System.Windows.Forms.FolderBrowserDialog();
  1213. //fbd.Description = "请选择文件夹";
  1214. //String str = System.Configuration.ConfigurationManager.AppSettings["FolderSelectedPath"];
  1215. //if (!string.IsNullOrEmpty(str))
  1216. //{
  1217. // fbd.SelectedPath = str;
  1218. //}
  1219. //if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  1220. //{
  1221. // path = fbd.SelectedPath;
  1222. // PrintReport(path);
  1223. // Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
  1224. // cfa.AppSettings.Settings["FolderSelectedPath"].Value = path;
  1225. // cfa.Save();
  1226. // System.Configuration.ConfigurationManager.RefreshSection("appSettings");
  1227. //}
  1228. string name = this.listView1.FocusedItem.Name.Split('.')[0] + "-";
  1229. SaveFileDialog exe = new SaveFileDialog();
  1230. exe.Filter = "Execl files (*.xlsx)|*.xlsx";
  1231. exe.FilterIndex = 0;
  1232. exe.RestoreDirectory = true;
  1233. //exe.CreatePrompt = true;
  1234. exe.Title = "Export Excel File";
  1235. // exe.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
  1236. exe.FileName = name;
  1237. //String str = System.Configuration.ConfigurationManager.AppSettings["FolderSelectedPath"];
  1238. DialogResult dr = exe.ShowDialog();
  1239. if (dr != DialogResult.OK)
  1240. {
  1241. return;
  1242. }
  1243. DataTable dtb = new DataTable();
  1244. foreach (DataGridViewColumn c in this.dataGridView1.Columns)
  1245. {
  1246. dtb.Columns.Add(c.HeaderText);
  1247. }
  1248. for (int r = 0; r < this.dataGridView1.Rows.Count; r++)
  1249. {
  1250. DataRow dataRow = dtb.NewRow();
  1251. for (int c = 0; c < this.dataGridView1.Rows[r].Cells.Count; c++)
  1252. {
  1253. dataRow[this.dataGridView1.Columns[c].HeaderText] = (string)this.dataGridView1.Rows[r].Cells[c].Value.ToString();
  1254. }
  1255. dtb.Rows.Add(dataRow);
  1256. //this.dataGridView4.Rows[r].Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
  1257. }
  1258. int index = exe.FileName.LastIndexOf('\\');
  1259. List<DataTable> list = new List<DataTable>();
  1260. list.Add(dtb);
  1261. DataTable dtb1 = new DataTable();
  1262. foreach (DataGridViewColumn c in this.dataGridView4.Columns)
  1263. {
  1264. dtb1.Columns.Add(c.HeaderText);
  1265. }
  1266. for (int r = 0; r < this.dataGridView4.Rows.Count; r++)
  1267. {
  1268. DataRow dataRow = dtb1.NewRow();
  1269. for (int c = 0; c < this.dataGridView4.Rows[r].Cells.Count; c++)
  1270. {
  1271. dataRow[this.dataGridView4.Columns[c].HeaderText] = (string)this.dataGridView4.Rows[r].Cells[c].Value.ToString();
  1272. }
  1273. dtb1.Rows.Add(dataRow);
  1274. //this.dataGridView4.Rows[r].Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
  1275. }
  1276. list.Add(dtb1);
  1277. //保存处理后的图片
  1278. double pantographRatio = (double)this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem.Index].GetRulerMultiple(MeasurementUnit.Micron);//标尺*放大倍数
  1279. List<Bitmap> tempBit = new List<Bitmap>();
  1280. Bitmap originalBit = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem.Index].CompositionSurface.CreateAliasedBitmap();
  1281. originalBit.Tag = pantographRatio;
  1282. tempBit.Add(originalBit);
  1283. Bitmap processedBit = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(this.documentWorkspace.PhaseModels[0].mat);
  1284. Bitmap newBit = originalBit.Clone(new Rectangle(0, 0, originalBit.Width, originalBit.Height), originalBit.PixelFormat);
  1285. Graphics graphics = Graphics.FromImage(newBit);
  1286. graphics.DrawImage(processedBit, new PointF(0, 0));
  1287. Draw(graphics);
  1288. newBit.Tag = pantographRatio;
  1289. tempBit.Add(newBit);
  1290. string GR_Path = exe.FileName.Remove(index) + "\\" + name + ".jpg";
  1291. newBit.Save(GR_Path);
  1292. this.appWorkspace.ExportDataToExcelWithProgress(list, exe.FileName, true, false, true);
  1293. }
  1294. /// <summary>
  1295. /// 导出报告
  1296. /// </summary>
  1297. private void PrintReport(string savePath)
  1298. {
  1299. List<List<string>> analysisContent = new List<List<string>>();
  1300. for (int i = 0; i < this.dataGridView1.Rows.Count; i++)
  1301. {
  1302. List<string> content1 = new List<string>();
  1303. if (i == 0)
  1304. {
  1305. content1.Add(this.dataGridView1.Columns[0].HeaderText);
  1306. content1.Add(this.dataGridView1.Columns[1].HeaderText);
  1307. analysisContent.Add(content1);
  1308. }
  1309. content1 = new List<string>();
  1310. content1.Add(this.dataGridView1.Rows[i].Cells[0].Value.ToString());
  1311. content1.Add(this.dataGridView1.Rows[i].Cells[1].Value.ToString());
  1312. analysisContent.Add(content1);
  1313. }
  1314. List<string> content2 = new List<string>();
  1315. analysisContent.Add(content2);
  1316. for (int i = 0; i < this.dataGridView4.Rows.Count; i++)
  1317. {
  1318. List<string> content1 = new List<string>();
  1319. if (i == 0)
  1320. {
  1321. content1.Add(this.dataGridView4.Columns[0].HeaderText);
  1322. content1.Add(this.dataGridView4.Columns[1].HeaderText);
  1323. content1.Add(this.dataGridView4.Columns[2].HeaderText);
  1324. content1.Add(this.dataGridView4.Columns[3].HeaderText);
  1325. content1.Add(this.dataGridView4.Columns[4].HeaderText);
  1326. content1.Add(this.dataGridView4.Columns[5].HeaderText);
  1327. analysisContent.Add(content1);
  1328. }
  1329. content1 = new List<string>();
  1330. content1.Add(this.dataGridView4.Rows[i].Cells[0].Value.ToString());
  1331. content1.Add(this.dataGridView4.Rows[i].Cells[1].Value.ToString());
  1332. content1.Add(this.dataGridView4.Rows[i].Cells[2].Value.ToString());
  1333. content1.Add(this.dataGridView4.Rows[i].Cells[3].Value.ToString());
  1334. content1.Add(this.dataGridView4.Rows[i].Cells[4].Value.ToString());
  1335. content1.Add(this.dataGridView4.Rows[i].Cells[5].Value.ToString());
  1336. analysisContent.Add(content1);
  1337. }
  1338. //保存处理后的图片
  1339. double pantographRatio = (double)this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem.Index].GetRulerMultiple(MeasurementUnit.Micron);//标尺*放大倍数
  1340. List<Bitmap> tempBit = new List<Bitmap>();
  1341. Bitmap originalBit = this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem.Index].CompositionSurface.CreateAliasedBitmap();
  1342. originalBit.Tag = pantographRatio;
  1343. tempBit.Add(originalBit);
  1344. Bitmap processedBit = OpenCvSharp.Extensions.BitmapConverter.ToBitmap(this.documentWorkspace.PhaseModels[0].mat);
  1345. Bitmap newBit = originalBit.Clone(new Rectangle(0, 0, originalBit.Width, originalBit.Height), originalBit.PixelFormat);
  1346. Graphics graphics = Graphics.FromImage(newBit);
  1347. graphics.DrawImage(processedBit, new PointF(0, 0));
  1348. Draw(graphics);
  1349. newBit.Tag = pantographRatio;
  1350. tempBit.Add(newBit);
  1351. List<Bitmap> bitList = new List<Bitmap>();
  1352. bitList.Add(tempBit[0]);
  1353. bitList.Add(tempBit[1]);
  1354. Dictionary<string, string> tagInfos = new Dictionary<string, string>();
  1355. // this.analyzeSettingModel.analyzeClassify
  1356. AnalyzeSettingModel model = new AnalyzeSettingModel();
  1357. string filePath = Application.StartupPath + "\\ModuleManage\\Dedicated\\MicrostructureBand_ASTME1268\\截面孔隙.docx";//获取文档路径
  1358. string filePath2 = "E:\\图形处理\\Metisvision20210204\\RBDC\\Metisvision\\bin\\Debug\\ModuleManage\\Dedicated\\MicrostructureBand_ASTME1268\\截面孔隙.docx";
  1359. model.modulePath = filePath;
  1360. model.savePath = savePath;
  1361. //model.itemNumber = this.textBox2.Text;
  1362. //model.ratingDate = this.dateTimePicker1.Value;
  1363. //model.inspectionPerson = this.textBox4.Text;
  1364. model.contact = "";
  1365. //model.inspectionDepartment = this.textBox5.Text;
  1366. //model.inspectionDate = this.dateTimePicker2.Value;
  1367. string name = this.listView1.FocusedItem.Name.Split('.')[0];
  1368. model.analyzeClassify = name;
  1369. this.analyzeSettingModel = new AnalyzeSettingModel();
  1370. //this.analyzeSettingModel.modelItems = new List<AnalyzeSavedModel.ModelItem>();
  1371. //this.analyzeSettingModel = new AnalyzeSavedModel.ModelItem();
  1372. //this.analyzeSettingModel.languageName = this.languageName;
  1373. this.analyzeSettingModel = model;
  1374. //this.analyzeSettingModel.modelItems.Add(analyzeModel);
  1375. this.appWorkspace.CreateAnalysisReport(this.analyzeSettingModel, analysisContent, bitList, tagInfos);
  1376. }
  1377. #region 内部类
  1378. internal class LocalListViewItem
  1379. {
  1380. public DocumentWorkspace Value { get; }
  1381. public string Display { get; }
  1382. public LocalListViewItem(DocumentWorkspace Value, string Display)
  1383. {
  1384. this.Value = Value;
  1385. this.Display = Display;
  1386. }
  1387. }
  1388. internal class DocumentItem
  1389. {
  1390. public Bitmap bitmap;
  1391. public GraphicsList graphicsList;
  1392. public List<PhaseModel> phaseModels;
  1393. //public AnalysisResult analysisResult;
  1394. public DocumentItem(Bitmap bitmap, GraphicsList graphicsList, List<PhaseModel> phaseModels)
  1395. {
  1396. this.bitmap = bitmap;
  1397. this.graphicsList = graphicsList;
  1398. this.phaseModels = phaseModels;
  1399. }
  1400. }
  1401. #endregion
  1402. #region 测试方法
  1403. //小球识别
  1404. private void saveimaget(int y)
  1405. {
  1406. DirectoryInfo derectory = new DirectoryInfo(@"E:\0\");
  1407. int uu = 0;
  1408. foreach (var file in derectory.GetFiles())
  1409. {
  1410. uu++;
  1411. Mat colon = new Mat();
  1412. Mat gray = new Mat();
  1413. Mat binary = new Mat();
  1414. Mat shifted = new Mat();
  1415. Mat g_srcImage = Cv2.ImRead(file.FullName);
  1416. colon = g_srcImage.Clone();
  1417. Cv2.GaussianBlur(g_srcImage, shifted, new OpenCvSharp.Size(15, 15), 0);
  1418. Cv2.CvtColor(shifted, gray, ColorConversionCodes.BGR2GRAY);
  1419. //二值化
  1420. double otsu = Cv2.Threshold(gray, binary, 0, 255, ThresholdTypes.Otsu/*.Otsu*/);
  1421. // distance transform
  1422. Mat dist = new Mat();
  1423. Cv2.DistanceTransform(binary, dist, DistanceTypes.L2, DistanceMaskSize.Mask3);
  1424. //归一化数据
  1425. Cv2.Normalize(dist, dist, 0, 1, NormTypes.MinMax);
  1426. // binary
  1427. Cv2.Threshold(dist, dist, 0.4, 1, ThresholdTypes.Binary);
  1428. // markers
  1429. Mat dist_m = new Mat();
  1430. dist.ConvertTo(dist_m, MatType.CV_8UC1);
  1431. OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
  1432. HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
  1433. Cv2.FindContours(dist_m, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
  1434. double maxarea = 0;
  1435. int maxindex = 0;
  1436. // create markers
  1437. Mat markers = Mat.Zeros(g_srcImage.Size(), MatType.CV_32SC1);
  1438. for (int t = 0; t < contours.Length; t++)
  1439. {
  1440. if (Cv2.ContourArea(contours[t]) > maxarea)
  1441. {
  1442. maxarea = Cv2.ContourArea(contours[t]);
  1443. maxindex = t;
  1444. }
  1445. }
  1446. Cv2.DrawContours(markers, contours, maxindex, new Scalar(1), -1);
  1447. // Cv2.ImShow("分割后", markers);
  1448. Cv2.Circle(markers, new OpenCvSharp.Point(5, 5), 30, new Scalar(255), -1);
  1449. //形体学操作 去掉干扰
  1450. InputArray kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));
  1451. Cv2.MorphologyEx(g_srcImage, g_srcImage, MorphTypes.Erode, kernel);
  1452. Cv2.Watershed(g_srcImage, markers);
  1453. // 颜色填充与最终显示
  1454. int index = 0;
  1455. Dictionary<int, List<OpenCvSharp.Point>> particlePixles = new Dictionary<int, List<OpenCvSharp.Point>>();
  1456. for (int row = 0; row < markers.Rows; row++)
  1457. {
  1458. for (int col = 0; col < markers.Cols; col++)
  1459. {
  1460. index = markers.At<int>(row, col);
  1461. if (index > 0 && index <= contours.Length)
  1462. {
  1463. if (particlePixles.ContainsKey(index))
  1464. {
  1465. particlePixles[index].Add(new OpenCvSharp.Point(col, row));
  1466. }
  1467. else
  1468. {
  1469. List<OpenCvSharp.Point> Pixles = new List<OpenCvSharp.Point>();
  1470. Pixles.Add(new OpenCvSharp.Point(col, row));
  1471. particlePixles.Add(index, Pixles);
  1472. }
  1473. }
  1474. }
  1475. }
  1476. foreach (var item in particlePixles)
  1477. {
  1478. Rect rect = Cv2.BoundingRect(item.Value);
  1479. List<OpenCvSharp.Point> pixel = item.Value;
  1480. Mat forwrit = g_srcImage[rect];
  1481. for (int i = 0; i < g_srcImage.Cols; i++)
  1482. {
  1483. for (int j = 0; j < g_srcImage.Rows; j++)
  1484. {
  1485. OpenCvSharp.Point pp = new OpenCvSharp.Point() { X = i, Y = j };
  1486. if (pixel.Contains(pp))
  1487. {
  1488. continue;
  1489. }
  1490. colon.Set<Vec3b>(j, i, new Vec3b(255, 0, 0));
  1491. }
  1492. }
  1493. }
  1494. Cv2.ImWrite("E:/ballcut/" + file.Name, colon);
  1495. }
  1496. }
  1497. //小球识别
  1498. private void getball()
  1499. {
  1500. DirectoryInfo derectory = new DirectoryInfo(@"E:\JPEGImages\");
  1501. int uu = 0;
  1502. foreach (var file in derectory.GetFiles())
  1503. {
  1504. uu++;
  1505. Mat colon = new Mat();
  1506. Mat gray = new Mat();
  1507. Mat binary = new Mat();
  1508. Mat shifted = new Mat();
  1509. Mat g_srcImage = Cv2.ImRead(file.FullName);
  1510. colon = g_srcImage.Clone();
  1511. Cv2.GaussianBlur(g_srcImage, shifted, new OpenCvSharp.Size(15, 15), 0);
  1512. Cv2.CvtColor(shifted, gray, ColorConversionCodes.BGR2GRAY);
  1513. //二值化
  1514. double otsu = Cv2.Threshold(gray, binary, 0, 255, ThresholdTypes.Otsu/*.Otsu*/);
  1515. // distance transform
  1516. Mat dist = new Mat();
  1517. Cv2.DistanceTransform(binary, dist, DistanceTypes.L2, DistanceMaskSize.Mask3);
  1518. //归一化数据
  1519. Cv2.Normalize(dist, dist, 0, 1, NormTypes.MinMax);
  1520. // binary
  1521. Cv2.Threshold(dist, dist, 0.4, 1, ThresholdTypes.Binary);
  1522. // markers
  1523. Mat dist_m = new Mat();
  1524. dist.ConvertTo(dist_m, MatType.CV_8UC1);
  1525. OpenCvSharp.Point[][] contours = new OpenCvSharp.Point[][] { };
  1526. HierarchyIndex[] hierarchyIndex = new HierarchyIndex[] { };
  1527. Cv2.FindContours(dist_m, out contours, out hierarchyIndex, RetrievalModes.External, ContourApproximationModes.ApproxNone);
  1528. // create markers
  1529. Mat markers = Mat.Zeros(g_srcImage.Size(), MatType.CV_32SC1);
  1530. for (int t = 0; t < contours.Length; t++)
  1531. {
  1532. Cv2.DrawContours(markers, contours, t, new Scalar(t + 1), -1);
  1533. }
  1534. // Cv2.ImShow("分割后", markers);
  1535. Cv2.Circle(markers, new OpenCvSharp.Point(5, 5), 30, new Scalar(255), -1);
  1536. //形体学操作 去掉干扰
  1537. InputArray kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(3, 3), new OpenCvSharp.Point(-1, -1));
  1538. Cv2.MorphologyEx(g_srcImage, g_srcImage, MorphTypes.Erode, kernel);
  1539. Cv2.Watershed(g_srcImage, markers);
  1540. // 颜色填充与最终显示
  1541. int index = 0;
  1542. Dictionary<int, List<OpenCvSharp.Point>> particlePixles = new Dictionary<int, List<OpenCvSharp.Point>>();
  1543. for (int row = 0; row < markers.Rows; row++)
  1544. {
  1545. for (int col = 0; col < markers.Cols; col++)
  1546. {
  1547. index = markers.At<int>(row, col);
  1548. if (index > 0 && index <= contours.Length)
  1549. {
  1550. if (particlePixles.ContainsKey(index))
  1551. {
  1552. particlePixles[index].Add(new OpenCvSharp.Point(col, row));
  1553. }
  1554. else
  1555. {
  1556. List<OpenCvSharp.Point> Pixles = new List<OpenCvSharp.Point>();
  1557. Pixles.Add(new OpenCvSharp.Point(col, row));
  1558. particlePixles.Add(index, Pixles);
  1559. }
  1560. }
  1561. }
  1562. }
  1563. int k = 0;
  1564. foreach (var item in particlePixles)
  1565. {
  1566. if (item.Value.Count > 99999)
  1567. {
  1568. k = item.Key;
  1569. break;
  1570. }
  1571. }
  1572. particlePixles.Remove(k);
  1573. int index1 = 0;
  1574. foreach (var item in particlePixles)
  1575. {
  1576. Rect rect = Cv2.BoundingRect(item.Value);
  1577. List<OpenCvSharp.Point> pixel = item.Value;
  1578. Mat forwrit = colon[rect];
  1579. Mat small = forwrit.Clone();
  1580. for (int i = 0; i < small.Cols; i++)
  1581. {
  1582. for (int j = 0; j < small.Rows; j++)
  1583. {
  1584. OpenCvSharp.Point pp = new OpenCvSharp.Point() { X = i + rect.X, Y = j + rect.Y };
  1585. if (pixel.Contains(pp))
  1586. {
  1587. continue;
  1588. }
  1589. small.Set<Vec3b>(j, i, new Vec3b(255, 0, 0));
  1590. }
  1591. }
  1592. Cv2.ImWrite("E:/0/" +file.Name + index1.ToString() + ".jpg", small);
  1593. index1++;
  1594. }
  1595. }
  1596. }
  1597. #endregion
  1598. #endregion
  1599. }
  1600. }