using OTSDataType; using OTSCommon.Model; using OTSMeasureApp; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using OTSIncAReportGrids.OTSIncAReportGridsFuncation; using System.Threading; using static OTSDataType.otsdataconst; using OTSPeriodicTable; using OpenCvSharp; using Point = System.Drawing.Point; using OTSIncAReportGraph.Controls; using OTSIncAReportGraph.OTSIncAReportGraphFuncation; using OTSCLRINTERFACE; using System.IO; using System.Reflection; using OTSModelSharp.ResourceManage; using System.Collections; using OTSIncAReportApp.SysMgrTools; using OTSIncAReportApp.DataOperation.DataAccess; using OTSModelSharp.DTLBase; using OTSRptPeriodicTable; using ExportToExcel; using ComboBoxItem = OTSMeasureApp.ComboBoxItem; namespace OTSIncAReportApp { public partial class frmReMeasure : Form { frmReportApp m_ReportApp; OTSImageDisHelp ReportFun; OTSReportGridsFun m_OTSIncAReportGridsFun; List SelectedParticles; List successParticles; Dictionary keyValuesMat; bool isCheck = true; bool stopFlag = false;//停止标识 Point handPoint; int partFunIndex = 0; int xrayScanMode = 0; int nBrukerDwellTime = 0; double ScanFieldSizeX = 0; double ScanFieldSizeX100 = 0; double ScanFieldSizeY100 = 0; double oldMag = 0; double old_pixelsize = 0; double new_pixelsize = 0; string sampleName = ""; int width = 0; int height = 0; OpenCvSharp.Size dsize; DataTable dt_new; //国际化 Language lan; Hashtable table; public static string ReportMgrParamFile = "\\Config\\SysData\\OTSReportMgrParam.rpf"; //报告对应使用的参数文件名 private delegate void DelSetPro(string txt, RichTextBox richTextBox);//设置进度条进度的委托方法 /// /// 设置进度。 /// /// /// private void SetProgressMessage(string txt, RichTextBox richTextBox) { //如果当前调用方不是创建控件的一方,则需要使用this.Invoke() //在这里,ProgressBar控件是由主线程创建的,所以子线程要对该控件进行操作 //必须执行this.InvokeRequired进行判断。 if (this.InvokeRequired) { DelSetPro setPro = new DelSetPro(SetProgressMessage); this.Invoke(setPro, new object[] { txt, richTextBox }); } else { WriteRictBox(txt); } } #region 将文本追加到RictBox的尾部上 /// /// 将文本追加到RictBox的尾部上 /// public void WriteRictBox(string in_str) { //追加到rictbox尾部 richTextBox_process.AppendText("[" + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ":" + DateTime.Now.Second.ToString() + "]" + in_str + Environment.NewLine); richTextBox_process.ScrollToCaret(); } #endregion public frmReMeasure(OTSImageDisHelp ReportFun, frmReportApp m_ReportApp) { InitializeComponent(); lan = new Language(this); table = lan.GetNameTable(this.Name); this.m_ReportApp = m_ReportApp; //初始化底层操作类 this.m_OTSIncAReportGridsFun = new OTSReportGridsFun(m_ReportApp); this.SelectedParticles = m_ReportApp.GetSelectedParticles(); this.ReportFun = ReportFun; //load the userdefine control dynamically System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Control_DrawDistrbutionImageAndBSE)); this.control_XRayTable1 = new Control_XRayTable(); this.control_XRayTable1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(180)))), ((int)(((byte)(255)))), ((int)(((byte)(255)))), ((int)(((byte)(255))))); this.control_XRayTable1.Dock = System.Windows.Forms.DockStyle.Fill; this.control_XRayTable1.GBInfoStr = ""; this.control_XRayTable1.GoodChineseName = ""; this.control_XRayTable1.MaterialName = ""; this.control_XRayTable1.List_ShowElementInfo = ((System.Collections.Generic.List)(resources.GetObject("control_XRayTable1.List_ShowElementInfo"))); this.control_XRayTable1.Name = "control_XRayTable1"; this.control_XRayTable1.ShowAnalysisXray = true; this.control_XRayTable1.ShowSearchXray = false; this.control_XRayTable1.Size = new System.Drawing.Size(groupBox2.Width, groupBox2.Height); this.control_XRayTable1.STDName = ""; this.control_XRayTable1.TabIndex = 16; this.groupBox2.Controls.Add(this.control_XRayTable1); ReadSuccessDb(); //显示已测颗粒 if (successParticles.Count != 0) { BindDataGridView(dataGridView_success, successParticles); } //显示待测颗粒 if (SelectedParticles.Count != 0) { BindDataGridView(dgV_ParticlesDevidePage, SelectedParticles); } //默认选中 foreach (DataGridViewRow dr in dgV_ParticlesDevidePage.Rows) { dr.Cells[0].Value = isCheck; } } /// /// 判断是否是二次测量颗粒 /// private void UpdateDB() { if (dgV_ParticlesDevidePage.Rows.Count == SelectedParticles.Count) { for (int i = 0; i < SelectedParticles.Count; i++) { if (dt_new.Select("FieldId = " + SelectedParticles[i].FieldId + " and ParticleId = " + SelectedParticles[i].ParticleId + "").Count() != 0) { dgV_ParticlesDevidePage.Rows[i].Cells["ReMeasure"].Value = "是"; } else { dgV_ParticlesDevidePage.Rows[i].Cells["ReMeasure"].Value = "否"; } } } for (int i = 0; i < dataGridView_success.Rows.Count; i++) { dataGridView_success.Rows[i].Cells["ReMeasure"].Value = "是"; } } /// /// 显示已测颗粒 /// private void ReadSuccessDb() { SQLiteHelper sQLiteHelper = new SQLiteHelper(ReportFun.resultFile.FilePath + "\\FIELD_FILES\\Inclusion.db"); if (!sQLiteHelper.IsExist("IncADataReMeasure")) { sQLiteHelper.ExecuteNonQuery("CREATE TABLE IncADataReMeasure AS SELECT * FROM IncAData where 1=0;"); } dt_new = sQLiteHelper.ExecuteDataTable("SELECT * FROM IncADataReMeasure"); successParticles = new List(); for (int i = 0; i < dt_new.Rows.Count; i++) { DataTable dt_xray = sQLiteHelper.ExecuteDataTable("SELECT XrayData FROM XRayData WHERE FieldId = " + dt_new.Rows[i]["FieldId"].ToString() + " AND XrayIndex = " + dt_new.Rows[i]["XrayId"].ToString() + ""); DataTable dt_Element = sQLiteHelper.ExecuteDataTable("SELECT * FROM ElementChemistry WHERE FieldId = " + dt_new.Rows[i]["FieldId"].ToString() + " AND XRayId = " + dt_new.Rows[i]["XrayId"].ToString() + ""); Particle particle = new Particle(); particle.FieldId = int.Parse(dt_new.Rows[i]["FieldId"].ToString()); particle.ParticleId = int.Parse(dt_new.Rows[i]["ParticleId"].ToString()); particle.AveGray = int.Parse(dt_new.Rows[i]["AveGray"].ToString()); particle.RectLeft = int.Parse(dt_new.Rows[i]["RectLeft"].ToString()); particle.RectTop = int.Parse(dt_new.Rows[i]["RectTop"].ToString()); particle.RectWidth = int.Parse(dt_new.Rows[i]["RectWidth"].ToString()); particle.RectHeight = int.Parse(dt_new.Rows[i]["RectHeight"].ToString()); particle.Area = double.Parse(dt_new.Rows[i]["Area"].ToString()); particle.PosX = int.Parse(dt_new.Rows[i]["PosX"].ToString()); particle.PosY = int.Parse(dt_new.Rows[i]["PosY"].ToString()); particle.TypeId = int.Parse(dt_new.Rows[i]["TypeId"].ToString()); particle.SegmentNum = int.Parse(dt_new.Rows[i]["SegmentNum"].ToString()); particle.SEMPosX = int.Parse(dt_new.Rows[i]["SEMPosX"].ToString()); particle.SEMPosY = int.Parse(dt_new.Rows[i]["SEMPosY"].ToString()); particle.XrayId = int.Parse(dt_new.Rows[i]["XrayId"].ToString()); particle.DMAX = double.Parse(dt_new.Rows[i]["DMAX"].ToString()); particle.DMIN = double.Parse(dt_new.Rows[i]["DMIN"].ToString()); particle.DPERP = double.Parse(dt_new.Rows[i]["DPERP"].ToString()); particle.PERIMETER = double.Parse(dt_new.Rows[i]["PERIMETER"].ToString()); particle.ORIENTATION = double.Parse(dt_new.Rows[i]["ORIENTATION"].ToString()); particle.DINSCR = double.Parse(dt_new.Rows[i]["DINSCR"].ToString()); particle.DMEAN = double.Parse(dt_new.Rows[i]["DMEAN"].ToString()); particle.DELONG = double.Parse(dt_new.Rows[i]["DELONG"].ToString()); particle.DFERET = double.Parse(dt_new.Rows[i]["DFERET"].ToString()); particle.TypeName = dt_new.Rows[i]["TypeName"].ToString(); particle.TypeColor = dt_new.Rows[i]["TypeColor"].ToString(); particle.XRayData = (Byte[])dt_xray.Rows[0][0]; particle.ElementList = new List(); particle.ElementNum = dt_Element.Rows.Count; for (int j = 0; j < dt_Element.Rows.Count; j++) { Element element = new Element(); element.FieldId = particle.FieldId; element.XrayId = particle.XrayId; element.Name = dt_Element.Rows[j]["Name"].ToString(); element.Percentage = double.Parse(dt_Element.Rows[j]["Percentage"].ToString()); element.ElementNum = particle.ElementNum; particle.ElementList.Add(element); } successParticles.Add(particle); } } private void BindDataGridView(DataGridView dgv, List particlesList) { dgv.Rows.Clear(); dgv.Columns.Clear(); //先建立个 CheckBox 栏 DataGridViewCheckBoxColumn cbCol = new DataGridViewCheckBoxColumn(); cbCol.Name = "dgv_check"; cbCol.Width = 50; //设定宽度 cbCol.HeaderText = "全选"; cbCol.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter; //置中 dgv.Columns.Insert(0, cbCol); //string startFun = ((Dictionary)((Dictionary)((Dictionary)ReportFun.resultFile.ResultInfo["Sample"])["Members"])["MsrParams"])["SysType"].ToString(); var startFun = m_ReportApp.m_RptConfigFile.Systype; //从报告xml文件中加载,显示计算列,显示元素信息 string str_DefaultComputedColName = ""; DataSet ds = OTSIncAReportApp.DataOperation.DataAccess.XMLoperate.GetXmlData(Application.StartupPath + ReportMgrParamFile, "XMLData"); DataTable dt = ds.Tables["Member"]; foreach (DataRow element in dt.Rows) { string RegName = element["RegName"].ToString(); if (RegName == "DefaultComputedColName") { str_DefaultComputedColName = element["strValue"].ToString(); } } //获取需要显示的计算列 string[] strs = str_DefaultComputedColName.Split(','); //列名 Dictionary keyValues = new Dictionary() { }; keyValues.Add("rowid", table["str1"].ToString()); keyValues.Add("ReMeasure", table["str19"].ToString()); keyValues.Add("TypeName", table["str20"].ToString()); keyValues.Add("FieldID", "FieldID"); keyValues.Add("particleid", "particleid"); keyValues.Add("SEMPosX", "SEMPosX"); keyValues.Add("SEMPosY", "SEMPosY"); for (int i = 0; i < strs.Count(); i++) { if (strs[i] == "Area") { keyValues.Add("Area", table["str21"].ToString()); } if (strs[i] == "EquivalentCircleDiameter") { keyValues.Add("Equivalent", table["str22"].ToString()); } if (strs[i] == "MaxDiameter") { keyValues.Add("DMAX", table["str23"].ToString()); } if (strs[i] == "MinDiameter") { keyValues.Add("DMIN", table["str24"].ToString()); } if (strs[i] == "DiameterRatio") { keyValues.Add("DiameterRatio", table["str25"].ToString()); } if (strs[i] == "FerretDiameter") { keyValues.Add("DFERET", table["str26"].ToString()); } if (strs[i] == "PERP") { keyValues.Add("DPERP", table["str27"].ToString()); } if (strs[i] == "PERI") { keyValues.Add("PERIMETER", table["str28"].ToString()); } if (strs[i] == "INSCR") { keyValues.Add("DINSCR", table["str29"].ToString()); } if (strs[i] == "MEAN") { keyValues.Add("DMEAN", table["str30"].ToString()); } if (strs[i] == "ELONG") { keyValues.Add("DELONG", table["str31"].ToString()); } if (strs[i] == "ASPECT_ELONG") { keyValues.Add("ASPECT_ELONG", table["str32"].ToString()); } if (strs[i] == "Orientation") { keyValues.Add("ORIENTATION", table["str33"].ToString()); } if (startFun == OTSCommon.Model.OTS_SysType_ID.CleannessA) { if (strs[i] == "Hardness") { keyValues.Add("Hardness", table["str36"].ToString()); } if (strs[i] == "Density") { keyValues.Add("Density", table["str35"].ToString()); } if (strs[i] == "Electrical_conductivity") { keyValues.Add("Electrical_conductivity", table["str34"].ToString()); } } } Dictionary.Enumerator en = keyValues.GetEnumerator(); for (int irow = 0; irow < keyValues.Count; irow++) { if (en.MoveNext()) { dgv.Columns.Add(en.Current.Key, en.Current.Value); } } DataTable particles = UpdateTable(particlesList); for (int i = 0; i < particles.Rows.Count; i++) { Dictionary.Enumerator enl = keyValues.GetEnumerator(); int add_rowindex = dgv.Rows.Add(); for (int k = 1; k < keyValues.Count; k++) { if (enl.MoveNext()) { if (enl.Current.Key == "rowid") { dgv.Rows[add_rowindex].Cells[k].Value = (i + 1); } if (enl.Current.Key == "DiameterRatio") { double d = Convert.ToDouble(particles.Rows[i]["DMAX"]) / Convert.ToDouble(particles.Rows[i]["DMIN"]); dgv.Rows[add_rowindex].Cells[k].Value = Math.Round(d, 2); } if (enl.Current.Key == "ASPECT_ELONG") { double d = Convert.ToDouble(particles.Rows[i]["DELONG"]) / Convert.ToDouble(particles.Rows[i]["DMEAN"]); dgv.Rows[add_rowindex].Cells[k].Value = Math.Round(d, 2); } if (particles.Columns.Contains(enl.Current.Key)) { double num = 0; if (double.TryParse(particles.Rows[i][enl.Current.Key].ToString(), out num)) { dgv.Rows[add_rowindex].Cells[k].Value = Math.Round(num, 2); } else { dgv.Rows[add_rowindex].Cells[k].Value = particles.Rows[i][enl.Current.Key]; } } if (enl.Current.Key == "TypeName") { if (particles.Rows[i]["TypeId"].ToString() == "9") { dgv.Rows[add_rowindex].Cells[k].Value = "Not Identified"; } } if (enl.Current.Key == "Equivalent") { double dSize = Convert.ToDouble(particles.Rows[i]["Area"]); double Diameter = Math.Sqrt(dSize / Math.PI) * 2; dgv.Rows[add_rowindex].Cells[k].Value = Math.Round(Diameter, 2); } } } } if (dgv.Name == "dataGridView_success") { dgv.Columns["dgv_check"].Visible = false; dgv.Columns["ReMeasure"].Visible = false; } UpdateDB(); } private DataTable UpdateTable(List particles) { List selectParticles = particles; DataTable dtUelect = new DataTable(); dtUelect.Columns.Add("fieldid"); dtUelect.Columns.Add("particleid"); dtUelect.Columns.Add("AveGray"); dtUelect.Columns.Add("RectLeft"); dtUelect.Columns.Add("RectTop"); dtUelect.Columns.Add("RectWidth"); dtUelect.Columns.Add("RectHeight"); dtUelect.Columns.Add("Area"); dtUelect.Columns.Add("PosX"); dtUelect.Columns.Add("PosY"); dtUelect.Columns.Add("TypeId"); dtUelect.Columns.Add("SegmentNum"); dtUelect.Columns.Add("SEMPosX"); dtUelect.Columns.Add("SEMPosY"); dtUelect.Columns.Add("XrayId"); dtUelect.Columns.Add("DMAX"); dtUelect.Columns.Add("DMIN"); dtUelect.Columns.Add("DPERP"); dtUelect.Columns.Add("PERIMETER"); dtUelect.Columns.Add("ORIENTATION"); dtUelect.Columns.Add("DINSCR"); dtUelect.Columns.Add("DMEAN"); dtUelect.Columns.Add("DELONG"); dtUelect.Columns.Add("DFERET"); dtUelect.Columns.Add("TypeName"); dtUelect.Columns.Add("TypeColor"); dtUelect.Columns.Add("SubParticles"); dtUelect.Columns.Add("Element"); dtUelect.Columns.Add("Hardness"); dtUelect.Columns.Add("Density"); dtUelect.Columns.Add("Electrical_conductivity"); for (int i = 0; i < selectParticles.Count; i++) { dtUelect.Rows.Add(selectParticles[i].FieldId, selectParticles[i].ParticleId, selectParticles[i].AveGray, selectParticles[i].RectLeft, selectParticles[i].RectTop, selectParticles[i].RectWidth, selectParticles[i].RectHeight, selectParticles[i].Area, selectParticles[i].PosX, selectParticles[i].PosX, selectParticles[i].TypeId, /*selectParticles[i].ElementNum,*/ selectParticles[i].SegmentNum, selectParticles[i].SEMPosX, selectParticles[i].SEMPosY, selectParticles[i].ParticleId, selectParticles[i].DMAX, selectParticles[i].DMIN, selectParticles[i].DPERP, selectParticles[i].PERIMETER, selectParticles[i].ORIENTATION, selectParticles[i].DINSCR, selectParticles[i].DMEAN, selectParticles[i].DELONG, selectParticles[i].DFERET, selectParticles[i].TypeName, selectParticles[i].TypeColor, "", "", "", "", ""); } string str_libraryName = ReportFun.resultFile.GetSTDName(); DataTable userLibraryData = new DataTable(); UserLibraryData userLibrary = new UserLibraryData(str_libraryName, ReportFun.resultFile.FilePath+"\\"); if (userLibrary.GetSqlHelper() != null) { userLibraryData = userLibrary.GetSubAttributeFromDatabase(); } else { userLibraryData = null; MessageBox.Show("未读取到用户标准库!"); } if (userLibraryData != null) { for (int i = 0; i < dtUelect.Rows.Count; i++) { DataRow[] dr = userLibraryData.Select("STDId=" + dtUelect.Rows[i]["TypeId"].ToString()); if (dr.Length > 0) { dtUelect.Rows[i]["Hardness"] = System.Text.RegularExpressions.Regex.Replace(dr[0]["Hardness"].ToString(), @"[^\d.\d]", ""); dtUelect.Rows[i]["Density"] = System.Text.RegularExpressions.Regex.Replace(dr[0]["Density"].ToString(), @"[^\d.\d]", ""); dtUelect.Rows[i]["Electrical_conductivity"] = System.Text.RegularExpressions.Regex.Replace(dr[0]["Electrical_conductivity"].ToString(), @"[^\d.\d]", ""); } else { dtUelect.Rows[i]["Hardness"] = ""; dtUelect.Rows[i]["Density"] = ""; dtUelect.Rows[i]["Electrical_conductivity"] = ""; } } } else { for (int i = 0; i < dtUelect.Rows.Count; i++) { dtUelect.Rows[i]["Hardness"] = ""; dtUelect.Rows[i]["Density"] = ""; dtUelect.Rows[i]["Electrical_conductivity"] = ""; } } ParticleData Particledata = new ParticleData(ReportFun.resultFile.FilePath); DataTable elementchemistry = Particledata.GetElementChemistry(); for (int i = 0; i < dtUelect.Rows.Count; i++) { string str = "XRayId = " + dtUelect.Rows[i]["particleId"].ToString() + " and fieldid = " + dtUelect.Rows[i]["fieldid"].ToString(); DataRow[] drs = elementchemistry.Select(str); string ConcatenatedString = ""; for (int j = 0; j < drs.Length; j++) { ConcatenatedString += drs[j]["name"] + "-" + drs[j]["Percentage"] + ';'; } dtUelect.Rows[i]["Element"] = ConcatenatedString; } return dtUelect; } private void frmReMeasure_Load(object sender, EventArgs e) { //图像扫描精度 IDC_COMBO_IMGSCANSPEED.Items.Clear(); foreach (otsdataconst.OTS_IMAGE_SCANSPEED_OPTIONS enum_one in Enum.GetValues(typeof(otsdataconst.OTS_IMAGE_SCANSPEED_OPTIONS))) { ComboBoxItem cbi = new ComboBoxItem(); cbi.Text = GetScanSpeedString(enum_one); cbi.Value = (int)enum_one; IDC_COMBO_IMGSCANSPEED.Items.Add(cbi); } IDC_COMBO_IMGSCANSPEED.SelectedIndex = (int)otsdataconst.OTS_IMAGE_SCANSPEED_OPTIONS.low; //X-Ray扫描方式 IDC_COMBO_XRAYSCANMODE.Items.Clear(); foreach (otsdataconst.OTS_X_RAY_SCAN_MODE enum_one in Enum.GetValues(typeof(otsdataconst.OTS_X_RAY_SCAN_MODE))) { ComboBoxItem cbi = new ComboBoxItem(); cbi.Text = GetXRayScanModeIdString(enum_one); cbi.Value = (int)enum_one; IDC_COMBO_XRAYSCANMODE.Items.Add(cbi); } IDC_COMBO_XRAYSCANMODE.SelectedIndex = (int)otsdataconst.OTS_X_RAY_SCAN_MODE.PointMode; ScanFieldSizeX = ReportFun.resultFile.GetScanFieldSizeX(); ScanFieldSizeX100 = ReportFun.resultFile.GetScanFieldSizeX100(); oldMag = Math.Round((ScanFieldSizeX100 / ScanFieldSizeX) * 100, 2); width = ReportFun.resultFile.GetImageWidth(); height = ReportFun.resultFile.GetImageHeight(); old_pixelsize = ScanFieldSizeX / width; ScanFieldSizeY100 = height * old_pixelsize; //颗粒方法 CB_partFun.SelectedIndex = 0; control_XRayTable1.Visible = false; } private void showXrayChart(Particle particle) { if (particle.XRayData == null) { control_XRayTable1.Visible = false; return; } //显示xray相关信息 uint[] Search_xray = new uint[2000]; uint[] Analysis_xray = new uint[2000]; //获取Xray数据 for (int i = 0; i < 2000; i++) { Analysis_xray[i] = BitConverter.ToUInt32(particle.XRayData, i * 4); } Search_xray = Analysis_xray; //get CElementChemistryClr list List list_showelementinfo = new List(); for (int i = 0; i < particle.ElementList.Count; i++) { ShowElementInfo ls_sei = new ShowElementInfo(); ls_sei.ElementName = particle.ElementList[i].Name; ls_sei.Percentage = particle.ElementList[i].Percentage; ls_sei.dKF = Convert.ToDouble(CListPeriodic.GetPeriodicByEleName(ls_sei.ElementName).K_Peak); double de_K_Peak = 0; if (CListPeriodic.GetPeriodicByEleName(ls_sei.ElementName).K_Peak == "" || CListPeriodic.GetPeriodicByEleName(ls_sei.ElementName).K_Peak == "-") { de_K_Peak = 0; } else { de_K_Peak = Convert.ToDouble(CListPeriodic.GetPeriodicByEleName(ls_sei.ElementName).K_Peak); } ls_sei.dLF = de_K_Peak; list_showelementinfo.Add(ls_sei); } //获取数据后,需要对xraytable设置 control_XRayTable1.Visible = false; control_XRayTable1.SetXRayShowLineValue(Search_xray, Analysis_xray, list_showelementinfo); //颗粒国标信息 control_XRayTable1.GBInfoStr = ""; control_XRayTable1.MaterialName = particle.TypeName;//名称 control_XRayTable1.List_ShowElementInfo = list_showelementinfo; control_XRayTable1.Visible = true; this.Refresh(); } public string GetScanSpeedString(otsdataconst.OTS_IMAGE_SCANSPEED_OPTIONS a_nScanSpeed) { string strScanSpeedId = ""; if (a_nScanSpeed >= otsdataconst.OTS_IMAGE_SCANSPEED_OPTIONS.low && a_nScanSpeed <= otsdataconst.OTS_IMAGE_SCANSPEED_OPTIONS.high) { strScanSpeedId = XmlResourceData.GetInstance().GetStringByKey(ResourceID.GrpOtherParam, ResourceID.IDS_SCANSPEED + (int)a_nScanSpeed); } return strScanSpeedId; } public static string GetXRayScanModeIdString(otsdataconst.OTS_X_RAY_SCAN_MODE a_nXRayScanMode) { string strXRayScanModeId = ""; if (a_nXRayScanMode >= otsdataconst.OTS_X_RAY_SCAN_MODE.PointMode && a_nXRayScanMode <= otsdataconst.OTS_X_RAY_SCAN_MODE.FeatureMode) { strXRayScanModeId = XmlResourceData.GetInstance().GetStringByKey(ResourceID.GrpOtherParam, ResourceID.IDS_XRAYSCANMODE + (int)a_nXRayScanMode); } return strXRayScanModeId; } private void BTN_NO_Click(object sender, EventArgs e) { stopFlag = true; } private void BTN_YES_Click(object sender, EventArgs e) { //参数定义 int nBrukerDwellTimeId = 3; switch (IDC_COMBO_IMGSCANSPEED.SelectedIndex) { case (int)OTS_IMAGE_SCANSPEED_OPTIONS.low: nBrukerDwellTimeId = 3; break; case (int)OTS_IMAGE_SCANSPEED_OPTIONS.meddium: nBrukerDwellTimeId = 4; break; case (int)OTS_IMAGE_SCANSPEED_OPTIONS.high: nBrukerDwellTimeId = 5; break; default: nBrukerDwellTimeId = 3; break; } nBrukerDwellTime = DWELLTIME_BRUKER_VALUES[nBrukerDwellTimeId]; tabControl_grid.SelectedIndex = 0; tabControl_grid.Enabled = false; groupBox_param.Enabled = false; partFunIndex = CB_partFun.SelectedIndex; xrayScanMode = IDC_COMBO_XRAYSCANMODE.SelectedIndex; bgw_process.RunWorkerAsync(); } private void bgw_process_DoWork(object sender, DoWorkEventArgs e) { //第一步,连接电镜 if (!m_OTSIncAReportGridsFun.Connection_ForParticlesGrid()) { SetProgressMessage(table["str2"].ToString(), richTextBox_process); return; } Thread.Sleep(500); keyValuesMat = new Dictionary(); for (int i = 0; i < SelectedParticles.Count; i++) { if (!(bool)dgV_ParticlesDevidePage.Rows[i].Cells[0].Value) { MessageBox.Show(i.ToString()); continue; } if (stopFlag) { MessageBox.Show(table["str3"].ToString()); return; } if (m_OTSIncAReportGridsFun.m_SEMConnectionState == true) { dgV_ParticlesDevidePage.Rows[i].DefaultCellStyle.BackColor = Color.Blue; SetProgressMessage(table["str4"].ToString() + (i + 1), richTextBox_process); double new_ScanFieldSize_width = (SelectedParticles[i].RectWidth + (double)NUD_Outspread.Value) * old_pixelsize; double new_ScanFieldSize_height = (SelectedParticles[i].RectHeight + (double)NUD_Outspread.Value) * old_pixelsize; double mag_width = Math.Round((ScanFieldSizeX100 / new_ScanFieldSize_width) * 100, 2); double mag_height = Math.Round((ScanFieldSizeY100 / new_ScanFieldSize_height) * 100, 2); double final_mag = mag_width > mag_height ? mag_height : mag_width; new_pixelsize = new_ScanFieldSize_width / width; SetProgressMessage(table["str5"].ToString() + final_mag, richTextBox_process); if (!m_OTSIncAReportGridsFun.SetMagnification(final_mag)) { SetProgressMessage(table["str6"].ToString(), richTextBox_process); return; } Point point = Control_DrawDistrbutionImageAndBSE.CalculateParticleCenterPosition(ReportFun.resultFile, new Point(SelectedParticles[i].SEMPosX, SelectedParticles[i].SEMPosY), new Point(SelectedParticles[i].PosX, SelectedParticles[i].PosY)); SetProgressMessage(table["str7"].ToString() + point.X + "," + point.Y, richTextBox_process); if (!m_OTSIncAReportGridsFun.MoveSemToPointXY_ForParticlesGrid(point.X, point.Y)) { SetProgressMessage(table["str8"].ToString(), richTextBox_process); return; } SetProgressMessage(table["str9"].ToString(), richTextBox_process); byte[] ImageByte = new byte[width * height]; if (!m_OTSIncAReportGridsFun.AcquireBSEImage(sampleName, width, height, nBrukerDwellTime, ref ImageByte)) { SetProgressMessage(table["str10"].ToString(), richTextBox_process); return; } SetProgressMessage(table["str11"].ToString(), richTextBox_process); //Mat mat = new Mat(@"F:\汽车清洁度\20220325\2\Sample1\FIELD_FILES\Field" + i + ".bmp", ImreadModes.Grayscale); //Mat mat = new Mat(resultFile.FilePath + "\\" + savePathName + "\\" + SelectedParticles[i].FieldId + "_" + SelectedParticles[i].ParticleId + ".bmp", ImreadModes.Grayscale); Mat mat = new Mat(height, width, MatType.CV_8UC1, ImageByte); Particle particle_new = (Particle)ReportFun.CloneObject(SelectedParticles[i]); particle_new.XrayId = SelectedParticles[i].XrayId + 10000; if (!FindNewPartInfo(ref mat, particle_new)) { SetProgressMessage(table["str12"].ToString(), richTextBox_process); return; } SetProgressMessage(table["str13"].ToString(), richTextBox_process); if (!m_OTSIncAReportGridsFun.AcquisitionSpectrum(ReportFun.resultFile.FilePath + "\\FIELD_FILES\\", xrayScanMode, new_pixelsize, ref particle_new, (uint)NUD_SCANTIME.Value)) { SetProgressMessage(table["str14"].ToString(), richTextBox_process); return; } showXrayChart(particle_new);//显示Xray图 SaveXray(particle_new.FieldId + "_" + particle_new.ParticleId + ".bmp");//保存图谱图 keyValuesMat.Add(i, mat); bgw_process.ReportProgress(0, OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat)); SetProgressMessage(table["str16"].ToString() + (i + 1), richTextBox_process); dgV_ParticlesDevidePage.Rows[i].DefaultCellStyle.BackColor = Color.Green; SelectedParticles[i] = particle_new; } } ReadSuccessDb(); BindDataGridView(dataGridView_success, successParticles); BindDataGridView(dgV_ParticlesDevidePage, SelectedParticles); Thread.Sleep(500); SetProgressMessage(table["str17"].ToString(), richTextBox_process); } private void bgw_process_ProgressChanged(object sender, ProgressChangedEventArgs e) { switch (e.ProgressPercentage) { case 0: pictureBox_part.Image = (Bitmap)e.UserState; break; default: break; } } private bool SaveImg(string imgName, Mat mat) { if (!Directory.Exists(ReportFun.resultFile.FilePath + "\\" + m_ReportApp.savePathName)) { Directory.CreateDirectory(ReportFun.resultFile.FilePath + "\\" + m_ReportApp.savePathName); } if (!Directory.Exists(ReportFun.resultFile.FilePath + "\\" + m_ReportApp.savePathName + "\\image")) { Directory.CreateDirectory(ReportFun.resultFile.FilePath + "\\" + m_ReportApp.savePathName + "\\image"); } Cv2.ImWrite(ReportFun.resultFile.FilePath + "\\" + m_ReportApp.savePathName + "\\image\\" + imgName, mat); return true; } private bool SaveXray(string imgName) { if (!Directory.Exists(ReportFun.resultFile.FilePath + "\\" + m_ReportApp.savePathName)) { Directory.CreateDirectory(ReportFun.resultFile.FilePath + "\\" + m_ReportApp.savePathName); } if (!Directory.Exists(ReportFun.resultFile.FilePath + "\\" + m_ReportApp.savePathName + "\\xray")) { Directory.CreateDirectory(ReportFun.resultFile.FilePath + "\\" + m_ReportApp.savePathName + "\\xray"); } using (Bitmap bmp = new Bitmap(control_XRayTable1.Width, control_XRayTable1.Height)) { control_XRayTable1.DrawToBitmap(bmp, control_XRayTable1.ClientRectangle); bmp.Save(ReportFun.resultFile.FilePath + "\\" + m_ReportApp.savePathName + "\\xray\\" + imgName); } return true; } /// /// 颗粒处理核心方法 /// /// /// /// private bool FindNewPartInfo(ref Mat mat, Particle particle_new) { try { using (Mat mat_dst = new Mat()) { Dictionary keyValuePairs = new Dictionary(); switch (partFunIndex) { case 0: Cv2.Threshold(mat, mat_dst, 0, 255, ThresholdTypes.Triangle);break; case 1: Cv2.Threshold(mat, mat_dst, 0, 255, ThresholdTypes.Otsu);break; } Mat labelMat = new Mat(); Mat stats = new Mat();//点的信息 Mat centroids = new Mat();//质心的信息 int nonenum = Cv2.ConnectedComponentsWithStats(mat_dst, labelMat, stats, centroids, PixelConnectivity.Connectivity8); for (int h = 1; h < centroids.Height; h++) { int areaField = stats.At(h, 4); keyValuePairs.Add(h, areaField); } int Key = 0;//新颗粒序列 if (CB_HAND.Checked)//手动处理 { Mat srcWhite = new Mat(mat_dst.Height, mat_dst.Width, MatType.CV_8UC1, new Scalar(0));//黑色底图 mat.CopyTo(srcWhite, mat_dst); bgw_process.ReportProgress(0, OpenCvSharp.Extensions.BitmapConverter.ToBitmap(srcWhite)); SetProgressMessage(table["str18"].ToString(), richTextBox_process); GetKeyNo(labelMat, mat_dst.Width, mat_dst.Height, ref Key); } else//自动处理 { keyValuePairs = keyValuePairs.OrderByDescending(a => a.Value).ToDictionary(a => a.Key, b => b.Value); Dictionary dsList = new Dictionary(); for (int i = 0; i < keyValuePairs.Count; i++) { dsList.Add(keyValuePairs.ElementAt(i).Key, Math.Abs(keyValuePairs.ElementAt(i).Value * new_pixelsize * new_pixelsize - particle_new.Area)); } dsList = dsList.OrderBy(a => a.Value).ToDictionary(a => a.Key, b => b.Value); Key = dsList.ElementAt(0).Key; } Cv2.CvtColor(mat_dst, mat_dst, ColorConversionCodes.RGB2BGR); OpenCvSharp.Point centroidsPoint = new OpenCvSharp.Point((int)centroids.At(Key, 0), (int)centroids.At(Key, 1)); Rect rect = new Rect(stats.At(Key, 0), stats.At(Key, 1), stats.At(Key, 2), stats.At(Key, 3)); Cv2.Circle(mat_dst, centroidsPoint, 5, Scalar.Green, -1); Cv2.Rectangle(mat_dst, rect, Scalar.Red); bgw_process.ReportProgress(0, OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat_dst)); //保存局部高清图片 mat = new Mat(mat, rect); if (mat.Width > mat.Height) { dsize = new OpenCvSharp.Size(100, 100 * mat.Height / mat.Width); } else { dsize = new OpenCvSharp.Size(100 * mat.Width / mat.Height, 100); } Cv2.Resize(mat, mat, dsize, 0, 0, InterpolationFlags.Cubic); //保存高清图 SaveImg(particle_new.FieldId + "_" + particle_new.ParticleId + ".bmp", mat); //取各个轮廓内的像素 List points = new List(); for (int k = 0; k < labelMat.Height; k++) { for (int j = 0; j < labelMat.Width; j++) { int no = labelMat.Get(k, j); if (Key == no) { points.Add(new Point(j, k)); } } } //保存颗粒信息 particle_new.PosX = centroidsPoint.X; particle_new.PosY = centroidsPoint.Y; particle_new.RectLeft = stats.At(Key, 0); particle_new.RectTop = stats.At(Key, 1); particle_new.RectWidth = stats.At(Key, 2); particle_new.RectHeight = stats.At(Key, 3); List SegmentClrList1 = new List(); List SegmentList1 = new List(); ReportFun.GetSegment(points, particle_new, SegmentClrList1, ref SegmentList1); particle_new.SegmentList = SegmentList1; particle_new.SegmentNum = SegmentList1.Count; } } catch (Exception ex) { SetProgressMessage(ex.ToString(), richTextBox_process); return false; } return true; } private void bgw_process_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { stopFlag = false; tabControl_grid.Enabled = true; groupBox_param.Enabled = true; } private void pictureBox_part_MouseDown(object sender, MouseEventArgs e) { if (CB_HAND.Checked && pictureBox_part.Image != null) { int originalWidth = this.pictureBox_part.Image.Width; int originalHeight = this.pictureBox_part.Image.Height; PropertyInfo rectangleProperty = this.pictureBox_part.GetType().GetProperty("ImageRectangle", BindingFlags.Instance | BindingFlags.NonPublic); Rectangle rectangle = (Rectangle)rectangleProperty.GetValue(this.pictureBox_part, null); int currentWidth = rectangle.Width; int currentHeight = rectangle.Height; double rate = (double)currentHeight / (double)originalHeight; int black_left_width = (currentWidth == this.pictureBox_part.Width) ? 0 : (this.pictureBox_part.Width - currentWidth) / 2; int black_top_height = (currentHeight == this.pictureBox_part.Height) ? 0 : (this.pictureBox_part.Height - currentHeight) / 2; int zoom_x = e.X - black_left_width; int zoom_y = e.Y - black_top_height; double original_x = (double)zoom_x / rate; double original_y = (double)zoom_y / rate; //StringBuilder sb = new StringBuilder(); //sb.AppendFormat("原始尺寸{0}/{1}(宽/高)\r\n", originalWidth, originalHeight); //sb.AppendFormat("缩放状态图片尺寸{0}/{1}(宽/高)\r\n", currentWidth, currentHeight); //sb.AppendFormat("缩放比率{0}\r\n", rate); //sb.AppendFormat("左留白宽度{0}\r\n", black_left_width); //sb.AppendFormat("上留白高度{0}\r\n", black_top_height); //sb.AppendFormat("当前鼠标坐标{0}/{1}(X/Y)\r\n", e.X, e.Y); //sb.AppendFormat("缩放图中鼠标坐标{0}/{1}(X/Y)\r\n", zoom_x, zoom_y); //sb.AppendFormat("原始图中鼠标坐标{0}/{1}(X/Y)\r\n", original_x, original_y); handPoint = new Point((int)original_x, (int)original_y); } } /// ///获取手动处理序号 /// /// /// /// /// private void GetKeyNo(Mat labelMat, int width, int height, ref int key) { handPoint = new Point(-1, -1); Color color = groupBox_img.BackColor; while (key == 0 && stopFlag == false) { groupBox_img.BackColor = Color.Red; Thread.Sleep(1000); if (handPoint.X >= 0 && handPoint.X < width && handPoint.Y >= 0 && handPoint.Y < height) { key = labelMat.Get((int)handPoint.Y, (int)handPoint.X); } } groupBox_img.BackColor = color; } private void dgV_ParticlesDevidePage_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.ColumnIndex == 0) { foreach (DataGridViewRow dr in dgV_ParticlesDevidePage.Rows) { dr.Cells[0].Value = !isCheck; } isCheck = !isCheck; } } private void dgV_ParticlesDevidePage_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.ColumnIndex == 0 && e.RowIndex != -1) { if ((bool)dgV_ParticlesDevidePage.Rows[e.RowIndex].Cells[e.ColumnIndex].Value) { dgV_ParticlesDevidePage.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = false; } else { dgV_ParticlesDevidePage.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = true; } } if (e.RowIndex != -1) { string imagePath = ReportFun.resultFile.FilePath + "\\" + m_ReportApp.savePathName + "\\image\\" + dgV_ParticlesDevidePage.Rows[e.RowIndex].Cells["FieldID"].Value + "_" + dgV_ParticlesDevidePage.Rows[e.RowIndex].Cells["particleid"].Value + ".bmp"; if (File.Exists(imagePath)) { pictureBox_part.Image = new Bitmap(imagePath); } else { pictureBox_part.Image = null; } showXrayChart(SelectedParticles[e.RowIndex]);//显示Xray图 } } private void dataGridView_success_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex != -1) { string imagePath = ReportFun.resultFile.FilePath + "\\" + m_ReportApp.savePathName + "\\image\\" + dataGridView_success.Rows[e.RowIndex].Cells["FieldID"].Value + "_" + dataGridView_success.Rows[e.RowIndex].Cells["particleid"].Value + ".bmp"; if (File.Exists(imagePath)) { pictureBox_part.Image = new Bitmap(imagePath); } else { pictureBox_part.Image = null; } showXrayChart(successParticles[e.RowIndex]);//显示Xray图 } } private void BTN_EXPORT_Click(object sender, EventArgs e) { ExportDgvToExcel export = new ExportDgvToExcel(); SetState(false); string imagePath = ReportFun.resultFile.FilePath + "\\" + m_ReportApp.savePathName; export.ExportExcel(imagePath, dataGridView_success, "宋体", 11);//默认文件名,DataGridView控件的名称,字体,字号 SetState(true); MessageBox.Show(table["str37"].ToString(), table["str38"].ToString(), MessageBoxButtons.OK, MessageBoxIcon.Information); } private void SetState(bool isTrue) { dataGridView_success.Columns["FieldID"].Visible = isTrue; dataGridView_success.Columns["particleid"].Visible = isTrue; dataGridView_success.Columns["SEMPosX"].Visible = isTrue; dataGridView_success.Columns["SEMPosY"].Visible = isTrue; } } }