using OpenCvSharp; using PaintDotNet.Base.CommTool; using PaintDotNet.Base.SettingModel; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace PaintDotNet.DedicatedAnalysis.GrainSize.GBT32461 { internal class MethodAreaDialog : GrainSizeStandardDialog { #region 组件 private GroupBox groupBox11; private Button button4; private CheckBox checkBox11; private CheckBox checkBox5_0; private CheckBox checkBox4_0; private CheckBox checkBox3_0; private RadioButton radioButton_DarkGray; #endregion 组件 #region 构造函数 public MethodAreaDialog(AppWorkspace appWorkspace) : base(appWorkspace, true, true) { } #endregion 构造函数 #region 初始化组件 private void InitializeLanguageText() { this.radioButton_DarkGray.Text = PdnResources.GetString("Menu.Darkgray.text"); this.groupBox11.Text = PdnResources.GetString("Menu.Displayparamssettings.text"); this.button4.Text = PdnResources.GetString("Menu.Refresh.text"); this.checkBox11.Text = PdnResources.GetString("Menu.Thegrainsareshownindifferentcolors.text"); this.checkBox5_0.Text = PdnResources.GetString("Menu.Displaygrainnumber.text"); this.checkBox4_0.Text = PdnResources.GetString("Menu.displaygrid.text"); this.checkBox3_0.Text = PdnResources.GetString("Menu.displaygrainboundaries.text"); this.Text = "GBT32461(" + PdnResources.GetString("Menu.Dedicatedanalysis.Nmetals.Averagegraimethod.text") + ")"; } private void InitializeComponent() { this.radioButton_DarkGray = new System.Windows.Forms.RadioButton(); this.groupBox11 = new System.Windows.Forms.GroupBox(); this.button4 = new System.Windows.Forms.Button(); this.checkBox11 = new System.Windows.Forms.CheckBox(); this.checkBox5_0 = new System.Windows.Forms.CheckBox(); this.checkBox4_0 = new System.Windows.Forms.CheckBox(); this.checkBox3_0 = new System.Windows.Forms.CheckBox(); this.groupBox_analysisResult1.SuspendLayout(); this.groupBox11.SuspendLayout(); this.SuspendLayout(); // // radioButton_DarkGray // this.radioButton_DarkGray.AutoSize = true; this.radioButton_DarkGray.Location = new System.Drawing.Point(178, 20); this.radioButton_DarkGray.Name = "radioButton_DarkGray"; this.radioButton_DarkGray.Size = new System.Drawing.Size(59, 16); this.radioButton_DarkGray.TabIndex = 38; this.radioButton_DarkGray.TabStop = true; this.radioButton_DarkGray.UseVisualStyleBackColor = true; // // groupBox11 // this.groupBox11.Controls.Add(this.button4); this.groupBox11.Controls.Add(this.checkBox11); this.groupBox11.Controls.Add(this.checkBox5_0); this.groupBox11.Controls.Add(this.checkBox4_0); this.groupBox11.Controls.Add(this.checkBox3_0); this.groupBox11.Location = new System.Drawing.Point(179, 553); this.groupBox11.Name = "groupBox11"; this.groupBox11.Size = new System.Drawing.Size(356, 71); this.groupBox11.TabIndex = 38; this.groupBox11.TabStop = false; // // button4 // this.button4.Anchor = System.Windows.Forms.AnchorStyles.Right; this.button4.Location = new System.Drawing.Point(259, 18); this.button4.Name = "button4"; this.button4.Size = new System.Drawing.Size(75, 23); this.button4.TabIndex = 18; this.button4.UseVisualStyleBackColor = true; this.button4.Click += new System.EventHandler(this.button4_Click); // // checkBox11 // this.checkBox11.AutoSize = true; this.checkBox11.Checked = true; this.checkBox11.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox11.Location = new System.Drawing.Point(139, 44); this.checkBox11.Name = "checkBox11"; this.checkBox11.Size = new System.Drawing.Size(132, 16); this.checkBox11.TabIndex = 3; this.checkBox11.UseVisualStyleBackColor = true; this.checkBox11.CheckedChanged += new System.EventHandler(this.checkBox11_CheckedChanged); // // checkBox5_0 // this.checkBox5_0.AutoSize = true; this.checkBox5_0.Checked = true; this.checkBox5_0.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox5_0.Location = new System.Drawing.Point(140, 22); this.checkBox5_0.Name = "checkBox5_0"; this.checkBox5_0.Size = new System.Drawing.Size(96, 16); this.checkBox5_0.TabIndex = 2; this.checkBox5_0.UseVisualStyleBackColor = true; this.checkBox5_0.CheckedChanged += new System.EventHandler(this.checkBox5_0_CheckedChanged); // // checkBox4_0 // this.checkBox4_0.AutoSize = true; this.checkBox4_0.Checked = true; this.checkBox4_0.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox4_0.Location = new System.Drawing.Point(15, 44); this.checkBox4_0.Name = "checkBox4_0"; this.checkBox4_0.Size = new System.Drawing.Size(72, 16); this.checkBox4_0.TabIndex = 1; this.checkBox4_0.UseVisualStyleBackColor = true; this.checkBox4_0.CheckedChanged += new System.EventHandler(this.checkBox4_0_CheckedChanged); // // checkBox3_0 // this.checkBox3_0.AutoSize = true; this.checkBox3_0.Checked = true; this.checkBox3_0.CheckState = System.Windows.Forms.CheckState.Checked; this.checkBox3_0.Location = new System.Drawing.Point(15, 22); this.checkBox3_0.Name = "checkBox3_0"; this.checkBox3_0.Size = new System.Drawing.Size(72, 16); this.checkBox3_0.TabIndex = 0; this.checkBox3_0.UseVisualStyleBackColor = true; this.checkBox3_0.CheckedChanged += new System.EventHandler(this.checkBox3_0_CheckedChanged); // // MethodAreaDialog // this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.ClientSize = new System.Drawing.Size(1127, 830); this.Controls.Add(this.groupBox11); this.Name = "MethodAreaDialog"; this.Controls.SetChildIndex(this.groupBox_img, 0); this.Controls.SetChildIndex(this.groupBox_review, 0); this.Controls.SetChildIndex(this.groupBox_analysisResult1, 0); this.Controls.SetChildIndex(this.groupBox6groupBox_analysisResult2, 0); this.Controls.SetChildIndex(this.groupBox_report, 0); this.Controls.SetChildIndex(this.groupBox11, 0); this.groupBox_analysisResult1.ResumeLayout(false); this.groupBox11.ResumeLayout(false); this.groupBox11.PerformLayout(); this.ResumeLayout(false); } #endregion 初始化组件 #region 需继承方法 protected override Boolean toshowPhoseModelAt(int index) { if (index == 1) { return (!showOrimat() && getGrainBoundryChecked() && checkBox3_0.Checked); } return true; } protected override void refreshWhileImgChanged() { if (this.bitmap != null && this.documentWorkspace.PhaseModels[2].mat != null && linePointList.Count > 0) { try { Getrains(linePointList, guideClass.RectangleFLine); } catch (Exception) { } } else { this.documentWorkspace.PhaseModels[2].mat = null;//清空前一张图的信息不遗留显示##效果考虑优化 massLabelPoints.Clear();//1013###19098(切换图片的时候前一张图的信息不遗留显示)} this.documentWorkspace.Refresh(); } } protected override void refreshPhaseModelChoise() { if (!showOrimat() && checkBox11.Checked) { this.documentWorkspace.PhaseModels[2].choise = true; } else { this.documentWorkspace.PhaseModels[2].choise = false; } } /// /// 保存结果 /// protected override void buildListBox_analysisResult() { if (this.matOrg == null) { MessageBox.Show(PdnResources.GetString("Menu.Pleaseselectapicture.text")+"!"); return; } if (this.comboBox1.SelectedItem != null && !PdnResources.GetString("Menu.Pleaseselecttheauxiliarylineused.text").Equals(this.comboBox1.SelectedItem)) { string imgName = getCurrentWorkspace().GetFriendlyName(); string tag = getCurrentWorkTag(); System.Data.DataTable dataTable = new System.Data.DataTable(); bool replace = false; int add = 0; foreach (ListViewItem item in this.listView2.Items) { if (item.Tag.Equals(tag)) { add++; DialogResult dr = MessageBox.Show(PdnResources.GetString("Menu.Theresuethertoreplace.text")+"?", PdnResources.GetString("Menu.hint.text"), MessageBoxButtons.OKCancel, MessageBoxIcon.Question); if (dr == DialogResult.OK) { replace = true; } break; } } if (replace || this.listView2.Items.Count == 0 || add == 0) { if (!replace) { ListViewItem listViewItem = new ListViewItem(); listViewItem.SubItems[0].Text = imgName; listViewItem.Tag = "" + tag; if (this.listView2.Items.Count == 0) this.listView2.Items.Add(listViewItem); else this.listView2.Items.Insert(0, listViewItem); } this.dataGridView2.Rows.Clear(); DataGridViewRow dgvr = new DataGridViewRow(); foreach (DataGridViewColumn c in this.dataGridView2.Columns) { dgvr.Cells.Add(c.CellTemplate.Clone() as DataGridViewCell); } dgvr.Cells[0].Value = imgName; dgvr.Cells[1].Value = this.comboBox1.SelectedItem; // 是否矩形辅助线 int isRect; double aec = guideClass.guideArea(this.comboBox1.SelectedItem, out isRect, 0/*this.gbtType*/); dgvr.Cells[2].Value = aec; aec = aec * 0.001 * 0.001; double grainNumber = GetNumberOfGrains(linePointList, guideClass.RectangleFLine); if (grainNumber > (int)grainNumber) { grainNumber = grainNumber + 0.5; } dgvr.Cells[3].Value = grainNumber; decimal M = 1;// this.getGainMultiple(); double small_l = (grainNumber * (double)M * (double)M) / aec; decimal A = Convert.ToDecimal(small_l * 1); double[] lengths = {3.88, 7.75 , 11.0, 15.50, 21.9, 25.0, 31.0, 43.8, 62.0, 69.4, 87.7, 100, 124, 175, 204, 248, 278, 351, 400, 496, 625, 701, 816, 992, 1111 , 1403, 1600, 1980, 2500, 2810, 3970, 4440, 5610, 7940, 10000, 11220, 12350, 15870, 20410, 22450, 27780, 31710, 40000, 44900, 63500, 89800 , 111100, 127000, 160000/*2.22*/};//###这块逻辑多认证认证 // 差值 decimal differenceNew = 0; decimal differenceOld = Math.Abs(Convert.ToDecimal(Math.Max((double)A - 2.88, (double)A - 160001)));// Convert.ToDecimal(double.MaxValue);// Math.Abs(A - 160000);// Convert.ToDecimal((double)A - 2.22); double selectArea = 0; int first = -1; foreach (double item in lengths) { selectArea = item; differenceNew = Math.Abs(A - Convert.ToDecimal(item)); if (differenceNew < differenceOld) { differenceOld = Math.Abs(A - Convert.ToDecimal(item)); first++; } else break; } string[] valueG = {"00A", "0" , "0.5", "1.0", "1.5", "1.5"/**/, "2.0", "2.5", "3.0", "3.0", "3.5", "3.5", "4.0", "4.5", "4.5", "5.0", "5.0", "5.5", "5.5", "6.0", "6.0", "6.5", "6.5", "7.0", "7.0" , "7.5", "7.5", "8.0", "8.0", "8.5", "9.0", "9.0", "9.5", "10.0", "10.0", "10.5", "10.5", "11.0", "11.0", "11.5", "11.5", "12.0", "12.0", "12.5", "13.0", "13.5" , "13.5", "14.0", "14.0"}; if (first >= valueG.Length) { first = valueG.Length - 1; } else if (first < 0) { first = 0; } dgvr.Cells[4].Value = valueG[first]; this.dataGridView2.Rows.Add(dgvr); dataTable.TableName = tag; foreach (System.Data.DataTable dataTable1 in dataTables) { if (dataTable1.TableName.Equals(dataTable.TableName)) { dataTables.Remove(dataTable1); break; } } foreach (DataGridViewColumn c in this.dataGridView2.Columns) { dataTable.Columns.Add(c.HeaderText); } for (int r = 0; r < this.dataGridView2.Rows.Count; r++) { DataRow dataRow = dataTable.NewRow(); for (int c = 0; c < this.dataGridView2.Rows[r].Cells.Count; c++) { dataRow[this.dataGridView2.Columns[c].HeaderText] = this.dataGridView2.Rows[r].Cells[c].Value; } dataTable.Rows.Add(dataRow); } this.dataTables.Add(dataTable); this.RefreshDataGridView4(); //保存处理后的图片 List tempBit = new List(); Bitmap originalBit = this.bitmap;// this.appWorkspace.DocumentWorkspaces[this.listView1.FocusedItem.Index].CompositionSurface.CreateAliasedBitmap(); tempBit.Add(originalBit); Bitmap newBit = originalBit.Clone(new Rectangle(0, 0, originalBit.Width, originalBit.Height), originalBit.PixelFormat); Graphics graphics = Graphics.FromImage(newBit); //if (true) //{ }//0914###18810 if (this.documentWorkspace.PhaseModels[0].choise && this.documentWorkspace.PhaseModels[0].mat != null) { Mat targetMat = this.documentWorkspace.PhaseModels[0].mat; graphics.DrawImage(OpenCvSharp.Extensions.BitmapConverter.ToBitmap(targetMat), 0, 0, targetMat.Width, targetMat.Height); } if (this.documentWorkspace.PhaseModels[1].choise && this.documentWorkspace.PhaseModels[1].mat != null) { Mat targetMat = this.documentWorkspace.PhaseModels[1].mat; graphics.DrawImage(OpenCvSharp.Extensions.BitmapConverter.ToBitmap(targetMat), 0, 0, targetMat.Width, targetMat.Height); } if (this.documentWorkspace.PhaseModels[2].choise && this.documentWorkspace.PhaseModels[2].mat != null) { Mat targetMat = this.documentWorkspace.PhaseModels[2].mat; graphics.DrawImage(OpenCvSharp.Extensions.BitmapConverter.ToBitmap(targetMat), 0, 0, targetMat.Width, targetMat.Height); } graphics.SmoothingMode = SmoothingMode.AntiAlias; drawSubclass(graphics); tempBit.Add(newBit); if (bitDic.ContainsKey(tag)) bitDic[tag] = tempBit; else bitDic.Add(tag, tempBit); //拼接中间数据 List> dataList = new List>(); List columnName = new List(); columnName.Add(PdnResources.GetString("Menu.Imagement.Measurementlist.ordernumber.text")); columnName.Add("X"+ PdnResources.GetString("Menu.coordinates.Text")); columnName.Add("Y"+ PdnResources.GetString("Menu.coordinates.Text")); columnName.Add(PdnResources.GetString("Menu.Whethertheinternal.Text")); dataList.Add(columnName); if (massLabelPoints.Count > 0) { int index = 0; int outMaxIndex = massLabelPoints.Count - 0 - within; foreach (var item in massLabelPoints) { List strList = new List(); strList.Add(("" + (++index)).ToString()); strList.Add(item.X.ToString()); strList.Add(item.Y.ToString()); if (outMaxIndex < index) strList.Add(PdnResources.GetString("Menu.Yes.text")); else strList.Add(PdnResources.GetString("Menu.no.text")); dataList.Add(strList); } } bool isExist = false;//是否已存在进行替换 int modelIndex = -1;//要替换的下标 for (int j = 0; j < tempDataModel.Count; j++) { if (tempDataModel[j].tagName.Equals(tag)) { isExist = true; modelIndex = j; break; } } if (isExist && modelIndex > -1) tempDataModel[modelIndex].dataList = dataList; else { Base.Functionodel.ExportProjectModel newModel = new Base.Functionodel.ExportProjectModel(); newModel.tagName = tag; newModel.picName = imgName; newModel.dataList = dataList; tempDataModel.Add(newModel); } } } else { MessageBox.Show(PdnResources.GetString("Menu.Pleaseselectauxiliaryline.text")+"!"); } } protected override void SubclassInitialize() { InitializeComponent(); InitializeLanguageText(); } //是否绘制辅助线 protected override bool drawGuideLines() { return checkBox4_0.Checked; } //是否绘制截点 protected override bool drawGuidePoints() { return (matOrg != null && this.checkBox5_0.Checked); } //是否绘制编号 protected override bool drawMassLabelPoints() { return this.checkBox5_0.Checked; } //辅助线类型 protected override string[] getTypeNames() { return new string[] { PdnResources.GetString("Menu.circular.Text")}; } protected override string getTemplateName() { return "Template.Manager.item3.GrainSizeArea_GBT32461"; } protected override string getProjectEngineeringName() { return "Menu.DedicatedAnalysis.NonferrousMetal.AluminiumAlloy.Text"; } protected override string getModelName() { return "GrainGBT32461AreaMethodModel.xml"; } #endregion /// /// 刷新晶粒编号 /// /// /// private void button4_Click(object sender, EventArgs e) { if (this.matOrg == null) { MessageBox.Show(PdnResources.GetString("Menu.Pleaseselectapicturefirst.text")); return; } Getrains(linePointList, guideClass.RectangleFLine); } private Double GetNumberOfGrains(List pointFs, RectangleF rectangleF) { Mat OriginalPicture; Mat analyzeMat = new Mat(); if (getGrainBoundryChecked()) { OriginalPicture = new Mat(matOrg.Size(), MatType.CV_8UC4, new Scalar(255, 255, 255, 255)); Mat oldMat = this.documentWorkspace.PhaseModels[1].mat; int Rows = oldMat.Rows; int Cols = oldMat.Cols; int[] point = new int[2]; //多通道图像的格式化 for (point[0] = 0; point[0] < Rows; point[0]++) { for (point[1] = 0; point[1] < Cols; point[1]++) { if (oldMat.At(point[0], point[1]).Item3 > 0) { OriginalPicture.Set(point, new Vec4b(0, 0, 0, 255)); } } } Cv2.Erode(OriginalPicture, OriginalPicture, null, null, 1); OriginalPicture.CopyTo(analyzeMat); } else if (getBinaryChecked()) { OriginalPicture = new Mat(matOrg.Size(), MatType.CV_8UC4, new Scalar(255, 255, 255, 255)); Mat oldMat = this.documentWorkspace.PhaseModels[0].mat; int Rows = oldMat.Rows; int Cols = oldMat.Cols; int[] point = new int[2]; //多通道图像的格式化 for (point[0] = 0; point[0] < Rows; point[0]++) { for (point[1] = 0; point[1] < Cols; point[1]++) { if (oldMat.At(point[0], point[1]).Item3 > 0) { OriginalPicture.Set(point, new Vec4b(0, 0, 0, 255)); } } } oldMat.CopyTo(analyzeMat); } else { OriginalPicture = new Mat(matOrg.Size(), MatType.CV_8UC4, new Scalar(255, 255, 255, 255)); matOrg.CopyTo(OriginalPicture); matOrg.CopyTo(analyzeMat); } Mat erzhi = OriginalPicture; Cv2.CvtColor(erzhi, erzhi, ColorConversionCodes.BGRA2GRAY); Cv2.Threshold(erzhi, erzhi, 100, 255, ThresholdTypes.Binary);//############# //Cv2.AdaptiveThreshold(erzhi, erzhi, 255, AdaptiveThresholdTypes.MeanC, ThresholdTypes.Binary, 99, 10); OpenCvSharp.Point[][] contours; HierarchyIndex[] hierarchy; Cv2.FindContours(erzhi, out contours, out hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxNone); //Cv2.ImWrite("erzhi1.tif", erzhi.CvtColor(ColorConversionCodes.GRAY2BGR)); List pointss = new List(); foreach (OpenCvSharp.Point[] contour in contours) { if (contour.Length < 100) { //foreach (OpenCvSharp.Point point in contour) //{ // erzhi.Set(point.Y, point.X, 255); //} pointss.Add(contour); } } Cv2.FillPoly(erzhi, pointss, new Scalar(255)); // 二次轮廓 Cv2.FindContours(erzhi, out contours, out hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxNone); // 计算所有轮廓质点 List massPoints = new List(); foreach (OpenCvSharp.Point[] contour in contours) { OpenCvSharp.Moments moments = new OpenCvSharp.Moments(contour, false); massPoints.Add(new Point2d(moments.M10 / moments.M00, moments.M01 / moments.M00)); } Mat labelMat = new Mat(); Mat stats = new Mat(); Mat centroids = new Mat(); // 连通域数量 int nccomps = Cv2.ConnectedComponentsWithStats(erzhi, labelMat, stats, centroids, PixelConnectivity.Connectivity8); //Cv2.ImWrite("erzhi2.tif", labelMat); //Cv2.ImWrite("erzhi3.tif", stats); //Cv2.ImWrite("erzhi4.tif", centroids); // 连通域质点 Dictionary keyValues = new Dictionary(); massLabelPoints.Clear(); foreach (var item in massPoints) { if (double.IsNaN(item.Y) || double.IsNaN(item.X)) { continue; } int label = labelMat.At((int)item.Y, (int)item.X); if (0 <= label && label <= nccomps) { keyValues[label] = item; } } Mat temp = new Mat(erzhi.Size(), MatType.CV_8UC4, new Scalar(0, 0, 0, 0)); // 矩形边线上的连通域 ArrayList nccompSelect = new ArrayList(); foreach (var pointF in pointFs) { if (labelMat.Width <= pointF.X || labelMat.Height <= pointF.Y || pointF.X < 0 || pointF.Y < 0) { continue; } //判断是否在晶界上面 Vec4b vec4B = analyzeMat.At((int)pointF.Y, (int)pointF.X); if (getGrainBoundryChecked() && vec4B.Item0 == 0 || getBinaryChecked() && vec4B.Item3 != 0 || !getGrainBoundryChecked() && !getBinaryChecked() && vec4B.Item0 == 0) { //temp.Set((int)pointF.Y, (int)pointF.X, new Vec4b(0, 255, 0, 255)); continue;//0925###19106 } int label = labelMat.At((int)pointF.Y, (int)pointF.X); if (!nccompSelect.Contains(label) && keyValues.ContainsKey(label) && keyValues[label] != null) { nccompSelect.Add(label); if (keyValues.ContainsKey(label) && keyValues[label] != null) massLabelPoints.Add(keyValues[label]); // massLabelPoints.Add(new Point2d((int)pointF.X, (int)pointF.Y/*-1, -1*/)); //else // massLabelPoints.Add(new Point2d((int)pointF.Y, (int)pointF.Y/*-1, -1*/)); } else if (keyValues.ContainsKey(label) && keyValues[label] != null) { int iii = 1; } else if (!nccompSelect.Contains(label)) { int iiii = 1; nccompSelect.Add(label); massLabelPoints.Add(new Point2d((int)pointF.X, (int)pointF.Y/*-1, -1*/)); } else { int iiii = 1; } } // 矩形内的连通域 within = 0; ArrayList inccompSelect = new ArrayList(); GrainSizeGuideAreaMethodModel grainSizeGuideStyleModel = guideClass.GrainSizeGuideAreaMethodModel; // 圆形 if (grainSizeGuideStyleModel.circularGuideStyles != null) { foreach (var circularGuideStyle in grainSizeGuideStyleModel.circularGuideStyles) { if (this.comboBox1.SelectedItem.Equals(circularGuideStyle.tag)) { foreach (var keyValue in keyValues) { //求点到圆心的距离 double c = BasicCalculationHelper.GetDistance(new PointF((float)keyValue.Value.X, (float)keyValue.Value.Y), new PointF(rectangleF.X + rectangleF.Width / 2, rectangleF.Y + rectangleF.Height / 2), 10); if (!nccompSelect.Contains(keyValue.Key) && c < guideClass.Mat_lineDiameter / 2) { if (!inccompSelect.Contains(keyValue.Key)) { within++; inccompSelect.Add(keyValue.Key); if (keyValue.Value != null) massLabelPoints.Add(keyValue.Value); } } } } } } // 矩形 if (grainSizeGuideStyleModel.rectangleGuideStyles != null) { foreach (var rectangleGuideStyle in grainSizeGuideStyleModel.rectangleGuideStyles) { if (this.comboBox1.SelectedItem.Equals(rectangleGuideStyle.tag)) { foreach (var keyValue in keyValues) { if (!nccompSelect.Contains(keyValue.Key) && keyValue.Value.X > rectangleF.X && keyValue.Value.X < rectangleF.Right && keyValue.Value.Y > rectangleF.Y && keyValue.Value.Y < rectangleF.Bottom) { if (!inccompSelect.Contains(keyValue.Key)) { within++; inccompSelect.Add(keyValue.Key); if (keyValue.Value != null) massLabelPoints.Add(keyValue.Value); } } } } } } //Mat temp = new Mat(erzhi.Size(), MatType.CV_8UC4); ////Mat temp = new Mat(erzhi.Size(), MatType.CV_8UC1); Random rd = new Random(); List colors = new List(nccomps); colors.Add(new Vec4b(0, 0, 0, 0)); for (int i = 0; i < nccomps; i++) { //colors.Add(new Vec3b(255, 255, 255)); colors.Add(new Vec4b(((byte)(rd.Next() % 256)), ((byte)(rd.Next() % 256)), ((byte)(rd.Next() % 256)), 255)); } for (int y = 0; y < temp.Rows; y++) { for (int x = 0; x < temp.Cols; x++) { int label = labelMat.At(y, x); if (nccompSelect.Contains(label)) temp.Set(y, x, colors[label + 1]); if (inccompSelect.Contains(label)) temp.Set(y, x, colors[label + 1]); //temp.Set(y, x, new Vec4b(127, 127, 127, 127)); ////if (0 <= label && label <= nccomps) ////{ //// temp.Set(y, x, colors[label]); ////} } } //foreach (var item in massPoints) //{ // if (double.IsNaN(item.Y) || double.IsNaN(item.X)) // { // continue; // } // temp.Set((int)item.Y, (int)item.X, new Vec4b(0, 0, 255, 255)); //} //Cv2.ImWrite("erzhi5.tif", temp); ////Cv2.ImShow("temp", temp); this.documentWorkspace.PhaseModels[2].mat = temp; this.documentWorkspace.Refresh(); return within + (double)nccompSelect.Count / 2; } /// /// 刷新晶粒编号 /// /// /// private void Getrains(List pointFs, RectangleF rectangleF) { Mat OriginalPicture; Mat analyzeMat = new Mat(); if (getGrainBoundryChecked()) { OriginalPicture = new Mat(matOrg.Size(), MatType.CV_8UC4, new Scalar(255, 255, 255, 255)); Mat oldMat = this.documentWorkspace.PhaseModels[1].mat; int Rows = oldMat.Rows; int Cols = oldMat.Cols; int[] point = new int[2]; //多通道图像的格式化 for (point[0] = 0; point[0] < Rows; point[0]++) { for (point[1] = 0; point[1] < Cols; point[1]++) { if (oldMat.At(point[0], point[1]).Item3 > 0) { OriginalPicture.Set(point, new Vec4b(0, 0, 0, 255)); } } } Cv2.Erode(OriginalPicture, OriginalPicture, null, null, 1); OriginalPicture.CopyTo(analyzeMat); } else if (getBinaryChecked()) { OriginalPicture = new Mat(matOrg.Size(), MatType.CV_8UC4, new Scalar(255, 255, 255, 255)); Mat oldMat = this.documentWorkspace.PhaseModels[0].mat; int Rows = oldMat.Rows; int Cols = oldMat.Cols; int[] point = new int[2]; //多通道图像的格式化 for (point[0] = 0; point[0] < Rows; point[0]++) { for (point[1] = 0; point[1] < Cols; point[1]++) { if (oldMat.At(point[0], point[1]).Item3 > 0) { OriginalPicture.Set(point, new Vec4b(0, 0, 0, 255)); } } } oldMat.CopyTo(analyzeMat); } else { OriginalPicture = new Mat(matOrg.Size(), MatType.CV_8UC4, new Scalar(255, 255, 255, 255)); matOrg.CopyTo(OriginalPicture); matOrg.CopyTo(analyzeMat); } Mat erzhi = OriginalPicture; Cv2.CvtColor(erzhi, erzhi, ColorConversionCodes.BGRA2GRAY); Cv2.Threshold(erzhi, erzhi, 100, 255, ThresholdTypes.Binary);//############# //Cv2.AdaptiveThreshold(erzhi, erzhi, 255, AdaptiveThresholdTypes.MeanC, ThresholdTypes.Binary, 99, 10); OpenCvSharp.Point[][] contours; HierarchyIndex[] hierarchy; Cv2.FindContours(erzhi, out contours, out hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxNone); List pointss = new List(); foreach (OpenCvSharp.Point[] contour in contours) { if (contour.Length < 100) { //foreach (OpenCvSharp.Point point in contour) //{ // erzhi.Set(point.Y, point.X, 255); //} pointss.Add(contour); } } Cv2.FillPoly(erzhi, pointss, new Scalar(255)); // 二次轮廓 Cv2.FindContours(erzhi, out contours, out hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxNone); // 计算所有轮廓质点 List massPoints = new List(); foreach (OpenCvSharp.Point[] contour in contours) { OpenCvSharp.Moments moments = new OpenCvSharp.Moments(contour, false); massPoints.Add(new Point2d(moments.M10 / moments.M00, moments.M01 / moments.M00)); } //Cv2.ImShow("erzhi", erzhi); Mat labelMat = new Mat(); Mat stats = new Mat(); Mat centroids = new Mat(); // 连通域数量 int nccomps = Cv2.ConnectedComponentsWithStats(erzhi, labelMat, stats, centroids, PixelConnectivity.Connectivity8); // 连通域质点 Dictionary keyValues = new Dictionary(); massLabelPoints.Clear(); foreach (var item in massPoints) { if (double.IsNaN(item.Y) || double.IsNaN(item.X)) { continue; } int label = labelMat.At((int)item.Y, (int)item.X); if (0 <= label && label <= nccomps) { keyValues[label] = item; } } Mat temp = new Mat(erzhi.Size(), MatType.CV_8UC4, new Scalar(0, 0, 0, 0));//#########to debug and test // 矩形边线上的连通域 ArrayList nccompSelect = new ArrayList(); foreach (var pointF in pointFs) { if (labelMat.Width <= pointF.X || labelMat.Height <= pointF.Y || pointF.X < 0 || pointF.Y < 0) { continue; } //判断是否在晶界上面 Vec4b vec4B = analyzeMat.At((int)pointF.Y, (int)pointF.X); if (getGrainBoundryChecked() && vec4B.Item0 == 0 || getBinaryChecked() && vec4B.Item3 != 0 || !getGrainBoundryChecked() && !getBinaryChecked() && vec4B.Item0 == 0) { //temp.Set((int)pointF.Y, (int)pointF.X, new Vec4b(0, 255, 0, 255)); continue;//0925###19106 } int label = labelMat.At((int)pointF.Y, (int)pointF.X); if (!nccompSelect.Contains(label) && keyValues.ContainsKey(label) && keyValues[label] != null) { nccompSelect.Add(label); if (keyValues.ContainsKey(label) && keyValues[label] != null) massLabelPoints.Add(keyValues[label]); // massLabelPoints.Add(new Point2d((int)pointF.X, (int)pointF.Y/*-1, -1*/)); //else // massLabelPoints.Add(new Point2d((int)pointF.Y, (int)pointF.Y/*-1, -1*/)); } else if (keyValues.ContainsKey(label) && keyValues[label] != null) { int iii = 1; } else if (!nccompSelect.Contains(label)) { int iiii = 1; nccompSelect.Add(label); massLabelPoints.Add(new Point2d((int)pointF.X, (int)pointF.Y/*-1, -1*/)); } else { int iiii = 1; } } // 矩形内的连通域 within = 0; ArrayList inccompSelect = new ArrayList(); GrainSizeGuideAreaMethodModel grainSizeGuideStyleModel = guideClass.GrainSizeGuideAreaMethodModel; // 圆形 if (grainSizeGuideStyleModel.circularGuideStyles != null) { foreach (var circularGuideStyle in grainSizeGuideStyleModel.circularGuideStyles) { if (this.getCurrentGuideName().Equals(circularGuideStyle.tag)) { foreach (var keyValue in keyValues) { //求点到圆心的距离 double c = BasicCalculationHelper.GetDistance(new PointF((float)keyValue.Value.X, (float)keyValue.Value.Y), new PointF(rectangleF.X + rectangleF.Width / 2, rectangleF.Y + rectangleF.Height / 2), 10); if (!nccompSelect.Contains(keyValue.Key) && c < guideClass.Mat_lineDiameter / 2) { if (!inccompSelect.Contains(keyValue.Key)) { within++; inccompSelect.Add(keyValue.Key); if (keyValue.Value != null) massLabelPoints.Add(keyValue.Value); } } } } } } // 矩形 if (grainSizeGuideStyleModel.rectangleGuideStyles != null) { foreach (var rectangleGuideStyle in grainSizeGuideStyleModel.rectangleGuideStyles) { if (this.getCurrentGuideName().Equals(rectangleGuideStyle.tag)) { foreach (var keyValue in keyValues) { if (!nccompSelect.Contains(keyValue.Key) && keyValue.Value.X > rectangleF.X && keyValue.Value.X < rectangleF.Right && keyValue.Value.Y > rectangleF.Y && keyValue.Value.Y < rectangleF.Bottom) { if (!inccompSelect.Contains(keyValue.Key)) { within++; inccompSelect.Add(keyValue.Key); if (keyValue.Value != null) massLabelPoints.Add(keyValue.Value); } } } } } } //Mat temp = new Mat(erzhi.Size(), MatType.CV_8UC4);//########### ////Mat temp = new Mat(erzhi.Size(), MatType.CV_8UC1); Random rd = new Random(); List colors = new List(nccomps); colors.Add(new Vec4b(0, 0, 0, 0)); for (int i = 0/*1*/; i < nccomps; i++) { //colors.Add(new Vec3b(255, 255, 255)); colors.Add(new Vec4b(((byte)(rd.Next() % 256)), ((byte)(rd.Next() % 256)), ((byte)(rd.Next() % 256)), 255)); } for (int y = 0; y < temp.Rows; y++) { for (int x = 0; x < temp.Cols; x++) { int label = labelMat.At(y, x); if (nccompSelect.Contains(label)) temp.Set(y, x, colors[label + 1]); if (inccompSelect.Contains(label)) temp.Set(y, x, colors[label + 1]); //temp.Set(y, x, new Vec4b(127, 127, 127, 127)); ////if (0 <= label && label <= nccomps) ////{ //// temp.Set(y, x, colors[label]); ////} } } //foreach (var item in massPoints) //{ // if (double.IsNaN(item.Y) || double.IsNaN(item.X)) // { // continue; // } // temp.Set((int)item.Y, (int)item.X, new Vec4b(0, 0, 255, 255)); //} ////Cv2.ImShow("temp", temp); this.documentWorkspace.PhaseModels[2].mat = temp; this.documentWorkspace.Refresh(); } /// /// 是否显示晶界 /// /// /// private void checkBox3_0_CheckedChanged(object sender, EventArgs e) { if (!showOrimat() && getGrainBoundryChecked() && checkBox3_0.Checked) { this.documentWorkspace.PhaseModels[1].choise = true; } else { this.documentWorkspace.PhaseModels[1].choise = false; } this.documentWorkspace.Refresh(); } private void checkBox4_0_CheckedChanged(object sender, EventArgs e) { this.documentWorkspace.Refresh(); } private void checkBox11_CheckedChanged(object sender, EventArgs e) { if (!showOrimat() && checkBox11.Checked) { this.documentWorkspace.PhaseModels[2].choise = true; } else { this.documentWorkspace.PhaseModels[2].choise = false; } this.documentWorkspace.Refresh(); } private void checkBox5_0_CheckedChanged(object sender, EventArgs e) { this.documentWorkspace.Refresh(); } } }