革博士V2程序
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

3090 строки
144 KiB

  1. using CCWin.SkinControl;
  2. using ClosedXML.Excel;
  3. using DocumentFormat.OpenXml.EMMA;
  4. using DocumentFormat.OpenXml.Office2010.ExcelAc;
  5. using DocumentFormat.OpenXml.Office2019.Excel.RichData;
  6. using DocumentFormat.OpenXml.Office2021.DocumentTasks;
  7. using GeBoShi.SysCtrl;
  8. using GeBoShi.UI;
  9. using GeBoShi.UI.DataQuery;
  10. using GeBoShi.UI.InageShow;
  11. using GeBoShi.UI.Load;
  12. using GeBoShi.UI.Product;
  13. using GeBoShi.UI.SysSet;
  14. using HalconDotNet;
  15. using HZH_Controls;
  16. using HZH_Controls.Controls;
  17. using HZH_Controls.Forms;
  18. using ImageToolKits;
  19. using MaiMuControl;
  20. using MaiMuControl.Device;
  21. using MaiMuControl.Device.CamDev;
  22. using Models;
  23. using Newtonsoft.Json.Linq;
  24. using OpenCvSharp;
  25. using OpenCvSharp.Extensions;
  26. using PG_Detect;
  27. using Service;
  28. using SqlSugar;
  29. using System;
  30. using System.Collections;
  31. using System.Collections.Generic;
  32. using System.ComponentModel;
  33. using System.Data;
  34. using System.Diagnostics;
  35. using System.Drawing;
  36. using System.IO;
  37. using System.IO.Ports;
  38. using System.Linq;
  39. using System.Linq.Expressions;
  40. using System.Runtime.InteropServices;
  41. using System.Text;
  42. using System.Threading;
  43. using System.Threading.Tasks;
  44. using System.Web.UI.WebControls.WebParts;
  45. using System.Windows.Forms;
  46. using System.Windows.Forms.DataVisualization.Charting;
  47. namespace GeBoShi
  48. {
  49. public partial class Main : Form
  50. {
  51. [DllImport("user32.dll ", EntryPoint = "SetParent")]
  52. private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); //将外部窗体嵌入程序
  53. [DllImport("user32.dll")]
  54. public static extern IntPtr FindWindow(string lpszClass, string lpszWindow); //按照窗体类名或窗体标题查找窗体
  55. object AddTextLock = new object();
  56. bool backgroundWorkerDo;
  57. private Stopwatch RunStartTime = new Stopwatch();
  58. /// <summary>
  59. /// 显示颜色现在对应30色,确保label在30个以内
  60. /// </summary>
  61. Color[] ChartColor = new Color[30] { Color.Red, Color.Blue, Color.Green, Color.YellowGreen, Color.Orange,
  62. Color.Peru, Color.DarkRed,Color.GreenYellow, Color.Pink , Color.Brown,
  63. Color.CadetBlue, Color.OrangeRed, Color.Cyan, Color.Lime, Color.Magenta, Color.Tan, Color.Sienna,
  64. Color.DarkGray, Color.SaddleBrown, Color.DarkBlue, Color.Firebrick,Color.Gainsboro,Color.Honeydew,Color.Khaki,Color.Lavender,
  65. Color.LightGoldenrodYellow,Color.Navy, Color.Khaki, Color.IndianRed,Color.Lavender};
  66. Process process = null;
  67. IntPtr appWin;
  68. public Main()
  69. {
  70. InitializeComponent();
  71. UIStyle.SetUIStyle(this);
  72. this.uiTitel1.FatherForm = this;
  73. //this.uiTitel1.UserMenuStrip = this.menuStrip1;
  74. this.uiTitel1.ShowContrlBox(true, true, true);
  75. this.uiTitel1.ShowMenu();
  76. this.DoubleBuffered = true;//设置本窗体
  77. SetStyle(ControlStyles.UserPaint, true);
  78. SetStyle(ControlStyles.AllPaintingInWmPaint, true); // 禁止擦除背景.
  79. SetStyle(ControlStyles.DoubleBuffer, true); // 双缓冲
  80. SysMgr.Instance.MainRuning += main_running;
  81. SysMgr.Instance.AutoRuning += auto_runing;
  82. #region 缺陷列表dataGridView设置
  83. skinDataGridView1.AllowUserToAddRows = skinDataGridView1.AllowUserToDeleteRows = false;//用户添加删除行
  84. skinDataGridView1.AllowUserToResizeRows = false;//用户调整行大小 //显示行号与列宽度自动调整
  85. skinDataGridView1.RowHeadersVisible = true;
  86. skinDataGridView1.RowHeadersWidth = 50;
  87. //dataGridView1.ColumnHeadersHeightSizeMode = dataGridView2.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
  88. skinDataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;//数据量过百绑定太变
  89. skinDataGridView1.RowTemplate.Height = 30;
  90. //skinDataGridView1.RowPostPaint += (sender, e) =>//序号列头
  91. //{
  92. // showRowNum_onDataGrid_RowPostPaint(this.skinDataGridView1, sender, e);
  93. //};
  94. for (int i = 0; i < skinDataGridView1.Columns.Count; i++)//禁止点击列头排序
  95. skinDataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
  96. this.skinDataGridView1.CellClick += skinDataGridView1_CellClick; ;
  97. #endregion
  98. #region 标准列表dataGridView设置
  99. dataGridView2.AutoGenerateColumns = false;//自动创建列
  100. dataGridView2.AllowUserToAddRows = dataGridView1.AllowUserToDeleteRows = false;//用户添加删除行
  101. //dataGridView2.AllowUserToResizeRows = true;//用户调整行大小
  102. // //dataGridView1.AllowUserToResizeColumns = false;//用户调整列大小
  103. // //显示行号与列宽度自动调整
  104. //dataGridView2.RowHeadersVisible = true;
  105. //dataGridView2.RowHeadersWidth = 62;
  106. //dataGridView2.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;//数据量过百绑定太变
  107. //dataGridView2.RowPostPaint += (sender, e) =>//序号列头
  108. //{
  109. // SysMgr.showRowNum_onDataGrid_RowPostPaint(this.dataGridView2, sender, e);
  110. //};
  111. //dataGridView2.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
  112. panel_jcbz.Visible = false;
  113. panel_jcbz.Location = new System.Drawing.Point(0, 0);
  114. panel_jcbz.Dock = DockStyle.Fill;
  115. #endregion
  116. //设置图标大小
  117. this.lineChartDefect.Size = new System.Drawing.Size(600, 800);
  118. this.lineChartFaceWidth.Size = new System.Drawing.Size(1000, 300);
  119. #region 数据查询dataGridView设置
  120. uiDataGridView1.AutoGenerateColumns = false;//自动创建列
  121. uiDataGridView1.AllowUserToAddRows = uiDataGridView1.AllowUserToDeleteRows = false;//用户添加删除行
  122. uiDataGridView1.AllowUserToResizeRows = true;//用户调整行大小
  123. uiDataGridView1.AllowUserToResizeColumns = false;//用户调整列大小
  124. uiDataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;//只可选中整行,不是单元格
  125. //显示行号与列宽度自动调整
  126. uiDataGridView1.RowHeadersVisible = true;
  127. uiDataGridView1.RowHeadersWidth = 30;
  128. uiDataGridView1.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;//数据量过百绑定太变
  129. uiDataGridView1.RowPostPaint += (sender, e) =>//序号列头
  130. {
  131. SysMgr.showRowNum_onDataGrid_RowPostPaint(this.uiDataGridView1, sender, e);
  132. };
  133. uiDataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
  134. //for (int i = 0; i < dataGridView1.Columns.Count; i++)//禁止点击列头排序
  135. // uiDataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
  136. //行列交叉处标题
  137. //if (uiDataGridView1.RowHeadersVisible) uiDataGridView1.TopLeftHeaderCell.Value = "SPH/CYL";
  138. //事件
  139. this.uiDataGridView1.DataBindingComplete += this.uiDataGridView1_DataBindingComplete;//bing data时发生,可修改单元格内容
  140. //this.uiDataGridView1.SelectIndexChange += uiDataGridView1_SelectIndexChange;//选择行时发行
  141. //this.uiDataGridView1.CellClick += UiDataGridView1_CellClick;
  142. #endregion
  143. //this.lblDefectLen.Top = toolStrip1.Top + 10;
  144. //this.lblDefectLen.Left = toolStrip1.Width - 300;
  145. //this.lblDefectSpeed.Top = toolStrip1.Top + 10 + lblDefectLen.Height + 5;
  146. //this.lblDefectSpeed.Left = toolStrip1.Width - 300;
  147. this.lbFK.Text = "当前幅宽:";
  148. this.skinTabControl1.SelectedIndex = 0;
  149. }
  150. #region 初始化
  151. /// <summary>
  152. /// 初始化
  153. /// </summary>
  154. /// <returns></returns>
  155. private bool InitSystem()
  156. {
  157. //进入初始化,初始化失败则中断
  158. InitFrm initFrm = new InitFrm();
  159. initFrm.ShowDialog();
  160. if (initFrm.DialogResult == DialogResult.OK)
  161. {
  162. //初始化成功
  163. }
  164. else
  165. {
  166. initFrm.Dispose();
  167. return false;
  168. }
  169. initFrm.Dispose();
  170. return true;
  171. }
  172. #endregion
  173. #region 界面刷新
  174. private void showRowNum_onDataGrid_RowPostPaint(DataGridView dgv, object sender, DataGridViewRowPostPaintEventArgs e)
  175. {
  176. Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgv.RowHeadersWidth - 4, e.RowBounds.Height);
  177. TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dgv.RowHeadersDefaultCellStyle.Font, rectangle, dgv.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
  178. }
  179. private void ResetUI(bool clearSN)
  180. {
  181. //保持产品名称和料号
  182. //txtProductName.Text = txtProductCode.Text = txtProductSN.Text = "";
  183. if (clearSN)
  184. cbPdtSN.Text = "";
  185. //this.lstLog.Items.Clear();
  186. this.tsbtnImpStop.Enabled = false;
  187. this.tsbtnStart.Enabled = true;
  188. this.tsbtnStop.Enabled = false;
  189. this.cbPdtSN.Enabled = true;
  190. this.cbPdtColor.Enabled = true;
  191. this.numPdtLength.Enabled = true;
  192. this.pictureBox1.Image = null;
  193. pictureBox1.Refresh();
  194. tslabelTime.Text = "实时测试队列";
  195. skinDataGridView1.DataSource = null;
  196. this.skinDataGridView1.Rows.Clear();
  197. ResetChart();
  198. lblDefectLen.Text = $"检测长度: 0 米";
  199. lblDefectSpeed.Text = $"检测速度: 0 米/分钟";
  200. ucSwitch1.Checked = SysMgr.Instance.GetDefectPause();
  201. ucSwitch2.Checked = SysMgr.Instance.GetDefectDB();
  202. this.Refresh();
  203. }
  204. void ResetChart()
  205. {
  206. chart1.Series.Clear();
  207. chart1.Series.Add("SELECT");
  208. chart1.Series["SELECT"].ChartType = SeriesChartType.Point;
  209. chart1.Series["SELECT"].MarkerSize = 25;
  210. chart1.Series["SELECT"].MarkerColor = Color.Black;
  211. chart1.Series["SELECT"].MarkerStyle = MarkerStyle.Star6;
  212. //chart1.Series["SELECT"].Enabled = false;
  213. chart1.ChartAreas[0].AxisX.Title = "宽度(cm)";
  214. chart1.ChartAreas[0].AxisY.Title = "长度(m)";
  215. chart3.Series.Clear();
  216. chart3.Series.Add("面宽");
  217. chart3.ChartAreas[0].AxisX.Title = "长度(m)";
  218. chart3.ChartAreas[0].AxisY.Title = "宽度(cm)";
  219. chart3.Series["面宽"].ChartType = SeriesChartType.Line;
  220. chart3.Series["面宽"].MarkerSize = 5;
  221. chart3.Series["面宽"].MarkerColor = Color.Blue;
  222. chart3.Series["面宽"].MarkerStyle = MarkerStyle.Circle;
  223. }
  224. #endregion
  225. #region 权限判断
  226. private void UserRightCheck()
  227. {
  228. //this.tsmPdtMgr.Enabled = SysMgr.Instance.UserMgr.RightControl(MaiMuControl.SysStatusMgr.UserMgr.UserRightEnum.Product);
  229. //this.tsmSysDataFind.Visible = SysMgr.Instance.UserMgr.RightControl(MaiMuControl.SysStatusMgr.UserMgr.UserRightEnum.Statistics);
  230. //this.tsmUserList.Enabled = SysMgr.Instance.UserMgr.RightControl(MaiMuControl.SysStatusMgr.UserMgr.UserRightEnum.User);
  231. //this.tsmUserRight.Enabled = SysMgr.Instance.UserMgr.RightControl(MaiMuControl.SysStatusMgr.UserMgr.UserRightEnum.Role);
  232. //if (this.tsmUserList.Enabled == false && this.tsmUserRight.Enabled == false)
  233. // this.tsmSysUserMgr.Visible = false;
  234. //else
  235. // this.tsmSysUserMgr.Visible = true;
  236. //this.tsmDebug.Enabled = SysMgr.Instance.UserMgr.RightControl(MaiMuControl.SysStatusMgr.UserMgr.UserRightEnum.Debug);
  237. //this.tsmSysSet.Enabled = SysMgr.Instance.UserMgr.RightControl(MaiMuControl.SysStatusMgr.UserMgr.UserRightEnum.ParamsSetting);
  238. //if (this.tsmDebug.Enabled == false && this.tsmSysSet.Enabled == false)
  239. // this.stmSysSet.Visible = false;
  240. //else
  241. // this.stmSysSet.Visible = true;
  242. }
  243. #endregion
  244. #region 运行判断
  245. /// <summary>
  246. /// 系统是否在运行
  247. /// </summary>
  248. /// <returns></returns>
  249. private bool SystemIsRun()
  250. {
  251. //if (SysMgr.Instance.IsRuning)
  252. //{
  253. // FrmDialog.ShowDialog(this, "设备正在运行中!", "警告", false);
  254. // //MessageBox.Show("设备正在运行中!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  255. // return false;
  256. //}
  257. return true;
  258. }
  259. #endregion
  260. #region 界面事件
  261. private void Main_Load(object sender, EventArgs e)
  262. {
  263. //登入
  264. if (SysMgr.Instance.LoginSystem())
  265. {
  266. //登入成功
  267. if (InitSystem())
  268. {
  269. this.Cursor = Cursors.WaitCursor;
  270. //this.WindowState = FormWindowState.Normal;
  271. this.Top = 0;
  272. this.Left = 0;
  273. this.Width = SystemInformation.WorkingArea.Width;
  274. this.Height = SystemInformation.WorkingArea.Height;
  275. //this.WindowState = FormWindowState.Maximized;
  276. //this.splitContainer1.SplitterDistance = this.Width / 3;
  277. ResetUI(true);
  278. this.Show();
  279. this.tsslLoginInfo.Text = $"操作员:{SysMgr.Instance.UserMgr.LoginUser.Code}({SysMgr.Instance.UserMgr.LoginUser.Name})";
  280. this.statusStrip1.LayoutStyle = System.Windows.Forms.ToolStripLayoutStyle.HorizontalStackWithOverflow;
  281. this.tsslLoginTime.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
  282. this.tsslLoginInfo.Alignment = System.Windows.Forms.ToolStripItemAlignment.Right;
  283. this.tsState.Text = "";
  284. //更新数据库格式
  285. Service.InitDB.initDB(ConfMgr.Instance.DBConStr);
  286. //权限判断
  287. UserRightCheck();
  288. //开启后台
  289. //timer1.Enabled = true;
  290. backgroundWorkerDo = true;
  291. backgroundWorker1.RunWorkerAsync();
  292. //s_BackWorker = true;
  293. //backgroundWorker.RunWorkerAsync();
  294. //开启云端连接
  295. //SysMgr.Instance.InitCloudConnect();
  296. //开启产品服务
  297. //SysMgr.Instance.InitPdtService();
  298. //开启处理事件反馈
  299. SysMgr.Instance.InitDefectEvent();
  300. //加载产品料号
  301. SysMgr.Instance.LoadProductCodeList();
  302. //加载产品选择
  303. LoadPdtList(SysMgr.Instance.ProductCodeList);
  304. this.Cursor = Cursors.Default;
  305. //初次加载缺陷标准列表
  306. InitDefectListDataView();
  307. //激活OnPageChanged事件
  308. pageCtrl1.OnPageChanged += new EventHandler(pagerControl1_OnPageChanged);
  309. //加载串口
  310. GetComPort();
  311. //运行前检测磁盘空间
  312. SysMgr.CheckDisk(this);
  313. }
  314. else
  315. {
  316. Application.Exit();
  317. }
  318. }
  319. else
  320. {
  321. Application.Exit();
  322. }
  323. }
  324. private void Main_FormClosing(object sender, FormClosingEventArgs e)
  325. {
  326. if (SystemIsRun())
  327. {
  328. DialogResult dr = DialogResult.Cancel;
  329. if (SysMgr.Instance.IsInit)
  330. {
  331. dr = FrmDialog.ShowDialog(this, "确定要退出当前系统?", "警告", true);
  332. }
  333. else
  334. dr = DialogResult.OK;
  335. if (dr == DialogResult.Cancel)
  336. {
  337. e.Cancel = true;
  338. }
  339. else
  340. {
  341. backgroundWorkerDo = false;
  342. //Thread.Sleep(300);
  343. Thread.Sleep(300);
  344. if (SysMgr.Instance.IsInit)
  345. SysMgr.Instance.Close();
  346. //SysMgr.Instance.MainRuning -= main_running;
  347. }
  348. }
  349. else
  350. e.Cancel = true;
  351. }
  352. private void Main_SizeChanged(object sender, EventArgs e)
  353. {
  354. if (this.WindowState == FormWindowState.Maximized)
  355. {
  356. this.WindowState = FormWindowState.Normal;
  357. this.Top = 0;
  358. this.Left = 0;
  359. this.Width = SystemInformation.WorkingArea.Width;
  360. this.Height = SystemInformation.WorkingArea.Height;
  361. }
  362. }
  363. #endregion
  364. #region 菜单
  365. #region 用户
  366. #endregion
  367. #region 系统设置
  368. private void MainFrm_Paint(object sender, PaintEventArgs e)
  369. {
  370. }
  371. #endregion
  372. #endregion
  373. #region 检测管理
  374. private string[] pdtlistData;
  375. private void LoadPdtList(List<string> list)
  376. {
  377. this.cbPdtType.Items.Clear();
  378. while (true)
  379. {
  380. bool bk = true;
  381. for (int i = 0; i < list.Count; i++)
  382. {
  383. if (list[i] == null || string.IsNullOrEmpty(list[i]))
  384. {
  385. list.Remove(list[i]);
  386. bk = false;
  387. }
  388. }
  389. if (bk)
  390. {
  391. break;
  392. }
  393. }
  394. this.pdtlistData = list.ToArray();
  395. cbPdtType.Items.AddRange(pdtlistData);//比使用DataSource速度要快一些
  396. this.cbPdtType.Text = "";
  397. cbPdtType.Focus();
  398. cbPdtType.SelectAll();
  399. }
  400. private void tsmPdtMgr_Click(object sender, EventArgs e)
  401. {
  402. if (SystemIsRun())
  403. {
  404. ProductListFrm frm = new ProductListFrm();
  405. frm.ShowDialog();
  406. //加载产品料号
  407. SysMgr.Instance.LoadProductCodeList();
  408. //加载产品选择
  409. LoadPdtList(SysMgr.Instance.ProductCodeList);
  410. }
  411. }
  412. #endregion
  413. #region 显示图像和消息
  414. /// <summary>
  415. /// 异步输出日志
  416. /// </summary>
  417. /// <param name="tag">模板标识</param>
  418. /// <param name="msg">内容</param>
  419. /// <param name="type"></param>
  420. private void AddTextEvent(string tag, string msg, WarningEnum level = WarningEnum.Normal, bool Show = true)
  421. {
  422. lock (AddTextLock)
  423. {
  424. if (tag != null && tag != "")
  425. tag = $" - [{tag}]";
  426. var now = DateTime.Now;
  427. msg = now.ToString("HH:mm:ss fff") + tag + " - " + msg;
  428. syslog.Text = msg;
  429. syslog.ForeColor = level == WarningEnum.Normal ? Color.White : level == WarningEnum.Low ? Color.Yellow : Color.Red;
  430. }
  431. }
  432. private void main_running(object sender, MainEventArgs e)
  433. {
  434. ShowMessage(e);
  435. }
  436. private delegate void ShowMessageDelegate(MainEventArgs e);
  437. private void ShowMessage(MainEventArgs e)
  438. {
  439. if (InvokeRequired)
  440. {
  441. ShowMessageDelegate smd = new ShowMessageDelegate(ShowMessage);
  442. this.BeginInvoke(smd, e);
  443. }
  444. else
  445. {
  446. AddTextEvent(e.Tag, e.Message, e.Warning, e.show);
  447. }
  448. }
  449. /// <summary>
  450. /// 自动运行流程显示
  451. /// </summary>
  452. /// <param name="sender"></param>
  453. /// <param name="e"></param>
  454. private void auto_runing(object sender, RunEventArgs e)
  455. {
  456. ShowUIEvent(e);
  457. }
  458. private delegate void ShowUIEventDelegate(RunEventArgs e);
  459. Bitmap bmp0;
  460. Bitmap bmp1;
  461. Bitmap bmp2;
  462. private void ReDrawDefectPoints(List<object[]> DataRowlist)
  463. {
  464. foreach (var rowItem in DataRowlist)
  465. {
  466. this.skinDataGridView1.Rows.Insert(0, rowItem);
  467. if (chart1.Series.FindByName((string)rowItem[3]) == null)//rowItem[3] 为name
  468. {
  469. chart1.Series.Add((string)rowItem[3]);
  470. var obj = SysMgr.Instance.GetDefectLabel((string)rowItem[3]);
  471. int labelIndex = obj.Value<int>("id");
  472. chart1.Series[(string)rowItem[3]].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point;
  473. chart1.Series[(string)rowItem[3]].MarkerSize = 5;
  474. chart1.Series[(string)rowItem[3]].MarkerColor = ChartColor[labelIndex];
  475. chart1.Series[(string)rowItem[3]].MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
  476. }
  477. chart1.Series[(string)rowItem[3]].Points.AddXY(rowItem[4], rowItem[5]);
  478. }
  479. //chart1.ChartAreas[0].AxisY.Maximum = ((int)(this.chart1.Series["划伤"].Points.FindMaxByValue().YValues.Max() / 10) + 1) * 10 + 5;
  480. chart1.ChartAreas[0].AxisY.ScaleView.Scroll(System.Windows.Forms.DataVisualization.Charting.ScrollType.Last);
  481. }
  482. private void LoadDefectLabelAndPrint(Product md, bool reLabel = false)
  483. {
  484. dataGridView1.Columns.Clear();
  485. DataTable dt = new DataTable(); //建立个数据表
  486. dt.Columns.Add(new DataColumn("二次判断项", typeof(string)));//在表中添加string类型的列
  487. dataGridView1.DataSource = dt;
  488. //插入按钮
  489. DataGridViewButtonColumn btn1 = new DataGridViewButtonColumn();
  490. btn1.Name = "Pause";
  491. btn1.HeaderText = "判断";
  492. //btn1.DefaultCellStyle.va = "启用";
  493. btn1.Text = "开启";
  494. btn1.UseColumnTextForButtonValue = false;
  495. btn1.DefaultCellStyle.NullValue = "开启";
  496. btn1.DefaultCellStyle.BackColor = Color.LimeGreen;
  497. dataGridView1.Columns.Add(btn1);
  498. DataGridViewButtonColumn btn2 = new DataGridViewButtonColumn();
  499. btn2.Name = "Print";
  500. btn2.HeaderText = "打标";
  501. btn2.Text = "开启";
  502. btn2.UseColumnTextForButtonValue = false;
  503. btn2.DefaultCellStyle.NullValue = "开启";
  504. btn2.DefaultCellStyle.BackColor = Color.LimeGreen;
  505. dataGridView1.Columns.Add(btn2);
  506. List<string> list = new List<string>();
  507. DataTable dts = (DataTable)dataGridView1.DataSource;
  508. dts.Clear();
  509. foreach (var item in md.QualifiedLimitList)
  510. {
  511. if (md.DefectPauseOption == null || md.DefectPauseOption.Count==0 || md.DefectPauseOption.Contains(item.Code))
  512. {
  513. //新增
  514. DataRow dr;//行
  515. dr = dts.NewRow();
  516. dr["二次判断项"] = item.NameCode;
  517. dts.Rows.Add(dr);//在表的对象的行里添加此行
  518. list.Add(item.NameCode);
  519. }
  520. }
  521. dataGridView1.Columns[0].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
  522. dataGridView1.Columns[0].DefaultCellStyle.ForeColor = Color.Black;
  523. dataGridView1.Columns[0].DefaultCellStyle.SelectionForeColor = Color.Black;
  524. if (reLabel)
  525. {
  526. SysMgr.Instance.LoadDefectItemsPuase(list);
  527. SysMgr.Instance.LoadDefectItemsDB(list);
  528. }
  529. }
  530. private void ReDrawDefectPoints(List<DefectInfo> DataRowlist)
  531. {
  532. try
  533. {
  534. //重新绘制
  535. chart1.Series.Clear();
  536. chart1.Series.Add("SELECT");
  537. chart1.Series["SELECT"].ChartType = SeriesChartType.Point;
  538. chart1.Series["SELECT"].MarkerSize = 25;
  539. chart1.Series["SELECT"].MarkerColor = Color.Black;
  540. chart1.Series["SELECT"].MarkerStyle = MarkerStyle.Star6;
  541. //chart1.Series["SELECT"].Enabled = false;
  542. chart1.ChartAreas[0].AxisX.Title = "宽度(cm)";
  543. chart1.ChartAreas[0].AxisY.Title = "长度(m)";
  544. foreach (var rowItem in DataRowlist)
  545. {
  546. //this.skinDataGridView1.Rows.Insert(0, rowItem);
  547. if (chart1.Series.FindByName((string)rowItem.Name) == null)//rowItem[3] 为name
  548. {
  549. chart1.Series.Add((string)rowItem.Name);
  550. var obj = SysMgr.Instance.GetDefectLabel((string)rowItem.Name);
  551. int labelIndex = obj.Value<int>("id");
  552. chart1.Series[(string)rowItem.Name].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point;
  553. chart1.Series[(string)rowItem.Name].MarkerSize = 5;
  554. chart1.Series[(string)rowItem.Name].MarkerColor = ChartColor[labelIndex];
  555. chart1.Series[(string)rowItem.Name].MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
  556. }
  557. chart1.Series[(string)rowItem.Name].Points.AddXY(rowItem.CentreX, rowItem.CentreY / 100);
  558. }
  559. //chart1.ChartAreas[0].AxisY.Maximum = ((int)(this.chart1.Series["划伤"].Points.FindMaxByValue().YValues.Max() / 10) + 1) * 10 + 5;
  560. chart1.ChartAreas[0].AxisY.ScaleView.Scroll(System.Windows.Forms.DataVisualization.Charting.ScrollType.Last);
  561. }
  562. catch
  563. { }
  564. }
  565. private void ShowUIEvent(RunEventArgs e)
  566. {
  567. if (InvokeRequired)
  568. {
  569. ShowUIEventDelegate smd = new ShowUIEventDelegate(ShowUIEvent);
  570. this.BeginInvoke(smd, e);
  571. }
  572. else
  573. {
  574. try
  575. {
  576. if (e.Cmd == 6) //显示主图
  577. {
  578. //this.BeginInvoke(new System.Action(() =>
  579. //{
  580. if (e.PicIndex == 1)
  581. {
  582. bmp1 = e.Pic.ToBitmap();
  583. //this.pictureBox2.Image = bmp1;
  584. //this.pictureBox2.Refresh();
  585. }
  586. else if (e.PicIndex == 2)
  587. {
  588. bmp2 = e.Pic.ToBitmap();
  589. //this.pictureBox3.Image = bmp2;
  590. //this.pictureBox3.Refresh();
  591. }
  592. else if (e.PicIndex == 0)
  593. {
  594. bmp0 = e.Pic.ToBitmap();
  595. this.pictureBox1.Image = bmp0;
  596. this.pictureBox1.Refresh();
  597. }
  598. //}));
  599. }
  600. else if (e.Cmd == 10) //测试结束
  601. {
  602. this.tsbtnStart.Enabled = true;
  603. this.tsbtnStop.Enabled = false;
  604. this.tsbtnImpStop.Enabled = false;
  605. this.cbPdtSN.Enabled = true;
  606. this.cbPdtColor.Enabled = true;
  607. this.numPdtLength.Enabled = true;
  608. this.cbPdtType.Enabled = true;
  609. }
  610. else if (e.Cmd == 11) //显示缺陷列表
  611. {
  612. //this.BeginInvoke(new System.Action(() =>
  613. //{
  614. ReDrawDefectPoints(e.DataRowlist);
  615. //显示最新缺陷
  616. var defectInfo = SysMgr.Instance.GetDefectInfo((long)this.skinDataGridView1.Rows[0].Cells["colUid"].Value);
  617. if (defectInfo == null)
  618. {
  619. return;
  620. }
  621. //OpenCvSharp.Mat img = BitmapConverter.ToMat((Bitmap)defectInfo.image);
  622. //imageBox3.RefreshWindow(img, ImageBox.ImageModeEnum.Zoom);//可以不显示区域
  623. //this.imageBox3.Image = (defectInfo.image);
  624. //}));
  625. }
  626. else if(e.Cmd == 12) //显示处理图
  627. {
  628. //this.BeginInvoke(new System.Action(() =>
  629. //{
  630. bmp0 = (Bitmap)e.Defectimg.Clone();
  631. this.pictureBox1.Image = bmp0;
  632. this.pictureBox1.Refresh();
  633. //}));
  634. }
  635. else if (e.Cmd == 13) //显示门幅
  636. {
  637. //this.BeginInvoke(new System.Action(() =>
  638. //{
  639. List<float> ydata = new List<float>();
  640. this.lbFK.Text = "当前幅宽:" + $"{e.Points[e.Points.Count - 1][1]}";
  641. this.chart3.Series["面宽"].Points.Clear();
  642. foreach (var Item in e.Points)
  643. {
  644. ydata.Add(Item[1]);
  645. float x = Item[0] / 100; //cm -> m
  646. this.chart3.Series["面宽"].Points.AddXY((float)Math.Round(x, 2), (float)Math.Round(Item[1], 2));
  647. }
  648. chart3.ChartAreas[0].AxisY.Maximum = Math.Round(ydata.Max() + 10, 0);
  649. chart3.ChartAreas[0].AxisY.Minimum = Math.Round(ydata.Min() - 10, 0);
  650. //chart3.ChartAreas["ChartArea1"].AxisX.ScaleView.Scroll(ScrollType.Last);
  651. //}));
  652. }
  653. else if (e.Cmd == 14) //显示速度
  654. {
  655. //this.BeginInvoke(new System.Action(() =>
  656. //{
  657. lblDefectLen.Text = $"检测长度: {Math.Round(e.Len, 2)} 米";
  658. lblDefectSpeed.Text = $"检测速度: {Math.Round(e.Speed,2)} 米/分钟";
  659. //}));
  660. }
  661. else if (e.Cmd == 15) //显示处理图 new
  662. {
  663. //this.BeginInvoke(new System.Action(() =>
  664. //{
  665. bmp0 = (Bitmap)e.DefectMat.ToBitmap();
  666. this.pictureBox1.Image = bmp0;
  667. this.pictureBox1.Refresh();
  668. //}));
  669. }
  670. else if (e.Cmd == 16) //显示缓存
  671. {
  672. this.tsState.Text = $"相机1:{e.Cam1ImgCnt},相机2:{e.Cam2ImgCnt}";
  673. this.tslabelTime.Text = e._DefinfoCnt;
  674. //this.stsSaveQueue.Text = $"存图队列:{e.SaveImgCnt}";
  675. }
  676. else if (e.Cmd == 17) //显示光源亮度
  677. {
  678. ;
  679. }
  680. else if (e.Cmd == 18) //显示二次判断和打标
  681. {
  682. //this.BeginInvoke(new System.Action(() =>
  683. //{
  684. // LoadDefectLabelAndPrint(e.MD);
  685. //}));
  686. }
  687. else if (e.Cmd == 19) // 二次判定数据修改
  688. {
  689. //不能使用同步Invoke方式,会使相机超时丢帧
  690. this.BeginInvoke(new System.Action(() =>
  691. {
  692. reFreashFrm(e.ImgIndex, e.LstEditDefect, e.Records, e.LstEditInfo);
  693. #if false
  694. int liDefectCount = e.LstEditDefect.Count;
  695. if(e.LstEditInfo != null || e.LstEditDefect != null)
  696. {
  697. string oldCode;
  698. for (int i = 0; i < this.skinDataGridView1.Rows.Count; i++)
  699. {
  700. if ((int)this.skinDataGridView1.Rows[i].Cells["colIndex"].Value != e.ImgIndex)
  701. continue;
  702. long uid = (long)this.skinDataGridView1.Rows[i].Cells["colUid"].Value;
  703. foreach (var row in e.LstEditDefect)
  704. {
  705. //AddTextEvent($"二次确认", $"修改第({i + 1})行瑕疵名称,{uid} {row.uid}");
  706. if (row.uid == uid)
  707. {
  708. oldCode = this.skinDataGridView1.Rows[i].Cells["colCode"].Value.ToString();
  709. //AddTextEvent($"二次确认", $"修改第({i + 1})行瑕疵名称 ({this.skinDataGridView1.Rows[i].Cells["colDefectName"].Value})->({row.Name})");
  710. this.skinDataGridView1.Rows[i].Cells["colCode"].Value = row.Code;
  711. this.skinDataGridView1.Rows[i].Cells["colDefectName"].Value = row.Name;
  712. //this.uiDataGridView1.Refresh();
  713. if (!string.IsNullOrWhiteSpace(row.TagFilePath) && oldCode != row.Code)
  714. File.Move(row.TagFilePath, row.TagFilePath.Replace($"_类别{oldCode}", $"_类别{row.Code}"));//
  715. break;
  716. }
  717. }
  718. if (e.LstEditInfo != null)
  719. {
  720. foreach (var item in e.LstEditInfo)
  721. {
  722. if (item.uid == uid)
  723. {
  724. this.skinDataGridView1.Rows.RemoveAt(i);
  725. i--;
  726. break;
  727. }
  728. }
  729. }
  730. }
  731. //SysMgr.Instance.DelDefectEdit(e.Records, frmDefect.lstDel);
  732. //double len = (double)this.lblLen.Tag;
  733. //this.reDrawDefectPoints(curRecord.DefectInfoList, new double[] { 0, Math.Round(curRecord.FaceWidthMax + 0.005f, 2) }, new double[] { 0, len });
  734. //AddTextEvent($"二次检测", $"本次忽略{frmDefect.lstDel.Count}个瑕疵,本张图由{liDefectCount} -> {e.LstEditDefect.Count},总数{e.Records.DefectInfoList.Count}");
  735. }
  736. //this.uiMiniPagination1.TotalCount = curRecord.DefectTotalCount = curRecord.DefectInfoList.Count;
  737. //
  738. //double len = Math.Round((res.photoIndex + 1) * bmpHeight * 1.0d / Config.cm2px_y + 0.005f, 2);
  739. //重新绘制分布图
  740. ReDrawDefectPoints(e.Records.DefectInfoList);
  741. //自动继续运行设备(这里临时暂停后不能再急停,否则无法继续)
  742. SysMgr.Instance.StartMotion();
  743. #endif
  744. }));
  745. }
  746. else if (e.Cmd == 20) //显示存图缓存
  747. {
  748. //this.tsState.Text = $"相机1:{e.Cam1ImgCnt},相机2:{e.Cam2ImgCnt}";
  749. this.stsSaveQueue.Text = $"存图队列:{e.SaveImgCnt}";
  750. }
  751. else if (e.Cmd == 21) //显示二次判定界面
  752. {
  753. this.BeginInvoke(new System.Action(() =>
  754. {
  755. var pimage = (Bitmap)e.TagImg.ToBitmap().Clone();
  756. List<DefectInfo> ld = new List<DefectInfo>();
  757. foreach (var item in e.LstEditDefect)
  758. {
  759. ld.Add(item);
  760. }
  761. int index = e.ImgIndex;
  762. //Task.Run(() =>
  763. //{
  764. int liDefectCount = ld.Count;
  765. ImageShowFrm frmDefect = new ImageShowFrm(index, ld, pimage);
  766. if (frmDefect.ShowDialog() == DialogResult.OK)
  767. {
  768. SysMgr.Instance.DelDefectEdit(e.Records, frmDefect.lstDel);
  769. reFreashFrm(index, ld, e.Records, frmDefect.lstDel);
  770. AddTextEvent($"二次检测2", $"本次忽略{frmDefect.lstDel.Count}个瑕疵,本张图由{liDefectCount} -> {ld.Count},总数{e.Records.DefectInfoList.Count}");
  771. }
  772. else
  773. {
  774. reFreashFrm(index, ld, e.Records, null);
  775. }
  776. //});
  777. }));
  778. }
  779. //Application.DoEvents();
  780. }
  781. catch { }
  782. }
  783. }
  784. #endregion
  785. #region 二次确认界面刷新
  786. void reFreashFrm(int index, List<DefectInfo> lstEditDefect, Records currRecord, List<DefectInfo> lstEditInfo)
  787. {
  788. int err = 0;
  789. try
  790. {
  791. //int liDefectCount = lstEditDefect.Count;
  792. //ImageShowFrm frmDefect = new ImageShowFrm(e.LstEditDefect, e.TagImg.ToBitmap());
  793. //frmDefect.Show();
  794. //if (frmDefect.ShowDialog() == DialogResult.OK)
  795. if (lstEditInfo != null || lstEditDefect != null)
  796. {
  797. err = 1;
  798. string oldCode;
  799. for (int i = 0; i < this.skinDataGridView1.Rows.Count; i++)
  800. {
  801. if ((int)this.skinDataGridView1.Rows[i].Cells["colIndex"].Value != index)
  802. continue;
  803. err = 2;
  804. long uid = (long)this.skinDataGridView1.Rows[i].Cells["colUid"].Value;
  805. foreach (var row in lstEditDefect)
  806. {
  807. //AddTextEvent($"二次确认", $"修改第({i + 1})行瑕疵名称,{uid} {row.uid}");
  808. if (row.uid == uid)
  809. {
  810. err = 3;
  811. oldCode = this.skinDataGridView1.Rows[i].Cells["colCode"].Value.ToString();
  812. //AddTextEvent($"二次确认", $"修改第({i + 1})行瑕疵名称 ({this.skinDataGridView1.Rows[i].Cells["colDefectName"].Value})->({row.Name})");
  813. this.skinDataGridView1.Rows[i].Cells["colCode"].Value = row.Code;
  814. this.skinDataGridView1.Rows[i].Cells["colDefectName"].Value = row.Name;
  815. //this.uiDataGridView1.Refresh();
  816. if (!string.IsNullOrWhiteSpace(row.TagFilePath) && oldCode != row.Code)
  817. File.Move(row.TagFilePath, row.TagFilePath.Replace($"_类别{oldCode}", $"_类别{row.Code}"));//
  818. break;
  819. }
  820. }
  821. err = 4;
  822. if (lstEditInfo != null)
  823. {
  824. foreach (var item in lstEditInfo)
  825. {
  826. if (item.uid == uid)
  827. {
  828. this.skinDataGridView1.Rows.RemoveAt(i);
  829. i--;
  830. break;
  831. }
  832. }
  833. }
  834. }
  835. //SysMgr.Instance.DelDefectEdit(e.Records, frmDefect.lstDel);
  836. //double len = (double)this.lblLen.Tag;
  837. //this.reDrawDefectPoints(curRecord.DefectInfoList, new double[] { 0, Math.Round(curRecord.FaceWidthMax + 0.005f, 2) }, new double[] { 0, len });
  838. //AddTextEvent($"二次检测", $"本次忽略{frmDefect.lstDel.Count}个瑕疵,本张图由{liDefectCount} -> {e.LstEditDefect.Count},总数{e.Records.DefectInfoList.Count}");
  839. }
  840. //this.uiMiniPagination1.TotalCount = curRecord.DefectTotalCount = curRecord.DefectInfoList.Count;
  841. //
  842. //double len = Math.Round((res.photoIndex + 1) * bmpHeight * 1.0d / Config.cm2px_y + 0.005f, 2);
  843. //重新绘制分布图
  844. err = 5;
  845. ReDrawDefectPoints(currRecord.DefectInfoList);
  846. err = 6;
  847. //自动继续运行设备(这里临时暂停后不能再急停,否则无法继续)
  848. SysMgr.Instance.StartMotion();
  849. }catch(Exception ex)
  850. {
  851. MessageBox.Show($"err {err}:{ex.Message}");
  852. }
  853. }
  854. #endregion
  855. #region 后台
  856. GetPN pn = new GetPN();
  857. private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
  858. {
  859. while (backgroundWorkerDo)
  860. {
  861. try
  862. {
  863. this.Invoke(new MethodInvoker(() =>
  864. {
  865. this.tsslLoginTime.Text = $" 当前时间:{DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss")}";
  866. }));
  867. //检测按钮和实时状态
  868. if (SysMgr.Instance.IsInit)
  869. {
  870. bool sts = SysMgr.Instance.WarningShowLed(false);
  871. if (sts)
  872. {
  873. this.Invoke(new MethodInvoker(() =>
  874. {
  875. this.tsbtnStart.Enabled = true;
  876. this.tsbtnStop.Enabled = false;
  877. }));
  878. }
  879. int stsno = 0;
  880. stsno = SysMgr.Instance.ButtonIOTrg(false);
  881. if (stsno == 1)
  882. {
  883. this.Invoke(new MethodInvoker(() =>
  884. {
  885. tsbtnStart_Click(null, null);
  886. }));
  887. }
  888. else if (stsno == 2)
  889. {
  890. this.Invoke(new MethodInvoker(() =>
  891. {
  892. this.tsbtnStart.Enabled = true;
  893. }));
  894. SysMgr.Instance.LedPause();
  895. }
  896. else if (stsno == 3)
  897. {
  898. this.Invoke(new MethodInvoker(() =>
  899. {
  900. tsbtnReset_Click(null, null);
  901. }));
  902. }
  903. }
  904. if (pn.P(SysMgr.Instance.IsRuning))
  905. {
  906. //继续计时
  907. RunStartTime.Start();
  908. }
  909. if (pn.N(SysMgr.Instance.IsRuning))
  910. {
  911. //停止计时
  912. RunStartTime.Stop();
  913. }
  914. if (SysMgr.Instance.IsRuning)
  915. {
  916. ////实时显示
  917. //RunStartTime.Stop();
  918. //this.Invoke(new MethodInvoker(() =>
  919. //{
  920. // tslabelTime.Text = "实时测试:" + ((double)RunStartTime.ElapsedMilliseconds / 1000.0).ToString("0.000") + "s";
  921. // //this.Refresh();
  922. //}));
  923. //RunStartTime.Start();
  924. }
  925. Thread.Sleep(100);
  926. //Application.DoEvents();
  927. }
  928. catch { }
  929. }
  930. }
  931. /// <summary>
  932. /// 信号上升沿下降沿捕获
  933. /// </summary>
  934. class GetPN
  935. {
  936. bool _P = false;
  937. bool _N = false;
  938. /// <summary>
  939. /// 判断上升沿
  940. /// </summary>
  941. /// <param name="Value"></param>
  942. /// <returns></returns>
  943. public bool P(bool Value)
  944. {
  945. if (Value && !_P)
  946. {
  947. _P = true;
  948. return true;
  949. }
  950. if (!Value)
  951. _P = false;
  952. return false;
  953. }
  954. /// <summary>
  955. /// 判断下降沿
  956. /// </summary>
  957. /// <param name="Value"></param>
  958. /// <returns></returns>
  959. public bool N(bool Value)
  960. {
  961. if (!Value && _N)
  962. {
  963. _N = false;
  964. return true;
  965. }
  966. if (Value)
  967. _N = true;
  968. return false;
  969. }
  970. }
  971. #endregion
  972. #region 表格点击
  973. private void skinDataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
  974. {
  975. if (e.RowIndex < 0)
  976. return;
  977. var defectInfo = SysMgr.Instance.GetDefectInfo((long)this.skinDataGridView1.CurrentRow.Cells["colUid"].Value);
  978. if (defectInfo == null)
  979. {
  980. DialogResult dr = DialogResult.Cancel;
  981. dr = FrmDialog.ShowDialog(this, "此记录已不存在!", "警告", true);
  982. return;
  983. }
  984. //选中
  985. this.Invoke(new System.Action(() =>
  986. {
  987. if (chart1.Series != null && chart1.Series.FindByName("SELECT") != null)
  988. {
  989. chart1.Series["SELECT"].Points.Clear();
  990. chart1.Series["SELECT"].Points.AddXY(defectInfo.CentreX, defectInfo.CentreY / 100);
  991. chart1.Refresh();
  992. }
  993. }));
  994. }
  995. #endregion
  996. #region 二次判断
  997. private void ucSwitch1_CheckedChanged(object sender, EventArgs e)
  998. {
  999. SysMgr.Instance.SetDefectPause(ucSwitch1.Checked);
  1000. }
  1001. #endregion
  1002. #region 打标
  1003. private void ucSwitch2_CheckedChanged(object sender, EventArgs e)
  1004. {
  1005. SysMgr.Instance.SetDefectDB(ucSwitch2.Checked);
  1006. }
  1007. #endregion
  1008. #region 控制光源
  1009. private void ucTrackBar1_ValueChanged(object sender, EventArgs e)
  1010. {
  1011. //SysMgr.Instance.SetLightValue((int)ucTrackBar1.Value);
  1012. }
  1013. #endregion
  1014. #region 二次判断和打标表格点击
  1015. private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
  1016. {
  1017. //for (int i = 0; i < this.dataGridView1.RowCount; i++)
  1018. //{
  1019. // namelist.Add(this.dataGridView1.Rows[i].Cells[0].Value.ToString());
  1020. //}
  1021. int Index = this.dataGridView1.CurrentRow.Index;//获取当前选中行的索引
  1022. if (Index < this.dataGridView1.Rows.Count && this.dataGridView1.Columns[this.dataGridView1.CurrentCell.ColumnIndex].HeaderText.ToString() == "判断")
  1023. {
  1024. List<string> namelist = new List<string>();
  1025. DataGridViewButtonCell btn = (DataGridViewButtonCell)this.dataGridView1.CurrentCell;
  1026. if (btn.FormattedValue.ToString() == "开启")
  1027. {
  1028. this.dataGridView1.CurrentCell.Value = "禁用";
  1029. this.dataGridView1.CurrentCell.Style.BackColor = Color.Red;
  1030. this.dataGridView1.CurrentCell.Style.ForeColor = Color.Red;
  1031. }
  1032. else
  1033. {
  1034. this.dataGridView1.CurrentCell.Value = "开启";
  1035. this.dataGridView1.CurrentCell.Style.BackColor = Color.LimeGreen;
  1036. this.dataGridView1.CurrentCell.Style.ForeColor = Color.Black;
  1037. }
  1038. for (int i = 0; i < this.dataGridView1.RowCount; i++)
  1039. {
  1040. DataGridViewButtonCell btn2 = (DataGridViewButtonCell)this.dataGridView1.Rows[i].Cells[1];
  1041. if (btn2.FormattedValue.ToString() == "开启")
  1042. namelist.Add(this.dataGridView1.Rows[i].Cells[0].Value.ToString());
  1043. }
  1044. //开启该项二次判断功能
  1045. SysMgr.Instance.LoadDefectItemsPuase(namelist);
  1046. }
  1047. else if (Index < this.dataGridView1.Rows.Count && this.dataGridView1.Columns[this.dataGridView1.CurrentCell.ColumnIndex].HeaderText.ToString() == "打标")
  1048. {
  1049. List<string> namelist = new List<string>();
  1050. DataGridViewButtonCell btn = (DataGridViewButtonCell)this.dataGridView1.CurrentCell;
  1051. if (btn.FormattedValue.ToString() == "开启")
  1052. {
  1053. this.dataGridView1.CurrentCell.Value = "禁用";
  1054. this.dataGridView1.CurrentCell.Style.BackColor = Color.Red;
  1055. this.dataGridView1.CurrentCell.Style.ForeColor = Color.Red;
  1056. }
  1057. else
  1058. {
  1059. this.dataGridView1.CurrentCell.Value = "开启";
  1060. this.dataGridView1.CurrentCell.Style.BackColor = Color.LimeGreen;
  1061. this.dataGridView1.CurrentCell.Style.ForeColor = Color.Black;
  1062. }
  1063. for (int i = 0; i < this.dataGridView1.RowCount; i++)
  1064. {
  1065. DataGridViewButtonCell btn2 = (DataGridViewButtonCell)this.dataGridView1.Rows[i].Cells[1];
  1066. if (btn2.FormattedValue.ToString() == "开启")
  1067. namelist.Add(this.dataGridView1.Rows[i].Cells[0].Value.ToString());
  1068. }
  1069. //开启该项打标功能
  1070. SysMgr.Instance.LoadDefectItemsDB(namelist);
  1071. }
  1072. }
  1073. #endregion
  1074. #region 选检测标准之后自动加载二次判断
  1075. private void cbDefectCode_SelectedIndexChanged(object sender, EventArgs e)
  1076. {
  1077. Product model = SysMgr.Instance.GetProduct(cbPdtType.Text);
  1078. if (model != null)
  1079. {
  1080. LoadDefectLabelAndPrint(model, true);
  1081. }
  1082. }
  1083. #endregion
  1084. #region 模拟键盘
  1085. private KeyBoardType keyBoardType = KeyBoardType.UCKeyBorderAll_EN;
  1086. [Description("键盘打开样式"), Category("自定义")]
  1087. public KeyBoardType KeyBoardType
  1088. {
  1089. get { return keyBoardType; }
  1090. set { keyBoardType = value; }
  1091. }
  1092. private void showKeyPanel(Control ctl)
  1093. {
  1094. //keyPanel.Top = ctl.Top + ctl.Height + 5;
  1095. //keyPanel.Left = ctl.Left;
  1096. //keyPanel.Visible = true;
  1097. //keyPanel.BringToFront();
  1098. process = Process.Start(@"C:\WINDOWS\system32\osk.exe");
  1099. }
  1100. //Froms.FrmAnchor m_frmAnchor;
  1101. private void cbPdtSN_Click(object sender, EventArgs e)
  1102. {
  1103. showKeyPanel((Control)sender);
  1104. }
  1105. #endregion
  1106. #region 主界面Tab切换
  1107. int curr_TabIndex = 0;
  1108. private void skinTabControl1_TabIndexChanged(object sender, EventArgs e)
  1109. {
  1110. }
  1111. private void skinTabControl1_Selected(object sender, TabControlEventArgs e)
  1112. {
  1113. if (this.skinTabControl1.SelectedIndex == curr_TabIndex)
  1114. return;
  1115. else
  1116. {
  1117. curr_TabIndex = this.skinTabControl1.SelectedIndex;
  1118. switch(curr_TabIndex)
  1119. {
  1120. case 0:
  1121. #region 主界面
  1122. #endregion
  1123. break;
  1124. case 1:
  1125. #region 标准界面
  1126. #endregion
  1127. break;
  1128. case 2:
  1129. #region 数据分析
  1130. #endregion
  1131. break;
  1132. case 3:
  1133. #region 系统设置
  1134. RefeshSysParams();
  1135. #endregion
  1136. break;
  1137. }
  1138. }
  1139. }
  1140. #endregion
  1141. #region 检测标准界面
  1142. Models.Product _model = new Models.Product();
  1143. #region 标准列表获取
  1144. private void InitDefectListDataView(int selIndex = -1)
  1145. {
  1146. var list = SysMgr.Instance.ProductList;
  1147. //tsslCount.Text = $"共 {list.Count} 条记录";
  1148. int liIndex = 0;
  1149. if (selIndex > 0) liIndex = selIndex;
  1150. else if (this.dataGridView2.CurrentRow != null)
  1151. liIndex = this.dataGridView2.CurrentRow.Index;
  1152. dataGridView2.DataSource = new BindingSource(list, null);
  1153. if (dataGridView2.Rows.Count > liIndex)
  1154. dataGridView2.CurrentCell = dataGridView2[1, liIndex];
  1155. //如果产品存在设置问题,无流程显示颜色
  1156. for (int i = 0; i < dataGridView2.Rows.Count; i++)
  1157. {
  1158. ;
  1159. }
  1160. }
  1161. #endregion
  1162. #region 检测标准搜索
  1163. private void tbSearch_TextChanged(object sender, EventArgs e)
  1164. {
  1165. if (tbSearch.Text != "")
  1166. {
  1167. int count = 0;
  1168. foreach (DataGridViewRow row in dataGridView2.Rows)
  1169. {
  1170. for (int i = 0; i < row.Cells.Count; i++)
  1171. {
  1172. if (row.Cells[i].Value != null && row.Cells[i].Value.ToString().Contains(tbSearch.Text))
  1173. {
  1174. count = count + 1;
  1175. }
  1176. }
  1177. if (count == 0)
  1178. {
  1179. CurrencyManager cm = (CurrencyManager)BindingContext[dataGridView2.DataSource];
  1180. cm.SuspendBinding(); //挂起数据绑定
  1181. row.Visible = false;
  1182. cm.ResumeBinding(); //恢复数据绑定
  1183. }
  1184. count = 0;
  1185. }
  1186. }
  1187. else
  1188. {
  1189. for (int i = 0; i < dataGridView2.Rows.Count; i++)
  1190. {
  1191. dataGridView2.Rows[i].Visible = true;
  1192. }
  1193. }
  1194. }
  1195. #endregion
  1196. #region 删除检测标准
  1197. private void btnDelDefectNav_Click(object sender, EventArgs e)
  1198. {
  1199. try
  1200. {
  1201. if (this.dataGridView2.CurrentRow == null)
  1202. return;
  1203. if (MessageBox.Show($"确认删除?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
  1204. {
  1205. var list = ((BindingSource)dataGridView2.DataSource).DataSource as List<Models.Product>;
  1206. int liIndex = this.dataGridView2.CurrentRow.Index;//获取当前选中行的索引
  1207. if (!SysMgr.Instance.DelDefectItem(list[liIndex]))
  1208. throw new Exception("删除失败!");
  1209. MessageBox.Show("删除成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
  1210. //initDataView();
  1211. this.dataGridView2.Rows.RemoveAt(liIndex);
  1212. if (this.dataGridView2.Rows.Count == 0)
  1213. InitDefectListDataView();
  1214. }
  1215. }
  1216. catch (Exception ex)
  1217. {
  1218. MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  1219. }
  1220. }
  1221. #endregion
  1222. #region 标准详细
  1223. private void initModelData()
  1224. {
  1225. //模型文件
  1226. string strDefectModelFile = ConfMgr.Instance.SysConfigParams.AIModelPath;
  1227. if (!Directory.Exists(strDefectModelFile))
  1228. {
  1229. MessageBox.Show("模型路径错误:" + strDefectModelFile, "警告");
  1230. return;
  1231. }
  1232. string[] onnxFiles = Directory.GetFiles(strDefectModelFile, "*.trt");
  1233. //标签文件
  1234. string[] labelFiles = Directory.GetFiles(strDefectModelFile, "*.json");
  1235. string errorStr = "";
  1236. foreach (string onnxFile in onnxFiles)
  1237. {
  1238. string onlyName;
  1239. onlyName = Path.GetFileName(onnxFile);
  1240. cmbDefectModelFile.Items.Add(onlyName);
  1241. string findname = onlyName.Replace(".trt", ".json");
  1242. //存在对应label文件
  1243. if (labelFiles.Count(p => Path.GetFileName(p) == findname) <= 0)
  1244. {
  1245. errorStr += $"{onlyName},";
  1246. }
  1247. }
  1248. if (!string.IsNullOrEmpty(errorStr))
  1249. MessageBox.Show("模型缺少词典文件:" + errorStr, "警告");
  1250. //加载材质
  1251. string configPath = ConfMgr.Instance.ConfigDir + $"\\material.json";
  1252. if (File.Exists(configPath))
  1253. {
  1254. string lsTmp = File.ReadAllText(configPath);
  1255. JArray defectItemList = JArray.Parse(lsTmp);
  1256. cmbClasses.Items.Clear();
  1257. foreach (JObject item in defectItemList)
  1258. {
  1259. string name = item.Value<string>("name");
  1260. cmbClasses.Items.Add(name);
  1261. }
  1262. }
  1263. else
  1264. MessageBox.Show("模型材质文件:" + configPath, "警告");
  1265. }
  1266. private void ShowDefectItemInfo(Product m = null)
  1267. {
  1268. panel_jcbz.Visible = true;
  1269. //panel_jcbz.Location = new System.Drawing.Point(0, 0);
  1270. //panel_jcbz.Dock = DockStyle.Fill;
  1271. #region 缺陷信息和等级dataGridView设置
  1272. dataGridView3.AllowUserToAddRows = dataGridView3.AllowUserToDeleteRows = false;//用户添加删除行
  1273. dataGridView4.AllowUserToAddRows = dataGridView4.AllowUserToDeleteRows = false;
  1274. dataGridView3.AllowUserToResizeRows = dataGridView4.AllowUserToResizeRows = false;//用户调整行大小
  1275. //dataGridView1.AllowUserToResizeColumns = false;//用户调整列大小
  1276. //显示行号与列宽度自动调整
  1277. dataGridView3.RowHeadersVisible = dataGridView4.RowHeadersVisible = true;
  1278. dataGridView3.RowHeadersWidth = dataGridView4.RowHeadersWidth = 50;
  1279. //dataGridView1.ColumnHeadersHeightSizeMode = dataGridView2.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
  1280. dataGridView3.RowHeadersWidthSizeMode = dataGridView4.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;//数据量过百绑定太变
  1281. dataGridView3.RowTemplate.Height = dataGridView4.RowTemplate.Height = 30;
  1282. #endregion
  1283. initModelData();
  1284. if (m != null)
  1285. {
  1286. _model = m;
  1287. //显示模型
  1288. foreach (string onnxFile in this.cmbDefectModelFile.Items)
  1289. if (!string.IsNullOrWhiteSpace(_model.ModelName) && onnxFile.ToLower() == _model.ModelName.ToLower())
  1290. this.cmbDefectModelFile.SelectedItem = _model.ModelName;
  1291. //显示寻边算法
  1292. foreach (string edge in this.cbEdgeDefect.Items)
  1293. if (!string.IsNullOrWhiteSpace(_model.EdgeDefectType) && edge.ToLower() == _model.EdgeDefectType.ToLower())
  1294. this.cbEdgeDefect.SelectedItem = _model.EdgeDefectType;
  1295. //显示识别算法
  1296. foreach (string defect in this.cbImageDefet.Items)
  1297. if (!string.IsNullOrWhiteSpace(_model.ImageDefectType) && defect.ToLower() == _model.ImageDefectType.ToLower())
  1298. this.cbImageDefet.SelectedItem = _model.ImageDefectType;
  1299. txtName.Text = _model.Name;
  1300. cmbClasses.Text = _model.Material;
  1301. tbColorName.Text = _model.ColorName;
  1302. numHoldCut.Value = _model.EdgeHoleCut;
  1303. int[] rgb = new int[3];
  1304. if (!string.IsNullOrEmpty(_model.ColorValue))
  1305. {
  1306. for (int i = 0; i < rgb.Length; i++)
  1307. rgb[i] = Convert.ToInt32(_model.ColorValue.Split(',')[i]);
  1308. tbColorName.ForeColor = Color.FromArgb(rgb[0], rgb[1], rgb[2]);
  1309. }
  1310. //tbSpec.Text = _model.Spec;
  1311. TrackBarLightValue.Value = _model.LightValue;
  1312. TrackBarExposureTime.Value = (int)_model.ExposureTime;
  1313. TrackBarGain.Value = (int)_model.Gain;
  1314. }
  1315. }
  1316. #endregion
  1317. #region 新增
  1318. private void btnNewDefectItem_Click(object sender, EventArgs e)
  1319. {
  1320. ShowDefectItemInfo();
  1321. }
  1322. #endregion
  1323. #region 表格双击
  1324. private void dataGridView2_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
  1325. {
  1326. var list = ((BindingSource)dataGridView2.DataSource).DataSource as List<Models.Product>;
  1327. int liIndex = this.dataGridView2.CurrentRow.Index;//获取当前选中行的索引
  1328. ShowDefectItemInfo(list[liIndex]);
  1329. }
  1330. #endregion
  1331. #region 光设置
  1332. private void TrackBarLightValue_ValueChanged(object sender, EventArgs e)
  1333. {
  1334. UCTrackBar trackBar = (UCTrackBar)sender;
  1335. if (trackBar.Name == "TrackBarLightValue")
  1336. {
  1337. numericUpDown1.Value = (decimal)trackBar.Value;
  1338. }
  1339. else if (trackBar.Name == "TrackBarExposureTime")
  1340. {
  1341. numericUpDown2.Value = (decimal)trackBar.Value;
  1342. }
  1343. else if (trackBar.Name == "TrackBarGain")
  1344. {
  1345. numericUpDown3.Value = (decimal)trackBar.Value;
  1346. }
  1347. }
  1348. private void numericUpDown1_ValueChanged(object sender, EventArgs e)
  1349. {
  1350. NumericUpDown num = (NumericUpDown)sender;
  1351. if (num.Name == "numericUpDown1")
  1352. {
  1353. TrackBarLightValue.Value = (float)num.Value > TrackBarLightValue.MaxValue ? TrackBarLightValue.MaxValue : (float)num.Value;
  1354. }
  1355. else if (num.Name == "numericUpDown2")
  1356. {
  1357. TrackBarExposureTime.Value = (float)num.Value > TrackBarExposureTime.MaxValue ? TrackBarExposureTime.MaxValue : (float)num.Value;
  1358. }
  1359. else if (num.Name == "numericUpDown3")
  1360. {
  1361. TrackBarGain.Value = (float)num.Value > TrackBarGain.MaxValue ? TrackBarGain.MaxValue : (float)num.Value;
  1362. }
  1363. }
  1364. #endregion
  1365. #region 模型加载
  1366. private void cmbDefectModelFile_TextChanged(object sender, EventArgs e)
  1367. {
  1368. try
  1369. {
  1370. string modeljson = cmbDefectModelFile.Text.Replace(".trt", ".json");
  1371. //加载缺陷
  1372. string configPath = ConfMgr.Instance.SysConfigParams.AIModelPath + $"\\{modeljson}";
  1373. string lsTmp = File.ReadAllText(configPath);
  1374. JArray defectItemList = JArray.Parse(lsTmp);
  1375. //加行
  1376. dataGridView3.Rows.Clear();
  1377. dataGridView4.Rows.Clear();
  1378. cbDefectName.Items.Clear();
  1379. foreach (JObject item in defectItemList)
  1380. {
  1381. string code = item.Value<string>("code");
  1382. string name = item.Value<string>("name");
  1383. //color = item.Value<string>("color");
  1384. dataGridView3.Rows.Add();
  1385. dataGridView3.Rows[dataGridView3.RowCount - 1].HeaderCell.Value = name;
  1386. dataGridView3[0, dataGridView3.RowCount - 1].Value = code;
  1387. dataGridView4.Rows.Add();
  1388. dataGridView4.Rows[dataGridView4.RowCount - 1].HeaderCell.Value = name;
  1389. dataGridView4[0, dataGridView4.RowCount - 1].Value = code;
  1390. cbDefectName.Items.Add(name);
  1391. }
  1392. //模型是否是产品模型
  1393. if (_model.ModelName == cmbDefectModelFile.Text)
  1394. {
  1395. //加载参数
  1396. string code;
  1397. QualifiedLimit item1;
  1398. for (int i = 0; i < dataGridView3.Rows.Count; i++)
  1399. {
  1400. code = dataGridView3.Rows[i].Cells["Code"].Value.ToString();
  1401. item1 = _model.QualifiedLimitList.FirstOrDefault(m => m.Code == code);
  1402. if (item1 != null)
  1403. {
  1404. dataGridView3.Rows[i].Cells["ZXD"].Value = item1.ZXD;
  1405. dataGridView3.Rows[i].Cells["Area"].Value = item1.Area;
  1406. dataGridView3.Rows[i].Cells["DBDH"].Value = Utils.ContrastToPercent(item1.ContrastTop);
  1407. dataGridView3.Rows[i].Cells["DBDL"].Value = Utils.ContrastToPercent(item1.ContrastLower);
  1408. dataGridView3.Rows[i].Cells["OrAnd"].Value = item1.IsOR;
  1409. dataGridView3.Rows[i].Cells["DefectLength"].Value = item1.DefectWarnLength;
  1410. dataGridView3.Rows[i].Cells["DefectWarn"].Value = item1.DefectWarnCnt;
  1411. }
  1412. else
  1413. {
  1414. dataGridView3.Rows[i].Cells["ZXD"].Value = 0.4;
  1415. dataGridView3.Rows[i].Cells["Area"].Value = 2;
  1416. dataGridView3.Rows[i].Cells["DBDH"].Value = 51;
  1417. dataGridView3.Rows[i].Cells["DBDL"].Value = 49;
  1418. dataGridView3.Rows[i].Cells["OrAnd"].Value = false;
  1419. dataGridView3.Rows[i].Cells["DefectLength"].Value = 0;
  1420. dataGridView3.Rows[i].Cells["DefectWarn"].Value = 0;
  1421. }
  1422. }
  1423. GradeLimit item2;
  1424. for (int i = 0; i < dataGridView4.Rows.Count; i++)
  1425. {
  1426. code = dataGridView4.Rows[i].Cells["Code2"].Value.ToString();
  1427. item2 = _model.GradeLimitList.FirstOrDefault(m => m.Code == code);
  1428. if (item2 != null)
  1429. {
  1430. dataGridView4.Rows[i].Cells["A"].Value = item2.A;
  1431. dataGridView4.Rows[i].Cells["B"].Value = item2.B;
  1432. dataGridView4.Rows[i].Cells["C"].Value = item2.C;
  1433. dataGridView4.Rows[i].Cells["D"].Value = item2.D;
  1434. dataGridView4.Rows[i].Cells["E"].Value = item2.E;
  1435. }
  1436. }
  1437. }
  1438. else
  1439. {
  1440. //加载默认参数
  1441. string code;
  1442. QualifiedLimit item1;
  1443. for (int i = 0; i < dataGridView3.Rows.Count; i++)
  1444. {
  1445. dataGridView3.Rows[i].Cells["ZXD"].Value = 0.4;
  1446. dataGridView3.Rows[i].Cells["Area"].Value = 2;
  1447. dataGridView3.Rows[i].Cells["DBDH"].Value = 51;
  1448. dataGridView3.Rows[i].Cells["DBDL"].Value = 49;
  1449. dataGridView3.Rows[i].Cells["OrAnd"].Value = false;
  1450. dataGridView3.Rows[i].Cells["DefectLength"].Value = 0;
  1451. dataGridView3.Rows[i].Cells["DefectWarn"].Value = 0;
  1452. }
  1453. GradeLimit item2;
  1454. for (int i = 0; i < dataGridView4.Rows.Count; i++)
  1455. {
  1456. dataGridView4.Rows[i].Cells["A"].Value = 0;
  1457. dataGridView4.Rows[i].Cells["B"].Value = 0;
  1458. dataGridView4.Rows[i].Cells["C"].Value = 0;
  1459. dataGridView4.Rows[i].Cells["D"].Value = 0;
  1460. dataGridView4.Rows[i].Cells["E"].Value = 0;
  1461. }
  1462. }
  1463. }
  1464. catch (Exception ex)
  1465. {
  1466. MessageBox.Show("载入出错:" + ex.Message, "警告");
  1467. }
  1468. }
  1469. #endregion
  1470. #region 标准设置
  1471. private void btnCelDefect_Click(object sender, EventArgs e)
  1472. {
  1473. panel_jcbz.Visible = false;
  1474. }
  1475. private void btnSaveDefect_Click(object sender, EventArgs e)
  1476. {
  1477. try
  1478. {
  1479. if (this.cmbClasses.SelectedIndex < 0) throw new Exception("请选择材质!");
  1480. if (string.IsNullOrEmpty(this.txtName.Text)) throw new Exception("请填写名称!");
  1481. if (string.IsNullOrEmpty(this.tbColorName.Text)) throw new Exception("请填写颜色!");
  1482. if (this.cmbDefectModelFile.SelectedIndex < 0) throw new Exception("请选择模型!");
  1483. if (this.cbEdgeDefect.SelectedIndex < 0) throw new Exception("请选择寻边算法!");
  1484. if (this.cbImageDefet.SelectedIndex < 0) throw new Exception("请选择识别算法!");
  1485. _model.Code = $"2.0-{txtName.Text}-{cmbClasses.Text}";
  1486. //_model.Color = (int)numColorNo.Value;
  1487. _model.Name = txtName.Text;
  1488. _model.Material = cmbClasses.Text;
  1489. _model.ColorName = tbColorName.Text;
  1490. _model.ModelName = cmbDefectModelFile.Text;
  1491. _model.EdgeHoleCut = (int)numHoldCut.Value;
  1492. _model.EdgeDefectType = cbEdgeDefect.Text;
  1493. _model.ImageDefectType = cbImageDefet.Text;
  1494. //_model.Spec = tbSpec.Text;
  1495. _model.LightValue = (int)TrackBarLightValue.Value;
  1496. _model.ExposureTime = (double)TrackBarExposureTime.Value;
  1497. _model.Gain = (double)TrackBarGain.Value;
  1498. //model.OpenThicknessDetection = cbGetHD.Checked;
  1499. //model.ThicknessDetectionStopDis = (int)numStopDis.Value;
  1500. //model.DefectAreaLimit = (int)numDefectAreaLimit.Value;
  1501. //model.DefectCntLength = (double)numDefectCntLength.Value;
  1502. //model.DefectCountLimit = (int)numDefectCountLimit.Value;
  1503. //model.WarnDefect = tbWarnDefect.Text;
  1504. //model.residueWarnningLen = (double)numReelLen.Value;
  1505. //缺陷阈值
  1506. if (_model.QualifiedLimitList == null)
  1507. _model.QualifiedLimitList = new List<Models.QualifiedLimit>();
  1508. else
  1509. _model.QualifiedLimitList.Clear();
  1510. QualifiedLimit qualifiedLimit = new QualifiedLimit();
  1511. string modeljson = cmbDefectModelFile.Text.Replace(".trt", ".json");
  1512. string configPath = ConfMgr.Instance.SysConfigParams.AIModelPath + $"\\{modeljson}";
  1513. string lsTmp = File.ReadAllText(configPath);
  1514. JArray defectItemList = JArray.Parse(lsTmp);
  1515. for (int i = 0; i < dataGridView3.Rows.Count; i++)
  1516. {
  1517. string code2 = dataGridView3.Rows[i].Cells["Code"].Value.ToString();
  1518. string nameCode = defectItemList.FirstOrDefault(x => x.Value<string>("code") == code2).Value<string>("name");
  1519. qualifiedLimit = new Models.QualifiedLimit()
  1520. {
  1521. Code = dataGridView3.Rows[i].Cells["Code"].Value.ToString(),
  1522. ZXD = Utils.IsDecimal(dataGridView3.Rows[i].Cells["ZXD"].Value) ? Convert.ToDouble(dataGridView3.Rows[i].Cells["ZXD"].Value) : 0,
  1523. Area = Utils.IsDecimal(dataGridView3.Rows[i].Cells["Area"].Value) ? Convert.ToDouble(dataGridView3.Rows[i].Cells["Area"].Value) : 0,
  1524. ContrastLower = Utils.IsDecimal(dataGridView3.Rows[i].Cells["DBDL"].Value) ? Utils.PercentToContrast(Convert.ToDouble(dataGridView3.Rows[i].Cells["DBDL"].Value)) : 0,
  1525. ContrastTop = Utils.IsDecimal(dataGridView3.Rows[i].Cells["DBDH"].Value) ? Utils.PercentToContrast(Convert.ToDouble(dataGridView3.Rows[i].Cells["DBDH"].Value)) : 0,
  1526. IsOR = Convert.ToBoolean(dataGridView3.Rows[i].Cells["OrAnd"].Value),
  1527. NameCode = nameCode,
  1528. DefectWarnLength = Utils.IsNumber(dataGridView3.Rows[i].Cells["DefectLength"].Value) ? Convert.ToInt32(dataGridView3.Rows[i].Cells["DefectLength"].Value) : 0,
  1529. DefectWarnCnt = Utils.IsDecimal(dataGridView3.Rows[i].Cells["DefectWarn"].Value) ? Convert.ToInt32(dataGridView3.Rows[i].Cells["DefectWarn"].Value) : 0,
  1530. ModifyUserCode = SysMgr.Instance.UserMgr.LoginUser.Code,
  1531. CreateUserCode = SysMgr.Instance.UserMgr.LoginUser.Code
  1532. };
  1533. if (qualifiedLimit.ContrastLower + qualifiedLimit.ContrastTop > 0 && qualifiedLimit.ContrastTop < qualifiedLimit.ContrastLower)
  1534. throw new Exception($"检测标准中第{i + 1}行中对比度上限值({qualifiedLimit.ContrastTop})不可小于下限值({qualifiedLimit.ContrastLower})!");
  1535. _model.QualifiedLimitList.Add(qualifiedLimit);
  1536. }
  1537. //产品等级
  1538. if (_model.GradeLimitList == null)
  1539. _model.GradeLimitList = new List<Models.GradeLimit>();
  1540. else
  1541. _model.GradeLimitList.Clear();
  1542. for (int i = 0; i < dataGridView4.Rows.Count; i++)
  1543. {
  1544. _model.GradeLimitList.Add(
  1545. new Models.GradeLimit()
  1546. {
  1547. Code = dataGridView4.Rows[i].Cells["Code2"].Value.ToString(),
  1548. A = Utils.IsNumber(dataGridView4.Rows[i].Cells["A"].Value) ? Convert.ToInt32(dataGridView4.Rows[i].Cells["A"].Value) : 0,
  1549. B = Utils.IsNumber(dataGridView4.Rows[i].Cells["B"].Value) ? Convert.ToInt32(dataGridView4.Rows[i].Cells["B"].Value) : 0,
  1550. C = Utils.IsNumber(dataGridView4.Rows[i].Cells["C"].Value) ? Convert.ToInt32(dataGridView4.Rows[i].Cells["C"].Value) : 0,
  1551. D = Utils.IsNumber(dataGridView4.Rows[i].Cells["D"].Value) ? Convert.ToInt32(dataGridView4.Rows[i].Cells["D"].Value) : 0,
  1552. E = Utils.IsNumber(dataGridView4.Rows[i].Cells["E"].Value) ? Convert.ToInt32(dataGridView4.Rows[i].Cells["E"].Value) : 0,
  1553. ModifyUserCode = SysMgr.Instance.UserMgr.LoginUser.Code,
  1554. CreateUserCode = SysMgr.Instance.UserMgr.LoginUser.Code
  1555. });
  1556. }
  1557. //
  1558. _model.ModifyUserCode = SysMgr.Instance.UserMgr.LoginUser.Code;
  1559. bool result;
  1560. bool IsAdd = false;
  1561. if (_model.Id == 0)
  1562. {
  1563. _model.CreateUserCode = SysMgr.Instance.UserMgr.LoginUser.Code;
  1564. result = SysMgr.Instance.AddDefectItem(_model);
  1565. IsAdd = true;
  1566. }
  1567. else
  1568. {
  1569. result = SysMgr.Instance.UpdateDefectItem(_model);
  1570. }
  1571. if (!result)
  1572. throw new Exception("数据保存失败!");
  1573. else
  1574. {
  1575. if(IsAdd)
  1576. InitDefectListDataView();
  1577. MessageBox.Show("保存成功!", "保存");
  1578. panel_jcbz.Visible = false;
  1579. }
  1580. }
  1581. catch (Exception ex)
  1582. {
  1583. MessageBox.Show("保存出错:" + ex.Message, "警告");
  1584. }
  1585. }
  1586. #endregion
  1587. #region 颜色选择
  1588. private void btnColor_Click(object sender, EventArgs e)
  1589. {
  1590. ColorDialog dlg = new ColorDialog();
  1591. DialogResult result = dlg.ShowDialog();
  1592. if (result == DialogResult.OK)
  1593. {
  1594. // 获取用户所选颜色
  1595. Color selectedColor = dlg.Color;
  1596. // 在 label1 中显示所选颜色的 RGB 值
  1597. tbColorName.Text = SysMgr.CLRToName(selectedColor);
  1598. tbColorName.ForeColor = selectedColor;
  1599. }
  1600. }
  1601. #endregion
  1602. #endregion
  1603. #region 数据分析界面
  1604. #region 表格事件
  1605. private void uiDataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
  1606. {
  1607. var list = uiDataGridView1.DataSource as List<Records>;
  1608. for (int i = 0; i < uiDataGridView1.Rows.Count; i++)
  1609. {
  1610. if (list[i].Grade < 1)
  1611. uiDataGridView1.Rows[i].Cells["colGrade"].Value = "";
  1612. else if (list[i].Grade <= 5)
  1613. uiDataGridView1.Rows[i].Cells["colGrade"].Value = (char)(list[i].Grade + 64);
  1614. else
  1615. uiDataGridView1.Rows[i].Cells["colGrade"].Value = "不合格";
  1616. //if (list[i].RoleInfo != null)
  1617. // uiDataGridView1.Rows[i].Cells["colRoleName"].Value = list[i].RoleInfo.Name;
  1618. }
  1619. }
  1620. #endregion
  1621. #region 数据查询
  1622. private Expression<Func<Records, bool>> createQueryExpression()
  1623. {
  1624. return Expressionable.Create<Records>()
  1625. .And(it => it.CreateTime >= uiDatePicker1.Value.Date)
  1626. .And(it => it.CreateTime < uiDatePicker2.Value.Date.AddDays(1))
  1627. .AndIF(!string.IsNullOrWhiteSpace(txtBarcode.Text), it => it.BarCode.Contains(txtBarcode.Text.Trim()))
  1628. .ToExpression();//注意 这一句 不能少
  1629. }
  1630. private void btnSelectData_Click(object sender, EventArgs e)
  1631. {
  1632. pageCtrl1.PageIndex = 1;
  1633. QueryData();
  1634. }
  1635. private void QueryData()
  1636. {
  1637. //未连接数据库,通过模拟数据来实现
  1638. //一般通过ORM的分页去取数据来填充
  1639. //pageIndex:第几页,和界面对应,从1开始,取数据可能要用pageIndex
  1640. //count:单页数据量,也就是PageSize值
  1641. int count = this.pageCtrl1.PageSize;
  1642. int totalCount = 0;
  1643. var list = SysMgr.Instance.GetRecords(pageCtrl1.PageIndex, count, ref totalCount, createQueryExpression());
  1644. uiDataGridView1.DataSource = list;
  1645. pageCtrl1.RecordCount = totalCount;
  1646. this.pageCtrl1.DrawControl(totalCount);
  1647. }
  1648. #endregion
  1649. #region 数据导出
  1650. private void btnExcel_Click(object sender, EventArgs e)
  1651. {
  1652. try
  1653. {
  1654. if (this.uiDataGridView1.CurrentRow == null)
  1655. return;
  1656. Models.Records record = SysMgr.Instance.GetRecord(int.Parse(this.uiDataGridView1.CurrentRow.Cells[0].Value.ToString()));
  1657. if (record.DefectInfoList.Count < 0)
  1658. throw new Exception("当前记录无缺陷!");
  1659. string path = ConfMgr.SelectFolder();
  1660. if (string.IsNullOrWhiteSpace(path))
  1661. return;
  1662. //var list = uiDataGridView1.DataSource as List<Records>;
  1663. //var table = ExcelUtil.ConvertToDataTable<Records>(list);
  1664. //{ 名称=x.Name,Xcm=x.X,Ym=x.Y/100,宽cm=x.Width,高cm=x.Height,面积=x.Area, 置信度 =x.ZXD}
  1665. var list = record.DefectInfoList;//.Select(x => new { x.Name,x.X,x.Y,x.Width,x.Height,x.Area, x.ZXD}).ToList();
  1666. //绘图1
  1667. double len = Math.Round(record.Len * 100, 2);//cm
  1668. this.reDrawDefectPoints(record, new double[] { 0, Math.Round(record.FaceWidthMax + 0.005f, 2) }, new double[] { 0, len });
  1669. //绘图2
  1670. //var points = Array.ConvertAll(record.FaceWidthListStr.Split(new[] { ',', }, StringSplitOptions.RemoveEmptyEntries),Double.Parse).ToList();
  1671. //reDrawFaceWidth(record.FacePointList,
  1672. // new double[] { 0, Math.Round(len + 0.005f, 2) },
  1673. // new double[] { record.FaceWidthMin, Math.Round(record.FaceWidthMax + 0.005f, 2) });
  1674. reDrawFaceWidth(record.FacePointList,
  1675. new double[] { 0, Math.Round(len + 0.005f, 2) },
  1676. new double[] { 130, 160 });
  1677. //
  1678. foreach (var item in list)
  1679. {
  1680. item.Name = SysMgr.Instance.GetDefectName(record.ProductInfo.ModelName, item.Code);
  1681. //item.Height = item.Height / 100; //单位错误,保证单位一致
  1682. }
  1683. //
  1684. string Grade = "";
  1685. if (record.Grade < 1) Grade = "";
  1686. else if (record.Grade <= 5) Grade = (char)(record.Grade + 64) + "";
  1687. else Grade = "不合格";
  1688. JsonProductDefects data = new JsonProductDefects()
  1689. {
  1690. ProName = record.BarCodeName,
  1691. BatchId = record.BatchId,
  1692. ReelId = record.ReelId,
  1693. Len = record.Len.ToString(),
  1694. Speed = Math.Round(record.Len / record.TimeLen, 2).ToString(),
  1695. Grade = Grade,
  1696. DateTime = record.CreateTime.ToString("yyyy年MM月dd日 HH:mm")
  1697. };
  1698. data.DefectTotal = record.DefectInfoList.GroupBy(x => x.Name).Select(g => new JDefectTotal { Name = g.Key, Count = g.Count() }).ToList();
  1699. data.DefectDetail = record.DefectInfoList.Select(x => new JDefectDetail
  1700. {
  1701. Index = x.PhotoIndex,
  1702. Name = x.Name,
  1703. X = x.X,
  1704. Y = Math.Round(x.Y / 100.0d, 2),
  1705. Width = x.Width * 10,
  1706. Height = x.Height * 10,
  1707. ZXD = x.ZXD,
  1708. Area = x.Area * 100,
  1709. Contrast = x.Contrast
  1710. })
  1711. .OrderBy(x => x.Index).ThenBy(x => x.Y).ToList();
  1712. data.Pdt = SysMgr.Instance.GteDefectItem(record.ProductId);
  1713. data.xyPix = $"X:{ConfMgr.Instance.SysConfigParams.Cm2px_x},Y:{ConfMgr.Instance.SysConfigParams.Cm2px_y}";
  1714. var image1 = captureControl(this.lineChartDefect);
  1715. var image2 = captureControl(this.lineChartFaceWidth);
  1716. var filePath = $"{path}缺陷列表_{record.BarCode}_{record.BarCodeName}.xlsx";
  1717. exportTabel(data, image1, image2, filePath, record.ProductInfo.ModelName);
  1718. //if (!res)
  1719. // throw new Exception("导出失败!");
  1720. MessageBox.Show("导出成功!", "导出完成");
  1721. System.Diagnostics.Process.Start(filePath);
  1722. }
  1723. catch (Exception ex)
  1724. {
  1725. MessageBox.Show($"{ex.Message}", "导出失败");
  1726. //UIMessageTip.ShowError(ex.Message, 2000);
  1727. //API.OutputDebugString(ex.StackTrace);
  1728. }
  1729. }
  1730. #region 切页
  1731. /// <summary>
  1732. /// 页数变化时调用绑定数据方法
  1733. /// </summary>
  1734. /// <param name="sender"></param>
  1735. /// <param name="e"></param>
  1736. private void pagerControl1_OnPageChanged(object sender, EventArgs e)
  1737. {
  1738. QueryData();
  1739. }
  1740. #endregion
  1741. #region 数据图形操作
  1742. public void exportTabel(JsonProductDefects ProductDefects, byte[] defectImage, byte[] faceWidthImage, string savePath, string modelName)
  1743. {
  1744. //try
  1745. //{
  1746. if (ProductDefects == null)
  1747. throw new Exception("传入的参数为空");
  1748. using (var workbook = new XLWorkbook())
  1749. {
  1750. var wsDefectsDetail = workbook.Worksheets.Add("正面疵点列表");
  1751. wsDefectsDetail.RowHeight = 20;
  1752. wsDefectsDetail.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
  1753. wsDefectsDetail.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;
  1754. wsDefectsDetail.Style.Font.FontName = "宋体";
  1755. wsDefectsDetail.Column("A").Width = 12;
  1756. wsDefectsDetail.Column("B").Width = 25;
  1757. wsDefectsDetail.Column("C").Width = 10;
  1758. wsDefectsDetail.Column("D").Width = 10;
  1759. wsDefectsDetail.Column("E").Width = 10;
  1760. wsDefectsDetail.Column("F").Width = 10;
  1761. wsDefectsDetail.Column("G").Width = 12;
  1762. wsDefectsDetail.Column("H").Width = 14;
  1763. wsDefectsDetail.Column("I").Width = 14;
  1764. int rowIndex = 1;
  1765. int cellIndex = 1;
  1766. #region 第一行
  1767. var row1_cell1 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex);
  1768. row1_cell1.Value = "产品疵点缺陷分布图表";
  1769. row1_cell1.Style.Font.Bold = true;
  1770. //row1_cell1.Style.Font.FontName = "宋体";
  1771. row1_cell1.Style.Font.FontSize = 12;
  1772. var mergeRange_row1 = wsDefectsDetail.Range("A1:I1").Row(1).Merge();
  1773. mergeRange_row1.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1774. #endregion
  1775. #region 第二行
  1776. rowIndex++;
  1777. var row2_cell1 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex);
  1778. row2_cell1.Value = "产品品名";
  1779. row2_cell1.Style.Font.Bold = true;
  1780. row2_cell1.Style.Font.FontSize = 10;
  1781. row2_cell1.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1782. var row2_cell2 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 1);
  1783. row2_cell2.DataType = XLDataType.Text;
  1784. row2_cell2.Value = ProductDefects.ProName;
  1785. row2_cell2.Style.Font.FontSize = 10;
  1786. row2_cell2.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1787. var row2_cell3 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 2);
  1788. row2_cell3.Value = "产品批号";
  1789. row2_cell3.Style = row2_cell1.Style;
  1790. var row2_cell4 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 3);
  1791. row2_cell4.Value = "'" + ProductDefects.BatchId;
  1792. row2_cell4.Style = row2_cell2.Style;
  1793. var row2_cell5 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 4);
  1794. row2_cell5.Value = "产品卷号";
  1795. row2_cell5.Style = row2_cell1.Style;
  1796. var row2_cell6 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 5);
  1797. //row2_cell6.SetDataType(XLDataType.Text);//类型设置不起作用 用"'"+内容代替
  1798. //row2_cell6.DataType = XLDataType.Text;
  1799. row2_cell6.Value = "'" + ProductDefects.ReelId;
  1800. row2_cell6.Style = row2_cell2.Style;
  1801. var row2_cell7 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 6);
  1802. row2_cell7.Value = "长度(米)";
  1803. row2_cell7.Style = row2_cell1.Style;
  1804. var row2_cell8 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 7);
  1805. row2_cell8.Value = ProductDefects.Len;
  1806. row2_cell8.Style = row2_cell2.Style;
  1807. //NULL
  1808. var row2_cell9 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 8);
  1809. row2_cell9.Style = row2_cell2.Style;
  1810. #endregion
  1811. #region 第三行
  1812. rowIndex++;
  1813. var row3_cell1 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex);
  1814. row3_cell1.Value = "检验时间";
  1815. row3_cell1.Style = row2_cell1.Style;
  1816. var row3_cell2 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 1);
  1817. row3_cell2.Value = "'" + ProductDefects.DateTime;
  1818. row3_cell2.Style = row2_cell2.Style;
  1819. var row3_cell3 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 2);
  1820. row3_cell3.Value = "检验长度";
  1821. row3_cell3.Style = row2_cell1.Style;
  1822. var row3_cell4 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 3);
  1823. row3_cell4.Value = ProductDefects.Len;
  1824. row3_cell4.Style = row2_cell2.Style;
  1825. var row3_cell5 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 4);
  1826. row3_cell5.Value = "平均速度";
  1827. row3_cell5.Style = row2_cell1.Style;
  1828. var row3_cell6 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 5);
  1829. row3_cell6.Value = ProductDefects.Speed;
  1830. row3_cell6.Style = row2_cell2.Style;
  1831. var row3_cell7 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 6);
  1832. row3_cell7.Value = "等级";
  1833. row3_cell7.Style = row2_cell1.Style;
  1834. var row3_cell8 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 7);
  1835. row3_cell8.Value = ProductDefects.Grade;
  1836. row3_cell8.Style = row2_cell2.Style;
  1837. var row3_cell9 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 8);
  1838. row3_cell9.Style = row2_cell2.Style;
  1839. #endregion
  1840. #region 第四第五行
  1841. rowIndex++;
  1842. var row4_cell1 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex);
  1843. row4_cell1.Value = "设备参数";
  1844. row4_cell1.Style = row2_cell1.Style;
  1845. row4_cell1.Style.Font.Bold = true;
  1846. row4_cell1.Style.Font.FontSize = 10;
  1847. row4_cell1.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1848. var mergeRange_row4 = wsDefectsDetail.Range("A4:A5").Column(1).Merge();
  1849. mergeRange_row4.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1850. var row4_cell2 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 1);
  1851. row4_cell2.Value = "光源亮度";
  1852. row4_cell2.Style = row2_cell1.Style;
  1853. var row4_cell3 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 2);
  1854. row4_cell3.Value = "曝光时间";
  1855. row4_cell3.Style = row2_cell1.Style;
  1856. var row4_cell4 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 3);
  1857. row4_cell4.Value = "增益";
  1858. row4_cell4.Style = row2_cell1.Style;
  1859. var row4_cell5 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 4);
  1860. row4_cell5.Value = "行频比";
  1861. row4_cell5.Style = row2_cell1.Style;
  1862. var row4_cell6 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 5);
  1863. row4_cell6.Value = "物面分辨率";
  1864. row4_cell6.Style = row2_cell1.Style;
  1865. var row4_cell7 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 6);
  1866. row4_cell7.Value = "触发计数";
  1867. row4_cell7.Style = row2_cell1.Style;
  1868. var row4_cell8 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 7);
  1869. row4_cell8.Value = "采集计数";
  1870. row4_cell8.Style = row2_cell1.Style;
  1871. var row4_cell9 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 8);
  1872. row4_cell9.Value = "";
  1873. row4_cell9.Style = row2_cell1.Style;
  1874. rowIndex++;
  1875. var row5_cell2 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 1);
  1876. row5_cell2.Value = ProductDefects.Pdt.LightValue;
  1877. row5_cell2.Style = row2_cell1.Style;
  1878. var row5_cell3 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 2);
  1879. row5_cell3.Value = ProductDefects.Pdt.ExposureTime;
  1880. row5_cell3.Style = row2_cell1.Style;
  1881. var row5_cell4 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 3);
  1882. row5_cell4.Value = ProductDefects.Pdt.Gain;
  1883. row5_cell4.Style = row2_cell1.Style;
  1884. var row5_cell5 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 4);
  1885. row5_cell5.Value = "";
  1886. row5_cell5.Style = row2_cell1.Style;
  1887. var row5_cell6 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 5);
  1888. row5_cell6.Value = ProductDefects.xyPix;
  1889. row5_cell6.Style = row2_cell1.Style;
  1890. var row5_cell7 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 6);
  1891. row5_cell7.Value = "";
  1892. row5_cell7.Style = row2_cell1.Style;
  1893. var row5_cell8 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 7);
  1894. row5_cell8.Value = "";
  1895. row5_cell8.Style = row2_cell1.Style;
  1896. var row5_cell9 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 8);
  1897. row5_cell9.Value = "";
  1898. row5_cell9.Style = row2_cell1.Style;
  1899. #endregion
  1900. #region 第六行后
  1901. rowIndex++;
  1902. if (ProductDefects.DefectTotal != null && ProductDefects.DefectTotal.Count > 0)
  1903. {
  1904. cellIndex = 1;
  1905. int DefectTotalCount = ProductDefects.DefectTotal.Count;
  1906. //最少5行,固定4列
  1907. var row6_cell1 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex);
  1908. row6_cell1.Value = "检测参数";
  1909. row6_cell1.Style.Font.Bold = true;
  1910. row6_cell1.Style.Font.FontSize = 10;
  1911. row6_cell1.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1912. string cellstr = $"A6:A{7 + ProductDefects.DefectTotal.Count}";
  1913. var mergeRange_row6 = wsDefectsDetail.Range(cellstr).Column(1).Merge();
  1914. mergeRange_row6.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1915. var row6_cell2 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 1);
  1916. row6_cell2.Value = "筛选标准";
  1917. row6_cell2.Style.Font.Bold = true;
  1918. row6_cell2.Style.Font.FontSize = 10;
  1919. row6_cell2.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1920. var mergeRange_row6_2 = wsDefectsDetail.Range($"B6:I6").Row(1).Merge();
  1921. mergeRange_row6_2.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1922. //第七行
  1923. rowIndex++;
  1924. var row7_cell2 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 1);
  1925. row7_cell2.Value = "缺陷类型";
  1926. row7_cell2.Style = row2_cell1.Style;
  1927. var row7_cell3 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 2);
  1928. row7_cell3.Value = "置信度";
  1929. row7_cell3.Style = row2_cell1.Style;
  1930. var row7_cell4 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 3);
  1931. row7_cell4.Value = "面积";
  1932. row7_cell4.Style = row2_cell1.Style;
  1933. var row7_cell5 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 4);
  1934. row7_cell5.Value = "对比度下限";
  1935. row7_cell5.Style = row2_cell1.Style;
  1936. var row7_cell6 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 5);
  1937. row7_cell6.Value = "对比度上限";
  1938. row7_cell6.Style = row2_cell1.Style;
  1939. var row7_cell7 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 6);
  1940. row7_cell7.Value = "所用模型版本";
  1941. row7_cell7.Style = row2_cell1.Style;
  1942. var row7_cell8 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 7);
  1943. row7_cell8.Value = "或向选择";
  1944. row7_cell8.Style = row2_cell1.Style;
  1945. var row7_cell9 = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + 8);
  1946. row7_cell9.Value = "本次检出数量";
  1947. row7_cell9.Style = row2_cell1.Style;
  1948. //第八行之后
  1949. rowIndex++;
  1950. for (int j = 1; j <= ProductDefects.DefectTotal.Count; j++) // 行
  1951. {
  1952. var temprowcel2 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 1);
  1953. var temprowcel3 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 2);
  1954. var temprowcel4 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 3);
  1955. var temprowcel5 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 4);
  1956. var temprowcel6 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 5);
  1957. var temprowcel7 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 6);
  1958. var temprowcel8 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 7);
  1959. var temprowcel9 = wsDefectsDetail.Row(rowIndex + j - 1).Cell(cellIndex + 8);
  1960. var tempItemDefectTotal = ProductDefects.DefectTotal[j - 1];
  1961. temprowcel2.Value = tempItemDefectTotal.Name;
  1962. temprowcel2.Style.Font.Bold = true;
  1963. temprowcel2.Style.Font.FontSize = 10;
  1964. temprowcel2.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1965. var temp = ProductDefects.Pdt.QualifiedLimitList.Find(x => SysMgr.Instance.GetDefectName(modelName, x.Code) == tempItemDefectTotal.Name);
  1966. temprowcel3.Value = temp.ZXD;
  1967. temprowcel3.Style.Font.Bold = true;
  1968. temprowcel3.Style.Font.FontSize = 10;
  1969. temprowcel3.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1970. temprowcel4.Value = temp.Area;
  1971. temprowcel4.Style.Font.Bold = true;
  1972. temprowcel4.Style.Font.FontSize = 10;
  1973. temprowcel4.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1974. temprowcel5.Value = ContrastToPercent(temp.ContrastLower);
  1975. temprowcel5.Style.Font.Bold = true;
  1976. temprowcel5.Style.Font.FontSize = 10;
  1977. temprowcel5.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1978. temprowcel6.Value = ContrastToPercent(temp.ContrastTop);
  1979. temprowcel6.Style.Font.Bold = true;
  1980. temprowcel6.Style.Font.FontSize = 10;
  1981. temprowcel6.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1982. temprowcel7.Value = ProductDefects.Pdt.ModelName;
  1983. temprowcel7.Style.Font.Bold = true;
  1984. temprowcel7.Style.Font.FontSize = 10;
  1985. temprowcel7.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1986. temprowcel8.Value = temp.IsOR;
  1987. temprowcel8.Style.Font.Bold = true;
  1988. temprowcel8.Style.Font.FontSize = 10;
  1989. temprowcel8.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1990. temprowcel9.Value = tempItemDefectTotal.Count;
  1991. temprowcel9.Style.Font.FontSize = 10;
  1992. temprowcel9.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  1993. }
  1994. //更新行号
  1995. rowIndex = rowIndex + ProductDefects.DefectTotal.Count;
  1996. }
  1997. #endregion
  1998. #region 最后
  1999. //rowIndex++;
  2000. if (ProductDefects.DefectDetail != null && ProductDefects.DefectDetail.Count > 0)
  2001. {
  2002. List<string> lstRow5str = new List<string>() { "源图", "名称", "X(cm)", "Y(米)", "宽(mm)", "高(mm)", "置信度", "面积(mm^2)", "对比度" };
  2003. for (int i = 0; i < lstRow5str.Count; i++)
  2004. {
  2005. var temp_row5_cell = wsDefectsDetail.Row(rowIndex).Cell(cellIndex + i);
  2006. temp_row5_cell.Value = lstRow5str[i];
  2007. temp_row5_cell.Style.Font.Bold = true;
  2008. temp_row5_cell.Style.Font.FontSize = 11;
  2009. temp_row5_cell.Style.Font.FontName = "等线";
  2010. temp_row5_cell.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  2011. }
  2012. rowIndex++;
  2013. for (int i = 0; i < ProductDefects.DefectDetail.Count; i++)
  2014. for (int j = 0; j < lstRow5str.Count; j++)
  2015. {
  2016. var temp_row6_cell = wsDefectsDetail.Row(rowIndex + i).Cell(cellIndex + j);
  2017. switch (lstRow5str[j])
  2018. {
  2019. case "源图":
  2020. temp_row6_cell.Value = ProductDefects.DefectDetail[i].Index;
  2021. break;
  2022. case "名称":
  2023. temp_row6_cell.Value = ProductDefects.DefectDetail[i].Name;
  2024. break;
  2025. case "X(cm)":
  2026. temp_row6_cell.Value = ProductDefects.DefectDetail[i].X;
  2027. break;
  2028. case "Y(米)":
  2029. temp_row6_cell.Value = ProductDefects.DefectDetail[i].Y;
  2030. break;
  2031. case "宽(mm)":
  2032. temp_row6_cell.Value = ProductDefects.DefectDetail[i].Width;
  2033. break;
  2034. case "高(mm)":
  2035. temp_row6_cell.Value = ProductDefects.DefectDetail[i].Height;
  2036. break;
  2037. case "置信度":
  2038. temp_row6_cell.Value = ProductDefects.DefectDetail[i].ZXD;
  2039. break;
  2040. case "面积(mm^2)":
  2041. temp_row6_cell.Value = ProductDefects.DefectDetail[i].Area;
  2042. break;
  2043. case "对比度":
  2044. temp_row6_cell.Value = ProductDefects.DefectDetail[i].Contrast;
  2045. break;
  2046. }
  2047. temp_row6_cell.Style.Font.FontSize = 11;
  2048. temp_row6_cell.Style.Font.FontName = "等线";
  2049. temp_row6_cell.Style.Border.OutsideBorder = XLBorderStyleValues.Thin;
  2050. }
  2051. // row6_cell1.InsertTable(ProductDefects.DefectDetail);
  2052. }
  2053. #endregion
  2054. var wsDefectsImg = workbook.Worksheets.Add("正面疵点分布图");
  2055. wsDefectsImg.AddPicture(new MemoryStream(defectImage), "纵向计算")
  2056. .MoveTo(wsDefectsImg.Cell(1, 1));
  2057. var wsFaceWidthImg = workbook.Worksheets.Add("门幅曲线");
  2058. wsFaceWidthImg.AddPicture(new MemoryStream(faceWidthImage), "幅宽曲线图")
  2059. .MoveTo(wsFaceWidthImg.Cell(1, 1));
  2060. workbook.SaveAs(savePath);
  2061. }
  2062. // return true;
  2063. //}
  2064. //catch (Exception ex)
  2065. //{
  2066. // return false;
  2067. //}
  2068. }
  2069. private double ContrastLow = 0.8;
  2070. private double ContrastTop = 1.2;
  2071. private double ContrastToPercent(double val)
  2072. {
  2073. if (val < ContrastLow)
  2074. return 0;
  2075. else if (val > ContrastTop)
  2076. return 100;
  2077. double temp = 100 / (ContrastTop - ContrastLow);
  2078. return Math.Round(temp * (val - ContrastLow), 2);
  2079. }
  2080. //
  2081. /// <summary>
  2082. /// 重新生成缺陷分布(cm2M在内部转换)
  2083. /// </summary>
  2084. /// <param name="lstDefectInfo">Records.DefectInfoList</param>
  2085. /// <param name="XSizeRange">幅宽</param>
  2086. /// <param name="YSizeRange">卷长度</param>
  2087. private void reDrawDefectPoints(Records records, double[] XSizeRange, double[] YSizeRange)
  2088. {
  2089. //AddTextEvent($"绘图", $"缺陷分布, W={string.Join(", ", XSizeRange)},H={string.Join(", ", YSizeRange)}, LastData={JsonConvert.SerializeObject(lstDefectInfo[lstDefectInfo.Count - 1])}");
  2090. var lstData = records.DefectInfoList.OrderBy(m => m.Code).ThenBy(m => m.Code).ToList();
  2091. if (XSizeRange == null || YSizeRange == null)
  2092. return;
  2093. else
  2094. {
  2095. if (YSizeRange[0] == YSizeRange[1])
  2096. {
  2097. YSizeRange[0] -= YSizeRange[0] / 10f;
  2098. YSizeRange[1] += YSizeRange[1] / 10f;
  2099. }
  2100. YSizeRange[0] /= 100;
  2101. YSizeRange[1] /= 100;
  2102. lineChartDefect.Series.Clear();
  2103. lineChartDefect.ChartAreas[0].AxisX.Title = "宽度(cm)";
  2104. lineChartDefect.ChartAreas[0].AxisY.Title = "长度(m)";
  2105. //option = new UILineOption();
  2106. //option.XAxis.Name = "面宽(cm)";
  2107. //option.YAxis.Name = "长度(米)";
  2108. //option.Grid.Top = 20;//边距
  2109. //option.Grid.Right = 20;//边距
  2110. foreach (var rowItem in lstData)
  2111. {
  2112. string name = SysMgr.Instance.GetDefectName(records.ProductInfo.ModelName, rowItem.Code);
  2113. if (lineChartDefect.Series.FindByName(name) == null)//rowItem[3] 为name
  2114. {
  2115. lineChartDefect.Series.Add(name);
  2116. var obj = SysMgr.Instance.GetDefectLabel(records.ProductInfo.ModelName, name);
  2117. int labelIndex = obj.Value<int>("id");
  2118. lineChartDefect.Series[name].ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point;
  2119. lineChartDefect.Series[name].MarkerSize = 5;
  2120. lineChartDefect.Series[name].MarkerColor = ChartColor[labelIndex];
  2121. lineChartDefect.Series[name].MarkerStyle = System.Windows.Forms.DataVisualization.Charting.MarkerStyle.Circle;
  2122. }
  2123. lineChartDefect.Series[name].Points.AddXY(rowItem.CentreX, rowItem.CentreY / 100);
  2124. }
  2125. lineChartDefect.ChartAreas[0].AxisX.Minimum = XSizeRange[0];
  2126. lineChartDefect.ChartAreas[0].AxisX.Maximum = XSizeRange[1];
  2127. lineChartDefect.ChartAreas[0].AxisY.Minimum = YSizeRange[0];
  2128. lineChartDefect.ChartAreas[0].AxisY.Maximum = YSizeRange[1];
  2129. //X轴数据类型
  2130. //option.XAxisType = UIAxisType.Value;
  2131. //设置X/Y轴显示范围
  2132. //option.XAxis.SetRange(XSizeRange[0], XSizeRange[1]);
  2133. //option.YAxis.SetRange(YSizeRange[0], YSizeRange[1]);
  2134. //坐标轴显示小数位数
  2135. //option.XAxis.AxisLabel.DecimalPlaces = option.YAxis.AxisLabel.DecimalPlaces = 1;
  2136. //X/Y轴画参考线
  2137. //option.YAxisScaleLines.Add(new UIScaleLine("上限", 3.5, Color.Red));
  2138. //option.YAxisScaleLines.Add(new UIScaleLine("下限", 2.2, Color.Gold));
  2139. //option.XAxisScaleLines.Add(new UIScaleLine(dt.AddHours(3).DateTimeString(), dt.AddHours(3), Color.Red));
  2140. //option.XAxisScaleLines.Add(new UIScaleLine(dt.AddHours(6).DateTimeString(), dt.AddHours(6), Color.Red));
  2141. //option.ToolTip.Visible = true;
  2142. //option.ToolTip.Formatter = "怎么自定义X,Y显示名称??{X}";
  2143. //option.Title = new UITitle();
  2144. //option.Title.Text = "";
  2145. //option.Title.SubText = "";
  2146. }
  2147. //string preCode = "";
  2148. //UILineSeries series = null;
  2149. //foreach (var item in lstData)
  2150. //{
  2151. // if (preCode != item.Code)//加一组新类型及样式
  2152. // {
  2153. // preCode = item.Code;
  2154. // var one = Config.getDefectItem(item.Code);
  2155. // if (one == null)
  2156. // {
  2157. // continue;
  2158. // }
  2159. // JObject objItem = one as JObject;
  2160. // Color color = ColorTranslator.FromHtml(objItem.Value<string>("color"));
  2161. // series = option.AddSeries(new UILineSeries(objItem.Value<string>("name"), color));//加一组
  2162. // series.Symbol = UILinePointSymbol.Star;
  2163. // series.SymbolSize = 4;
  2164. // series.SymbolLineWidth = 2;
  2165. // series.ShowLine = false;
  2166. // series.SymbolColor = color;
  2167. // //数据点显示小数位数(针对当前UILineSeries)
  2168. // series.XAxisDecimalPlaces = 1;
  2169. // series.YAxisDecimalPlaces = 2;
  2170. // //series.Smooth = false;
  2171. // }
  2172. // series.Add(item.CentreX, item.CentreY / 100); //cm -> m
  2173. //}
  2174. //====
  2175. //option.GreaterWarningArea = new UILineWarningArea(3.5);
  2176. //option.LessWarningArea = new UILineWarningArea(2.2, Color.Gold);
  2177. //this.BeginInvoke(new System.Action(() =>
  2178. //{
  2179. //this.lineChartDefect.SetOption(option);
  2180. //series.UpdateYData();//按序号更新Y轴值(可设置值超出范围用于闪烁)
  2181. //}));
  2182. }
  2183. /// <summary>
  2184. /// 重新门幅宽度
  2185. /// </summary>
  2186. /// <param name="points"></param>
  2187. /// <param name="XSizeRange">卷长度</param>
  2188. /// <param name="YSizeRange">幅宽</param>
  2189. private void reDrawFaceWidth(List<float[]> points, double[] XSizeRange, double[] YSizeRange)
  2190. {
  2191. //AddTextEvent($"绘图", $"门幅宽度, W={string.Join(", ", XSizeRange)},H={string.Join(", ", YSizeRange)}, LastData={JsonConvert.SerializeObject(points[points.Count-1])}");
  2192. if (YSizeRange[0] == YSizeRange[1])
  2193. {
  2194. YSizeRange[0] -= YSizeRange[0] / 10f;
  2195. YSizeRange[1] += YSizeRange[1] / 10f;
  2196. }
  2197. XSizeRange[0] /= 100;
  2198. XSizeRange[1] /= 100;
  2199. //防止超限
  2200. XSizeRange[1] += 0.01;
  2201. YSizeRange[1] += 0.1;
  2202. lineChartFaceWidth.Series.Clear();
  2203. lineChartFaceWidth.Series.Add("面宽");
  2204. lineChartFaceWidth.ChartAreas[0].AxisX.Title = "长度(m)";
  2205. lineChartFaceWidth.ChartAreas[0].AxisY.Title = "宽度(cm)";
  2206. lineChartFaceWidth.Series["面宽"].ChartType = SeriesChartType.Line;
  2207. lineChartFaceWidth.Series["面宽"].MarkerSize = 5;
  2208. lineChartFaceWidth.Series["面宽"].MarkerColor = Color.Blue;
  2209. lineChartFaceWidth.Series["面宽"].MarkerStyle = MarkerStyle.Circle;
  2210. //UILineOption option = new UILineOption();
  2211. //option.XAxis.Name = "长度(米)";
  2212. //option.YAxis.Name = "面宽(cm)";
  2213. //option.Grid.Top = 20;
  2214. //option.Grid.Right = 20;
  2215. //X轴数据类型
  2216. //option.XAxisType = UIAxisType.Value;
  2217. //设置X/Y轴显示范围
  2218. //option.XAxis.SetRange(XSizeRange[0], XSizeRange[1]);
  2219. //option.YAxis.SetRange(YSizeRange[0], YSizeRange[1]);
  2220. //坐标轴显示小数位数
  2221. //option.XAxis.AxisLabel.DecimalPlaces = option.YAxis.AxisLabel.DecimalPlaces = 1;
  2222. //X/Y轴画参考线
  2223. //option.YAxisScaleLines.Add(new UIScaleLine("上限", 3.5, Color.Red));
  2224. //option.YAxisScaleLines.Add(new UIScaleLine("下限", 2.2, Color.Gold));
  2225. //option.XAxisScaleLines.Add(new UIScaleLine(dt.AddHours(3).DateTimeString(), dt.AddHours(3), Color.Red));
  2226. //option.XAxisScaleLines.Add(new UIScaleLine(dt.AddHours(6).DateTimeString(), dt.AddHours(6), Color.Red));
  2227. //option.ToolTip.Visible = true;
  2228. //option.ToolTip.Formatter = "怎么自定义X,Y显示名称??{X}";
  2229. //option.Title = new UITitle();
  2230. //option.Title.Text = "";
  2231. //option.Title.SubText = "";
  2232. //Color color = Color.Blue;
  2233. //UILineSeries series = null;
  2234. //series = option.AddSeries(new UILineSeries("面宽", color));
  2235. //series.Symbol = UILinePointSymbol.Circle;
  2236. //series.ShowLine = true;
  2237. //series.SymbolSize = 4;
  2238. //series.SymbolLineWidth = 2;
  2239. //series.SymbolColor = color;
  2240. ////数据点显示小数位数(针对当前UILineSeries)
  2241. //series.XAxisDecimalPlaces = 2;
  2242. //series.YAxisDecimalPlaces = 1;
  2243. lineChartFaceWidth.ChartAreas[0].AxisY.Maximum = YSizeRange[1];
  2244. lineChartFaceWidth.ChartAreas[0].AxisY.Minimum = YSizeRange[0];
  2245. lineChartFaceWidth.ChartAreas[0].AxisX.Maximum = XSizeRange[1];
  2246. lineChartFaceWidth.ChartAreas[0].AxisX.Minimum = XSizeRange[0];
  2247. float x;
  2248. foreach (var item in points)
  2249. {
  2250. x = item[0] / 100; //cm -> m
  2251. //series.Add(x, item[1]);
  2252. this.lineChartFaceWidth.Series["面宽"].Points.AddXY((float)Math.Round(x, 2), (float)Math.Round(item[1], 2));
  2253. }
  2254. //====
  2255. //option.GreaterWarningArea = new UILineWarningArea(3.5);
  2256. //option.LessWarningArea = new UILineWarningArea(2.2, Color.Gold);
  2257. //this.BeginInvoke(new System.Action(() =>
  2258. //{
  2259. //this.lineChartFaceWidth.SetOption(option);
  2260. //}));
  2261. }
  2262. // 截图操作函数
  2263. private byte[] captureControl(System.Windows.Forms.Control control)
  2264. {
  2265. Bitmap bmp = new Bitmap(control.Width, control.Height);
  2266. Graphics graphics = Graphics.FromImage(bmp);
  2267. Rectangle rectangle = new Rectangle(0, 0, control.Width, control.Height);
  2268. control.DrawToBitmap(bmp, rectangle);
  2269. //bmp to jpg
  2270. MemoryStream ms = new MemoryStream();
  2271. bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);//bmp是已经获得的bitmap数据
  2272. byte[] bytes = ms.GetBuffer();
  2273. ms.Close();
  2274. graphics.Dispose();
  2275. return bytes;
  2276. //bitmap.Save(@"C:\Images\Capture.jpg", ImageFormat.Jpeg);
  2277. //return Image.FromStream(new MemoryStream(bytes));
  2278. }
  2279. public class JsonProductDefects
  2280. {
  2281. [Description("产品品名")]
  2282. public string ProName { get; set; }
  2283. [Description("产品批号")]
  2284. public string BatchId { get; set; }
  2285. [Description("产品卷号")]
  2286. public string ReelId { get; set; }
  2287. [Description("检验长度")]
  2288. public string Len { get; set; }
  2289. [Description("平均速度")]
  2290. public string Speed { get; set; }
  2291. [Description("等级")]
  2292. public string Grade { get; set; }
  2293. [Description("检验时间")]
  2294. public string DateTime { get; set; }
  2295. [Description("疵点统计")]
  2296. public List<JDefectTotal> DefectTotal = new List<JDefectTotal>();
  2297. public List<JDefectDetail> DefectDetail = new List<JDefectDetail>();
  2298. [Description("检测设置")]
  2299. public Models.Product Pdt { get; set; }
  2300. [Description("物面分辨率")]
  2301. public string xyPix { get; set; }
  2302. }
  2303. public class JDefectTotal
  2304. {
  2305. [Description("疵点名")]
  2306. public string Name { get; set; }
  2307. [Description("疵点数")]
  2308. public int Count { get; set; }
  2309. }
  2310. public class JDefectDetail
  2311. {
  2312. [Description("源图")]
  2313. public int Index { get; set; }
  2314. [Description("名称")]
  2315. public string Name { get; set; }
  2316. [Description("X(cm)")]
  2317. public double X { get; set; }
  2318. [Description("Y(米)")]
  2319. public double Y { get; set; }
  2320. [Description("宽(cm)")]
  2321. public double Width { get; set; }
  2322. [Description("高(cm)")]
  2323. public double Height { get; set; }
  2324. [Description("置信度")]
  2325. public double ZXD { get; set; }
  2326. [Description("面积(cm^2)")]
  2327. public double Area { get; set; }
  2328. [Description("对比度")]
  2329. public double Contrast { get; set; }
  2330. }
  2331. #endregion
  2332. #endregion
  2333. #endregion
  2334. #region 系统上设置界面
  2335. #region 串口获取
  2336. private void GetComPort()
  2337. {
  2338. var comNameList = SerialPort.GetPortNames().ToList();
  2339. comNameList.ForEach(comName =>
  2340. {
  2341. this.cobLightPortNum.Items.Add(comName);
  2342. this.cbJimiqiCom.Items.Add(comName);
  2343. });
  2344. //显示所有打印机
  2345. //if (SysMgr.Instance.PrintControl != null)
  2346. //{
  2347. // List<string> list = SysMgr.Instance.PrintControl.GetPrintersName();
  2348. // foreach (string printer in list)
  2349. // {
  2350. // cboPrinters.Items.Add(printer);
  2351. // cboPrinters2.Items.Add(printer);
  2352. // }
  2353. //}
  2354. }
  2355. #endregion
  2356. #region 界面刷新&保存
  2357. private void RefeshSysParams()
  2358. {
  2359. chkBuzzer.Checked = ConfMgr.Instance.SysConfigParams.OpenBuzzer;
  2360. //chkDoorSensor.Checked = ConfMgr.Instance.SysConfigParams.OpenDoor;
  2361. cbIODev.Checked = ConfMgr.Instance.SysConfigParams.OpenIO;
  2362. cbPLC.Checked = ConfMgr.Instance.SysConfigParams.OpenPLC;
  2363. cbJimiqi.Checked = ConfMgr.Instance.SysConfigParams.OpenLengthCount;
  2364. cbAutorun.Checked = ConfMgr.Instance.SysConfigParams.OpenAutoRun;
  2365. //cbJMStop.Checked = ConfMgr.Instance.SysConfigParams.OpenLengthCountStop;
  2366. //cbAIEdge.Checked = ConfMgr.Instance.SysConfigParams.OpenAIEdge;
  2367. //cbEmgStop.Checked = ConfMgr.Instance.SysConfigParams.OpenEMGStop;
  2368. cbOpenDB.Checked = ConfMgr.Instance.SysConfigParams.OpenDB;
  2369. cobLightPortNum.Text = ConfMgr.Instance.SysConfigParams.LightCom;
  2370. numLightBaud.Value = ConfMgr.Instance.SysConfigParams.LightComBaud;
  2371. cbJimiqiCom.Text = ConfMgr.Instance.SysConfigParams.LengthCounterCom;
  2372. numJimiqiBaud.Value = ConfMgr.Instance.SysConfigParams.LengthCounterComBaud;
  2373. tbIODevNum.Text = ConfMgr.Instance.SysConfigParams.IODevName;
  2374. //tbIOCfgPath.Text = ConfMgr.Instance.SysConfigParams.IOCfgPath;
  2375. tbPLCIP.Text = ConfMgr.Instance.SysConfigParams.PLC_IP;
  2376. tbCamCfgPath.Text = ConfMgr.Instance.SysConfigParams.CamPath_1;
  2377. tbCamCfgPath2.Text = ConfMgr.Instance.SysConfigParams.CamPath_2;
  2378. numCamIndex.Value = ConfMgr.Instance.SysConfigParams.CamIndex_1;
  2379. numCamIndex2.Value = ConfMgr.Instance.SysConfigParams.CamIndex_2;
  2380. numCamDev.Value = ConfMgr.Instance.SysConfigParams.CamDev_1;
  2381. numCamDev2.Value = ConfMgr.Instance.SysConfigParams.CamDev_2;
  2382. tbDefectPath.Text = ConfMgr.Instance.SysConfigParams.ImageDir;
  2383. chkSave1.Checked = ConfMgr.Instance.SysConfigParams.DefectSrcImag.AutoSave;
  2384. chkSave2.Checked = ConfMgr.Instance.SysConfigParams.DefectSplicImag.AutoSave;
  2385. chkSave3.Checked = ConfMgr.Instance.SysConfigParams.DefectSmallImag.AutoSave;
  2386. chkSave4.Checked = ConfMgr.Instance.SysConfigParams.CamImag.AutoSave;
  2387. chkDefect_Path_AutoClear.Checked = ConfMgr.Instance.SysConfigParams.DefectSrcImag.AutoDelete;
  2388. numDefect_Path_AutoClear.Value = (decimal)ConfMgr.Instance.SysConfigParams.DefectSrcImag.AutoDeleteDays;
  2389. //chkSave2.Checked = ConfMgr.Instance.SysConfigParams.DefectSmallImag.AutoSave;
  2390. //tbDefectSmallPath.Text = ConfMgr.Instance.SysConfigParams.DefectSmallImag.SavePath;
  2391. //chkDefect_Small_Path_AutoClear.Checked = ConfMgr.Instance.SysConfigParams.DefectSmallImag.AutoDelete;
  2392. //numDefect_Small_Path_AutoClear.Value = (decimal)ConfMgr.Instance.SysConfigParams.DefectSmallImag.AutoDeleteDays;
  2393. //chkSave3.Checked = ConfMgr.Instance.SysConfigParams.DefectSplicImag.AutoSave;
  2394. //tbDefectCompressSavePath.Text = ConfMgr.Instance.SysConfigParams.DefectSplicImag.SavePath;
  2395. //chkDefect_Compress_SavePath_AutoClear.Checked = ConfMgr.Instance.SysConfigParams.DefectSplicImag.AutoDelete;
  2396. //numDefect_Compress_SavePath_AutoClear.Value = (decimal)ConfMgr.Instance.SysConfigParams.DefectSplicImag.AutoDeleteDays;
  2397. //chkSave4.Checked = ConfMgr.Instance.SysConfigParams.CamImag.AutoSave;
  2398. //tbCamIamgePath.Text = ConfMgr.Instance.SysConfigParams.CamImag.SavePath;
  2399. //cbAutoDel.Checked = ConfMgr.Instance.SysConfigParams.CamImag.AutoDelete;
  2400. //numCamimageAutoDelDay.Value = (decimal)ConfMgr.Instance.SysConfigParams.CamImag.AutoDeleteDays;
  2401. //tbModelPath.Text = ConfMgr.Instance.SysConfigParams.AIModelPath;
  2402. //tbPdtPath.Text = ConfMgr.Instance.ProjectDir;
  2403. //tbLogPath.Text = ConfMgr.Instance.SysConfigParams.LogPath;
  2404. //ckbAutoClear.Checked = ConfMgr.Instance.SysConfigParams.AutoDeleteLog;
  2405. //numLogDays.Value = (decimal)ConfMgr.Instance.SysConfigParams.AutoDeleteLogData;
  2406. numViewX.Value = (decimal)ConfMgr.Instance.SysConfigParams.Cm2px_x;
  2407. numViewY.Value = (decimal)ConfMgr.Instance.SysConfigParams.Cm2px_y;
  2408. numMid.Value = (decimal)ConfMgr.Instance.SysConfigParams.MidCoin;
  2409. //numKW.Value = (decimal)ConfMgr.Instance.SysConfigParams.HolePx;
  2410. //numL.Value = (decimal)ConfMgr.Instance.SysConfigParams.LCrop;
  2411. //numR.Value = (decimal)ConfMgr.Instance.SysConfigParams.RCrop;
  2412. /////////////Print////////////////
  2413. //this.cbOpenBarTenderPrint.Checked = ConfMgr.Instance.SysConfigParams.EnableLabelPrint;
  2414. //this.cboPrinters.SelectedItem = ConfMgr.Instance.SysConfigParams.LabelPrinterName;
  2415. //this.cbOpenExcelPrint.Checked = ConfMgr.Instance.SysConfigParams.EnableExcelPrint;
  2416. //this.cboPrinters2.SelectedItem = ConfMgr.Instance.SysConfigParams.ExcelPrinterName;
  2417. ////////////////////////////////
  2418. ////////////////本地云端////////////////
  2419. //cbOpenCloud.Checked = ConfMgr.Instance.SysConfigParams.OpenCloud;
  2420. //tbCloudName.Text = ConfMgr.Instance.SysConfigParams.CloudThisName;
  2421. //tbCloudIP.Text = ConfMgr.Instance.SysConfigParams.CloudServerIP;
  2422. //numCloudPort.Value = (decimal)ConfMgr.Instance.SysConfigParams.CloudServerPort;
  2423. //tbCloudUser.Text = ConfMgr.Instance.SysConfigParams.CloudUser;
  2424. //tbCloudPassword.Text = ConfMgr.Instance.SysConfigParams.CloudPassword;
  2425. ////////////////////////////////////////
  2426. ///
  2427. this.cbMX1.Checked = ConfMgr.Instance.SysConfigParams.Cam1_flipXY;
  2428. //this.cbMY1.Checked = ConfMgr.Instance.SysConfigParams.Cam1_flipY;
  2429. this.cbMX2.Checked = ConfMgr.Instance.SysConfigParams.Cam2_flipXY;
  2430. //this.cbMY2.Checked = ConfMgr.Instance.SysConfigParams.Cam2_flipY;
  2431. this.numStopDis.Value = (decimal)ConfMgr.Instance.SysConfigParams.StopLookDis;
  2432. //this.numStopDecTime.Value = (decimal)ConfMgr.Instance.SysConfigParams.StopDecTime;
  2433. this.numStopPicCnt.Value = ConfMgr.Instance.SysConfigParams.StopImageCnt;
  2434. this.numDBdis.Value = (decimal)ConfMgr.Instance.SysConfigParams.CamToDBDis;
  2435. }
  2436. private void GetParamsSave()
  2437. {
  2438. SysConfigParams configParams = new SysConfigParams();
  2439. configParams = ConfMgr.Instance.SysConfigParams;
  2440. configParams.OpenBuzzer = chkBuzzer.Checked;
  2441. //configParams.OpenDoor = chkDoorSensor.Checked;
  2442. configParams.OpenIO = cbIODev.Checked;
  2443. configParams.OpenPLC = cbPLC.Checked;
  2444. configParams.OpenLengthCount = cbJimiqi.Checked;
  2445. configParams.OpenAutoRun = cbAutorun.Checked;
  2446. configParams.OpenDB = cbOpenDB.Checked;
  2447. configParams.LightCom = cobLightPortNum.Text;
  2448. configParams.LightComBaud = (int)numLightBaud.Value;
  2449. configParams.LengthCounterCom = cbJimiqiCom.Text;
  2450. configParams.LengthCounterComBaud = (int)numJimiqiBaud.Value;
  2451. configParams.IODevName = tbIODevNum.Text;
  2452. //configParams.IOCfgPath = tbIOCfgPath.Text;
  2453. configParams.PLC_IP = tbPLCIP.Text;
  2454. configParams.PLC_Rack = 0;
  2455. configParams.PLC_Solt = 1;
  2456. configParams.CamPath_1 = tbCamCfgPath.Text;
  2457. configParams.CamPath_2 = tbCamCfgPath2.Text;
  2458. configParams.CamIndex_1 = (int)numCamIndex.Value;
  2459. configParams.CamIndex_2 = (int)numCamIndex2.Value;
  2460. configParams.CamDev_1 = (int)numCamDev.Value;
  2461. configParams.CamDev_2 = (int)numCamDev2.Value;
  2462. configParams.ImageDir = tbDefectPath.Text;
  2463. configParams.DefectSrcImag.AutoSave = chkSave1.Checked;
  2464. configParams.DefectSrcImag.SavePath = $"{configParams.ImageDir}//原图";
  2465. configParams.DefectSrcImag.AutoDelete = chkDefect_Path_AutoClear.Checked;
  2466. configParams.DefectSrcImag.AutoDeleteDays = (double)numDefect_Path_AutoClear.Value;
  2467. configParams.DefectSplicImag.AutoSave = chkSave2.Checked;
  2468. configParams.DefectSplicImag.SavePath = $"{configParams.ImageDir}//瑕疵图";
  2469. configParams.DefectSplicImag.AutoDelete = chkDefect_Path_AutoClear.Checked;
  2470. configParams.DefectSplicImag.AutoDeleteDays = (double)numDefect_Path_AutoClear.Value;
  2471. configParams.DefectSmallImag.AutoSave = chkSave3.Checked;
  2472. configParams.DefectSmallImag.SavePath = $"{configParams.ImageDir}//瑕疵小图";
  2473. configParams.DefectSmallImag.AutoDelete = chkDefect_Path_AutoClear.Checked;
  2474. configParams.DefectSmallImag.AutoDeleteDays = (double)numDefect_Path_AutoClear.Value;
  2475. configParams.CamImag.AutoSave = chkSave4.Checked;
  2476. configParams.CamImag.SavePath = $"{configParams.ImageDir}//相机图";
  2477. configParams.CamImag.AutoDelete = chkDefect_Path_AutoClear.Checked;
  2478. configParams.CamImag.AutoDeleteDays = (double)numDefect_Path_AutoClear.Value;
  2479. //configParams.AIModelPath = tbModelPath.Text;
  2480. //configParams.ProductPath = tbPdtPath.Text;
  2481. //configParams.LogPath = tbLogPath.Text;
  2482. //configParams.AutoDeleteLog = ckbAutoClear.Checked;
  2483. //configParams.AutoDeleteLogData = (double)numLogDays.Value;
  2484. configParams.Cm2px_x = (int)numViewX.Value;
  2485. configParams.Cm2px_y = (int)numViewY.Value;
  2486. configParams.MidCoin = (int)numMid.Value;
  2487. ////////////////////Print//////////////////////////
  2488. //configParams.EnableLabelPrint = this.cbOpenBarTenderPrint.Checked;
  2489. //if (this.cboPrinters.SelectedItem != null)
  2490. // configParams.LabelPrinterName = this.cboPrinters.SelectedItem.ToString();
  2491. //configParams.EnableExcelPrint = this.cbOpenExcelPrint.Checked;
  2492. //if (this.cboPrinters2.SelectedItem != null)
  2493. // configParams.ExcelPrinterName = this.cboPrinters2.SelectedItem.ToString();
  2494. /////////////////////////////////////////////////
  2495. ///////本地云端////////////////////////////
  2496. //configParams.OpenCloud = this.cbOpenCloud.Checked;
  2497. //configParams.CloudThisName = this.tbCloudName.Text;
  2498. //configParams.CloudServerIP = this.tbCloudIP.Text;
  2499. //configParams.CloudServerPort = (int)this.numCloudPort.Value;
  2500. //configParams.CloudUser = this.tbCloudUser.Text;
  2501. //configParams.CloudPassword = this.tbCloudPassword.Text;
  2502. ///////////////////////////////////////////
  2503. ///
  2504. configParams.Cam1_flipXY = this.cbMX1.Checked;
  2505. configParams.Cam2_flipXY = this.cbMX2.Checked;
  2506. configParams.StopLookDis = (double)this.numStopDis.Value;
  2507. //configParams.StopDecTime = (double)this.numStopDecTime.Value;
  2508. configParams.StopImageCnt = (int)this.numStopPicCnt.Value;
  2509. configParams.CamToDBDis = (double)this.numDBdis.Value;
  2510. ConfMgr.Instance.WriteSysConfParams(configParams);
  2511. }
  2512. #endregion
  2513. #region 文件路径选择
  2514. private void btnClearPath_Click(object sender, EventArgs e)
  2515. {
  2516. PictureBox pb = (PictureBox)sender;
  2517. string path = "";
  2518. if (pb.Name == btnClearDefect_Path.Name)
  2519. this.tbDefectPath.Text = path;
  2520. }
  2521. private void tbDefectPath_Click(object sender, EventArgs e)
  2522. {
  2523. TextBox tb = (TextBox)sender;
  2524. string path = ConfMgr.SelectFolder(Application.StartupPath);
  2525. if (!string.IsNullOrWhiteSpace(path))
  2526. {
  2527. tb.Text = path;
  2528. }
  2529. }
  2530. private void tbCamCfgPath_Click(object sender, EventArgs e)
  2531. {
  2532. TextBox tb = (TextBox)sender;
  2533. string path = ConfMgr.SelectFile("所有文件|*.*", Application.StartupPath);
  2534. if (!string.IsNullOrWhiteSpace(path))
  2535. {
  2536. if (tb.Name == tbCamCfgPath.Name)
  2537. this.tbCamCfgPath.Text = path;
  2538. else if (tb.Name == tbCamCfgPath2.Name)
  2539. this.tbCamCfgPath2.Text = path;
  2540. }
  2541. }
  2542. #endregion
  2543. #endregion
  2544. #region 主界面控制
  2545. #region 按钮
  2546. private void tsbtnStart_Click(object sender, EventArgs e)
  2547. {
  2548. if (!SysMgr.Instance.IsRuning)
  2549. {
  2550. //低报警自动复位
  2551. if (SysMgr.Instance.StatusMgr.Status == SystemStsEnum.Warning)
  2552. {
  2553. if (SysMgr.Instance.StatusMgr.Warning == WarningEnum.Low)
  2554. {
  2555. SysMgr.Instance.StatusMgr.ClearWarning();
  2556. SysMgr.Instance.StatusMgr.GotoNormalStandby();
  2557. }
  2558. }
  2559. //提示正在报警中
  2560. if (SysMgr.Instance.StatusMgr.Status == SystemStsEnum.Warning)
  2561. {
  2562. FrmDialog.ShowDialog(this, "系统报警中!无法启动运行!", "警告", false);
  2563. return;
  2564. }
  2565. this.Cursor = Cursors.WaitCursor;
  2566. System.Windows.Forms.Application.DoEvents();
  2567. if (SysMgr.Instance.StatusMgr.Status != SystemStsEnum.Pause)
  2568. {
  2569. ResetUI(false);
  2570. AddTextEvent("运行", $"启动自动检测流程");
  2571. string color = this.cbPdtColor.Text;
  2572. string len = this.numPdtLength.Value.ToString();
  2573. string type = this.cbPdtType.Text;
  2574. string sn = this.cbPdtSN.Text;
  2575. if (string.IsNullOrEmpty(sn))
  2576. {
  2577. FrmDialog.ShowDialog(this, "未输入产品单号!", "提示", false);
  2578. return;
  2579. }
  2580. if (string.IsNullOrEmpty(color) || string.IsNullOrEmpty(type))
  2581. {
  2582. FrmDialog.ShowDialog(this, "未选择颜色和产品材质!", "提示", false);
  2583. return;
  2584. }
  2585. if (SysMgr.Instance.StartRun(this, sn, ref color, ref type, ref sn))
  2586. {
  2587. this.tsbtnImpStop.Enabled = true;
  2588. this.tsbtnStop.Enabled = true;
  2589. this.tsbtnStart.Enabled = false;
  2590. //锁定信息
  2591. this.cbPdtSN.Enabled = false;
  2592. this.cbPdtColor.Enabled = false;
  2593. this.numPdtLength.Enabled = false;
  2594. this.cbPdtType.Enabled = false;
  2595. //记录开始运行时间
  2596. RunStartTime.Restart();
  2597. //重新显示
  2598. //this.cbPdtColor.Text = name;
  2599. //this.cbProductBatch.Text = batch;
  2600. //this.cbProductReelNum.Text = reel;
  2601. //this.cbProductNum.Text = len;
  2602. //this.cbPdtType.Text = defname;
  2603. ResetChart();
  2604. }
  2605. }
  2606. else //暂停状态开始
  2607. {
  2608. if (SysMgr.Instance.ReStartRun())
  2609. {
  2610. this.tsbtnStop.Enabled = true;
  2611. this.tsbtnStart.Enabled = false;
  2612. }
  2613. }
  2614. this.Cursor = Cursors.Default;
  2615. }
  2616. }
  2617. private void tsbtnReset_Click(object sender, EventArgs e)
  2618. {
  2619. }
  2620. private void tsbtnStop_Click(object sender, EventArgs e)
  2621. {
  2622. AddTextEvent("暂停", "手动暂停");
  2623. this.tsbtnStart.Enabled = true;
  2624. SysMgr.Instance.Stop();
  2625. SysMgr.Instance.StatusMgr.GotoPause();
  2626. SysMgr.Instance.SendStatus();
  2627. SysMgr.Instance.LedPause();
  2628. }
  2629. private void tsbtnWarning_Click(object sender, EventArgs e)
  2630. {
  2631. if (SysMgr.Instance.StatusMgr.Warning != WarningEnum.Normal)
  2632. {
  2633. AddTextEvent("清除", "手动清除报警");
  2634. SysMgr.Instance.StatusMgr.ClearWarning();
  2635. SysMgr.Instance.LedReady();
  2636. if (SysMgr.Instance.IsAuto)
  2637. SysMgr.Instance.StatusMgr.GotoPause();
  2638. else
  2639. SysMgr.Instance.StatusMgr.GotoNormalStandby();
  2640. SysMgr.Instance.SendStatus();
  2641. }
  2642. }
  2643. /// <summary>
  2644. /// 结束验布
  2645. /// </summary>
  2646. /// <param name="sender"></param>
  2647. /// <param name="e"></param>
  2648. private void tsbtnImpStop_Click(object sender, EventArgs e)
  2649. {
  2650. AddTextEvent("结束验布", "手动结束验布");
  2651. SysMgr.Instance.StatusMgr.GotoPause();
  2652. SysMgr.Instance.DefectEnd(this);
  2653. this.tsbtnStop.Enabled = false;
  2654. this.tsbtnStart.Enabled = true;
  2655. this.tsbtnImpStop.Enabled = false;
  2656. SysMgr.Instance.StatusMgr.GotoNormalStandby();
  2657. SysMgr.Instance.SendStatus();
  2658. SysMgr.Instance.LedReady();
  2659. }
  2660. #endregion
  2661. #endregion
  2662. #region 调试
  2663. private void button2_Click(object sender, EventArgs e)
  2664. {
  2665. Mat img = new Mat("H:\\CPL\\GeBoshi\\新建文件夹\\23_src.bmp");
  2666. HObject himg = new HObject();
  2667. //转换
  2668. OpencvUtils.MatToHObject(img, out himg);
  2669. PGDetect tPGDetect = new PGDetect();
  2670. //HObject obj = new HObject();
  2671. //HOperatorSet.GenImageConst(out obj, "byte", 2048 * 8, 2048 * 2);//生成一幅图像,用byte格式,默认是黑色
  2672. //Mat initMat = new Mat(2048 * 2, 2048 * 8, MatType.CV_8UC3);
  2673. if (!tPGDetect.IniOptimization(himg, ConfMgr.Instance.SysConfigParams.HalconDataPath))
  2674. throw new Exception($"传统算法({ConfMgr.Instance.SysConfigParams.HalconDataPath})初始化失败!");
  2675. Stopwatch stopwatch = Stopwatch.StartNew();
  2676. double[] ststopwatch = new double[4];
  2677. HObject ho_imgG = new HObject();
  2678. HObject ho_ImageResult3 = new HObject();
  2679. HObject ho_ImageSub = new HObject();
  2680. HTuple hv_RES, hv_gauss_filter1, hv_gauss_filter2, hv_Energy_value, hv_Region_S_value, hv_class, hv_defectinfo;
  2681. int object_num = 0;
  2682. stopwatch.Stop();
  2683. ststopwatch[0] = stopwatch.ElapsedMilliseconds;
  2684. stopwatch.Restart();
  2685. //预处理
  2686. tPGDetect.Processing(himg, out ho_imgG, out ho_ImageResult3, out ho_ImageSub, ConfMgr.Instance.SysConfigParams.HalconDataPath,
  2687. out hv_RES, out hv_gauss_filter1, out hv_gauss_filter2, out hv_Energy_value, out hv_Region_S_value, out hv_class);
  2688. stopwatch.Stop();
  2689. ststopwatch[1] = stopwatch.ElapsedMilliseconds;
  2690. stopwatch.Restart();
  2691. //算法处理
  2692. tPGDetect.Detect(himg, ho_imgG, ho_ImageResult3, ho_ImageSub, hv_Energy_value, hv_Region_S_value, hv_class,
  2693. out hv_defectinfo, out object_num);
  2694. stopwatch.Stop();
  2695. ststopwatch[2] = stopwatch.ElapsedMilliseconds;
  2696. stopwatch.Restart();
  2697. //打标
  2698. double[] defectinfo = hv_defectinfo.ToDArr();
  2699. //List<DefectLabelInfo> DefectLabelInfoList = new List<DefectLabelInfo>();
  2700. for (int i = 0; i < object_num; i++)
  2701. {
  2702. #region 检测信息汇总
  2703. int index = i * 6;
  2704. // 打印输出信息(示例代码,根据实际情况进行修改和格式化)
  2705. // 获取输出信息
  2706. int x = (int)defectinfo[index];
  2707. int y = (int)defectinfo[index + 1];
  2708. int w = (int)defectinfo[index + 2];
  2709. int h = (int)defectinfo[index + 3];
  2710. int classId = (int)defectinfo[index + 4];
  2711. double confidence = Math.Round(defectinfo[index + 5], 2); //置信度
  2712. int px = x;
  2713. //var cmX = Math.Round(px * task.widthRatio / task.cm2px_x, 2);
  2714. //var cmY = Math.Round((task.bmp.Height - y - h) * task.widthRatio / task.cm2px_y, 2);//外面计Y从右下角为原点
  2715. //DefectLabelInfoList.Add(new DefectLabelInfo()
  2716. //{
  2717. // x = x,
  2718. // y = y,
  2719. // w = w,
  2720. // h = h,
  2721. // classId = classId,
  2722. // confidence = confidence, //置信度
  2723. // cmW = Math.Round(w * task.widthRatio / task.cm2px_x, 2),
  2724. // cmH = Math.Round(h * task.widthRatio / task.cm2px_y, 2),
  2725. // i = i,
  2726. // j = i,
  2727. //});
  2728. ////y = image_hight-y-h;//转到右下角为原点
  2729. //task.excelTable.Rows.Add($"{task.photoIndex}", cmX, cmY,
  2730. //Math.Round(w * task.widthRatio / task.cm2px_x, 2), Math.Round(h * task.widthRatio / task.cm2px_y, 2),
  2731. //i, classId, confidence, 0);
  2732. int penLine = 20;
  2733. //打标
  2734. var point1 = new OpenCvSharp.Point(x, y);
  2735. var point2 = new OpenCvSharp.Point(point1.X + w + penLine / 2, point1.Y + h + penLine / 2);
  2736. Cv2.Rectangle(img, point1, point2, new Scalar(0.0, 0.0, 255.0), penLine);//画打标点
  2737. //切小图
  2738. int left, top, decX, decY;
  2739. int tdecX = (w / 2) / 2;
  2740. int tdecY = w / h > 4 ? w / 8 : (h / 1) / 2;
  2741. decX = (w > 236 ? tdecX : 256 - w) / 2;
  2742. decY = (h > 236 ? tdecY : 256 - h) / 2;
  2743. left = point1.X - decX;
  2744. top = point1.Y - decY;
  2745. if (left < 0) left = 0;
  2746. if (top < 0) top = 0;
  2747. int width = w + decX * 2;
  2748. int height = h + decY * 2;
  2749. if (left + width > img.Width - 1) width = img.Width - left - 1;
  2750. if (top + height > img.Height - 1) height = img.Height - top - 1;
  2751. Rect roi = new Rect(left, top, width, height);
  2752. //task.lstDefectBmp.Add(new Mat(task.bmpTag, roi).Clone());
  2753. #endregion
  2754. }
  2755. stopwatch.Stop();
  2756. ststopwatch[3] = stopwatch.ElapsedMilliseconds;
  2757. }
  2758. #endregion
  2759. }
  2760. }