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

727 строки
31 KiB

  1. using Devart.Common;
  2. using ImageToolKits;
  3. using MaiMuAOI.SysCtrl;
  4. using MaiMuControl.Device;
  5. using Models;
  6. using Newtonsoft.Json;
  7. using Newtonsoft.Json.Linq;
  8. using OpenCvSharp;
  9. using OpenCvSharp.Flann;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.ComponentModel;
  13. using System.Data;
  14. using System.Drawing;
  15. using System.Drawing.Imaging;
  16. using System.IO;
  17. using System.Linq;
  18. using System.Text;
  19. using System.Threading.Tasks;
  20. using System.Windows.Forms;
  21. using Yolo5;
  22. namespace MaiMuAOI.SysUI.DefectPicShow
  23. {
  24. public partial class DistributionFrm : Form
  25. {
  26. private Order _order;
  27. private Dictionary<string, List<List<string>>> defectInfoDir = new Dictionary<string, List<List<string>>>();
  28. private List<DefectStruct> defectList = new List<DefectStruct>();
  29. private Dictionary<string, Bitmap> defectBmpsDir = new Dictionary<string, Bitmap>();
  30. private Yolo_Class yolo = new Yolo_Class();
  31. private int currDefectIndex = 0;
  32. private Color[] colorList = { Color.Red, Color.Green, Color.DarkViolet , Color.Magenta, Color.Orange, Color.Brown,
  33. Color.Olive, Color.PaleGreen, Color.CadetBlue,Color.Aqua,Color.YellowGreen,Color.Blue,Color.SpringGreen,Color.Fuchsia,Color.White };
  34. private string[] DefectCodes = { "dk", "zw","xws","gsyc","qk", "zk","pp","hs","yx", "xb", "sx","ds"};
  35. #region 表格数据类型
  36. private class DefectStruct
  37. {
  38. //Defect_{order.SN}_{res.index}_X{res.Xmm}_Y{res.Ymm}
  39. public string Key { get; set; }
  40. public int CurrIndex { get; set; }//当前缺陷在本大图中的索引0-n
  41. public int MainIndex { get; set; }//大图
  42. public double MainX { get; set; }//大图X 大相机拍照时原始X,Y轴坐标
  43. public double MainY { get; set; }//大图X
  44. //["4","3.9","-0.8","dk","0.39"],["index","X","Y","缺陷类型","缺陷的置信度"]
  45. public int Index { get; set; }
  46. public double X { get; set; }
  47. public double Y { get; set; }
  48. public string DefectName { get; set; }//缺陷类型
  49. public double DefectCC { get; set; }//缺陷的置信度
  50. //2023-10-30 修复情况
  51. public string Restoratory { get; set; }
  52. }
  53. #endregion
  54. public DistributionFrm(Order order)
  55. {
  56. InitializeComponent();
  57. UIStyle.SetUIStyle(this);
  58. this.uiTitel1.FatherForm = this;
  59. _order = order;
  60. imageBox0.SetIconsVisible(false);
  61. imageBox0.ChangeCursorModeIsHand(true);
  62. //imageBox0.set
  63. imageBox1.SetIconsVisible(false);
  64. imageBox1.ChangeCursorModeIsHand(true);
  65. #region 图片列表设置
  66. this.dgvProcess.AutoGenerateColumns = false;
  67. //显示行号与列宽度自动调整
  68. dgvProcess.RowHeadersVisible = true;
  69. dgvProcess.RowHeadersWidth = 30;
  70. dgvProcess.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
  71. //dgvProcess.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;//数据量过百绑定太变
  72. dgvProcess.RowPostPaint += (sender, e) =>//序号列头
  73. {
  74. showRowNum_onDataGrid_RowPostPaint(this.dgvProcess, sender, e);
  75. };
  76. for (int i = 0; i < dgvProcess.Columns.Count; i++)//禁止点击列头排序
  77. dgvProcess.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
  78. dgvProcess.DefaultCellStyle.ForeColor = Color.Black;
  79. #endregion
  80. #region 图纸列表设置
  81. this.dataGridView1.AutoGenerateColumns = false;
  82. //显示行号与列宽度自动调整
  83. dataGridView1.RowHeadersVisible = true;
  84. dataGridView1.RowHeadersWidth = 30;
  85. dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
  86. //dgvProcess.RowHeadersWidthSizeMode = DataGridViewRowHeadersWidthSizeMode.AutoSizeToAllHeaders;//数据量过百绑定太变
  87. dataGridView1.RowPostPaint += (sender, e) =>//序号列头
  88. {
  89. showRowNum_onDataGrid_RowPostPaint(this.dataGridView1, sender, e);
  90. };
  91. for (int i = 0; i < dataGridView1.Columns.Count; i++)//禁止点击列头排序
  92. dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
  93. dataGridView1.DefaultCellStyle.ForeColor = Color.Black;
  94. #endregion
  95. //图片查看功能现阶段禁用,存在bug
  96. tabControl1.TabPages.Remove(this.tabPage1);
  97. }
  98. //数据表重绘
  99. private void showRowNum_onDataGrid_RowPostPaint(DataGridView dgv, object sender, DataGridViewRowPostPaintEventArgs e)
  100. {
  101. Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgv.RowHeadersWidth - 4, e.RowBounds.Height);
  102. TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), dgv.RowHeadersDefaultCellStyle.Font, rectangle, dgv.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
  103. }
  104. #region 界面调整
  105. private void DistributionFrm_SizeChanged(object sender, EventArgs e)
  106. {
  107. if (this.WindowState == FormWindowState.Maximized)
  108. {
  109. this.WindowState = FormWindowState.Normal;
  110. this.Top = 0;
  111. this.Left = 0;
  112. this.Width = SystemInformation.WorkingArea.Width;
  113. this.Height = SystemInformation.WorkingArea.Height;
  114. }
  115. }
  116. #endregion
  117. #region 获取缺陷代码对应缺陷项
  118. public string getDefectName(string defectCode)
  119. {
  120. defectCode = defectCode.ToLower();
  121. switch (defectCode)
  122. {
  123. case "dk":
  124. return "堵孔";
  125. case "zw":
  126. return "脏污";
  127. case "xws":
  128. return "纤维丝";
  129. case "gsyc":
  130. return "钢丝异常";
  131. case "qk":
  132. return "缺口";
  133. case "zk":
  134. return "针孔";
  135. case "pp":
  136. return "泡泡";
  137. case "hs":
  138. return "划伤";
  139. case "yx":
  140. return "压线";
  141. case "xb":
  142. return "斜边";
  143. case "sx":
  144. return "栅线";
  145. case "ds":
  146. return "断栅";
  147. default:
  148. return "未知";
  149. }
  150. }
  151. #endregion
  152. #region 数据获取
  153. private bool GetDefectDataFromSN(string sn, string date)
  154. {
  155. try
  156. {
  157. JObject data = new JObject();
  158. string path, key;
  159. string[] files;
  160. #region 获取所有缺陷数据
  161. //文件名格式:$"Size_SN{order.SN}_I{res.index}_X{res.Defects_X}_Y{res.Defects_Y}_.....json/bmp
  162. //--缺陷
  163. path = $"{ConfMgr.Instance.SysConfigParams.DefectRepairImag.SavePath}\\{date}\\{sn}\\";
  164. if (Directory.Exists(path))
  165. {
  166. files = Directory.GetFiles(path, $"Defect_SN{sn}_*.json", SearchOption.TopDirectoryOnly);
  167. //对文件名中的数字(index)进行大小排序
  168. files = files.OrderBy(s => int.Parse(Path.GetFileNameWithoutExtension(s).Split('_')[2].Substring(1))).ToArray();
  169. foreach (string file in files)
  170. {
  171. key = Path.GetFileNameWithoutExtension(file);
  172. if (File.Exists(path + key + ".bmp"))
  173. data.Add(key, JArray.Parse(File.ReadAllText(file)));
  174. //加载小图
  175. //LoadDefectPic(new Bitmap(path + key + ".bmp"), key);
  176. }
  177. }
  178. //--缺陷加载小图
  179. path = $"{ConfMgr.Instance.SysConfigParams.DefectSmallImag.SavePath}\\{date}\\{sn}\\";
  180. if (Directory.Exists(path))
  181. {
  182. files = Directory.GetFiles(path, $"Defect_SN{sn}_*.bmp", SearchOption.TopDirectoryOnly);
  183. //对文件名中的数字(index)进行大小排序
  184. files = files.OrderBy(s => int.Parse(Path.GetFileNameWithoutExtension(s).Split('_')[2].Substring(1))).ToArray();
  185. foreach (string file in files)
  186. {
  187. key = Path.GetFileNameWithoutExtension(file);
  188. //加载小图
  189. LoadDefectPic(new Bitmap(file), key);
  190. }
  191. }
  192. //--比对
  193. path = $"{ConfMgr.Instance.SysConfigParams.SizeRepairImag.SavePath}\\{date}\\{sn}\\";
  194. if (Directory.Exists(path))
  195. {
  196. files = Directory.GetFiles(path, $"Size_SN{sn}_*.json", SearchOption.TopDirectoryOnly);
  197. //对文件名中的数字(index)进行大小排序
  198. files = files.OrderBy(s => int.Parse(Path.GetFileNameWithoutExtension(s).Split('_')[2].Substring(1))).ToArray();
  199. foreach (string file in files)
  200. {
  201. key = Path.GetFileNameWithoutExtension(file);
  202. if (File.Exists(path + key + ".bmp"))
  203. data.Add(key, JArray.Parse(File.ReadAllText(file)));
  204. }
  205. }
  206. #endregion
  207. #region 加载图片和数据
  208. string file_path;
  209. foreach (var kv in data)
  210. {
  211. defectInfoDir.Add(kv.Key, JsonConvert.DeserializeObject<List<List<string>>>(kv.Value.ToString()));
  212. file_path = $"{ConfMgr.Instance.SysConfigParams.DefectRepairImag.SavePath}\\{date}\\{sn}\\{kv.Key}.bmp";
  213. if (!File.Exists(file_path))
  214. throw new Exception(kv.Key + " 缺陷文件不存在!");
  215. Bitmap bmp = new Bitmap(file_path);
  216. defectBmpsDir.Add(kv.Key, bmp);
  217. }
  218. defectList.Clear();
  219. if (File.Exists(ConfMgr.Instance.SysConfigParams.ImageProcessDataPath))
  220. {
  221. double X, Y;
  222. int MainIndex;
  223. foreach (var item in defectInfoDir)
  224. {
  225. //Key : Defect_SN{order.SN}_I{res.index}_X{res.Xmm}_Y{res.Ymm}_C{res.defectCount}
  226. string[] str = item.Key.Split('_');
  227. MainIndex = Convert.ToInt32(str[2].Substring(1));
  228. X = Convert.ToDouble(str[3].Substring(1));
  229. Y = Convert.ToDouble(str[4].Substring(1));
  230. var arr = yolo.ImageXY2RepairTable(item.Value, X, Y, ConfMgr.Instance.SysConfigParams.ImageProcessDataPath);
  231. int i = 0;
  232. foreach (var arr2 in arr)
  233. {
  234. var obj = new DefectStruct();
  235. obj.Key = item.Key;
  236. obj.CurrIndex = i++;
  237. obj.MainIndex = MainIndex;
  238. obj.MainX = X;
  239. obj.MainY = Y;
  240. obj.Index = Convert.ToInt32(arr2[0].ToString());
  241. obj.X = Convert.ToDouble(arr2[1].ToString());
  242. obj.Y = Convert.ToDouble(arr2[2].ToString());
  243. obj.DefectName = getDefectName(arr2[3].ToString());
  244. obj.DefectCC = Convert.ToDouble(arr2[4].ToString());
  245. defectList.Add(obj);
  246. }
  247. }
  248. this.Invoke(new System.Action(() =>
  249. {
  250. this.dgvProcess.DataSource = null;
  251. //注:这样绑定List中的对象必需得用{get;set;}方式定义属性,否则单独格为空内容
  252. this.dgvProcess.DataSource = new BindingSource(defectList, null);
  253. this.gpbDefectList.Text = $"缺陷明细({defectList.Count}条)";
  254. }));
  255. gotoDefctListIndex(currDefectIndex);
  256. }
  257. else
  258. throw new Exception("转换文件不存在!Path:" + ConfMgr.Instance.SysConfigParams.ImageProcessDataPath);
  259. /*
  260. string file_path;
  261. bool first = true;
  262. foreach (var kv in data)
  263. {
  264. defectInfoDir.Add(kv.Key, JsonConvert.DeserializeObject<List<List<string>>>(kv.Value.ToString()));
  265. file_path = $"{ConfMgr.Instance.SysConfigParams.DefectRepairImag.SavePath}\\{date}\\{sn}\\{kv.Key}.bmp";
  266. if (!File.Exists(file_path))
  267. throw new Exception(kv.Key + " 缺陷文件不存在!");
  268. Bitmap bmp = new Bitmap(file_path);
  269. defectBmpsDir.Add(kv.Key, bmp);
  270. //["4","3.9","-0.8","dk","0.39"],["index","X","Y","缺陷类型","缺陷的置信度"]
  271. JArray arr = kv.Value as JArray;//二维数组
  272. foreach (JArray arr2 in arr)
  273. {
  274. var obj = new DefectStruct();
  275. obj.Key = kv.Key;
  276. obj.MainIndex = int.Parse(kv.Key.Split('_')[2].Substring(1));
  277. obj.Index = Convert.ToInt32(arr2[0].ToString());
  278. obj.X = Convert.ToDouble(arr2[1].ToString());
  279. obj.Y = Convert.ToDouble(arr2[2].ToString());
  280. obj.DefectName = getDefectName(arr2[3].ToString());
  281. obj.DefectCC = Convert.ToDouble(arr2[4].ToString());
  282. defectList.Add(obj);
  283. }
  284. if (first)
  285. {
  286. first = false;
  287. this.Invoke(new System.Action(() =>
  288. {
  289. this.reloadPic(bmp, defectInfoDir[defectList[0].Key], defectList[0]);
  290. //Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
  291. //mat = yolo.RepairTableDrawRec(defectInfor2RepairTable, defectInfo.MainX, defectInfo.MainY, defectInfo.CurrIndex, mat);
  292. }));
  293. }
  294. }
  295. this.Invoke(new System.Action(() =>
  296. {
  297. //注:这样绑定List中的对象必需得用{get;set;}方式定义属性,否则单独格为空内容
  298. this.dgvProcess.DataSource = new BindingSource(defectList, null);
  299. this.gpbDefectList.Text = $"缺陷明细({defectList.Count}条)";
  300. //2023-11-1 图纸对比缺陷标红
  301. for (int i = 0; i < defectList.Count; i++)
  302. {
  303. string defName = (string)this.dgvProcess.Rows[i].Cells["colDefectName"].Value;
  304. if ((defName == getDefectName("ds")) || ((defName == getDefectName("yx"))))
  305. this.dgvProcess.Rows[i].DefaultCellStyle.BackColor = Color.Red;
  306. }
  307. }));*/
  308. #endregion
  309. }
  310. catch (Exception ex)
  311. {
  312. MessageBox.Show(ex.Message, "加载错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
  313. return false;
  314. }
  315. return true;
  316. }
  317. #endregion
  318. #region 图片加载
  319. private void reloadPic(Bitmap bmp, List<List<string>> defectInfor2RepairTable, DefectStruct defectInfo)
  320. {
  321. //绘框
  322. if (defectInfor2RepairTable != null && defectInfo != null)
  323. {
  324. Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);
  325. mat = yolo.RepairTableDrawRec(defectInfor2RepairTable, defectInfo.MainX, defectInfo.MainY, defectInfo.CurrIndex, mat);
  326. //mat.ImWrite("ttt.bmp");
  327. imageBox0.RefreshWindow(mat);
  328. }
  329. }
  330. #endregion
  331. #region 表格事件
  332. private void dgvProcess_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
  333. {
  334. int preIndex = currDefectIndex;
  335. currDefectIndex = e.RowIndex;
  336. gotoDefctListIndex(currDefectIndex, preIndex);
  337. //图片对应不上,不使用
  338. //Control[] cts = this.pnlBmpList.Controls.Find("imgDefect_" + (currDefectIndex), true);
  339. //if((cts != null)&&(cts.Length>0))
  340. //{
  341. // cts[0].Select();
  342. //}
  343. }
  344. private void data_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
  345. {
  346. int preIndex = currDefectIndex;
  347. currDefectIndex = e.RowIndex;
  348. gotoDefctListIndex2(currDefectIndex, preIndex);
  349. //图片对应不上,不使用
  350. //Control[] cts = this.pnlBmpList.Controls.Find("imgDefect_" + (currDefectIndex), true);
  351. //if((cts != null)&&(cts.Length>0))
  352. //{
  353. // cts[0].Select();
  354. //}
  355. }
  356. #endregion
  357. #region 选择缺陷
  358. private void gotoDefctListIndex(int index, int preIndex = -1)
  359. {
  360. try
  361. {
  362. this.Invoke(new System.Action(() =>
  363. {
  364. string key = defectList[index].Key;
  365. if (defectBmpsDir.ContainsKey(key))
  366. {
  367. reloadPic(defectBmpsDir[key], defectInfoDir[key], defectList[index]);
  368. }
  369. if (preIndex > -1)
  370. this.dgvProcess.Rows[preIndex].DefaultCellStyle.BackColor = Color.White;
  371. this.dgvProcess.Rows[index].DefaultCellStyle.BackColor = Color.LightGreen;
  372. this.dgvProcess.Rows[index].Selected = true;
  373. //this.dgvProcess.CurrentCell = this.dgvProcess.Rows[index].Cells["colResult"];
  374. //this.dgvProcess.Rows[index].Cells["colResult"].Value = "已检";
  375. //reDrawByIndex(index);
  376. }));
  377. if ((defectList[index].X <= 0) || (defectList[index].Y <= 0))
  378. {
  379. return;
  380. }
  381. }
  382. catch (Exception ex)
  383. {
  384. }
  385. }
  386. private void gotoDefctListIndex2(int index, int preIndex = -1)
  387. {
  388. try
  389. {
  390. this.Invoke(new System.Action(() =>
  391. {
  392. if (preIndex > -1)
  393. this.dataGridView1.Rows[preIndex].DefaultCellStyle.BackColor = Color.White;
  394. this.dataGridView1.Rows[index].DefaultCellStyle.BackColor = Color.LightGreen;
  395. this.dataGridView1.Rows[index].Selected = true;
  396. reDrawByIndex(index);
  397. }));
  398. }
  399. catch (Exception ex)
  400. {
  401. }
  402. }
  403. #endregion
  404. #region 图纸显示
  405. private string _imgPath;
  406. private void reDraw(string imgPath)
  407. {
  408. _imgPath = imgPath;
  409. Bitmap bmp;
  410. Graphics g;
  411. using (System.Drawing.Image img = System.Drawing.Image.FromFile(imgPath))
  412. {
  413. if (IsIndexedPixelFormat(img.PixelFormat))
  414. {
  415. bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb);
  416. g = Graphics.FromImage(bmp);
  417. g.DrawImage(img, 0, 0);
  418. }
  419. else
  420. {
  421. bmp = new Bitmap(imgPath);
  422. g = Graphics.FromImage(bmp);
  423. }
  424. }
  425. var list = _order.DefectInfoList;
  426. int x, y, w, h;
  427. int i = 0;
  428. int index = 0;
  429. foreach (string code in DefectCodes)
  430. {
  431. var lstDefectCode = list.Where(m => m.Code == code ).ToList();
  432. foreach (var info in lstDefectCode)
  433. {
  434. x = (int)info.X - 10;
  435. y = (int)info.Y - 10;
  436. w = h = 20;
  437. if (x < 0) x = 0;
  438. if (y < 0) y = 0;
  439. if (w > bmp.Width - 1) w = bmp.Width - 1;
  440. if (h > bmp.Height - 1) h = bmp.Height - 1;
  441. //g.DrawRectangle(new Pen(item.ForeColor, 1.0f), x,y,w,h);
  442. g.FillEllipse(new SolidBrush(colorList[i]), x, y, w, h);
  443. var obj = new DefectStruct();
  444. //obj.Key = info.Pid;
  445. obj.CurrIndex = index++;
  446. //obj.MainIndex = MainIndex;
  447. //obj.MainX = X;
  448. //obj.MainY = Y;
  449. //obj.Index = Convert.ToInt32(arr2[0].ToString());
  450. obj.X = info.X;
  451. obj.Y = info.Y;
  452. obj.DefectName = getDefectName(info.Code);
  453. obj.DefectCC = info.ZXD;
  454. defectList.Add(obj);
  455. }
  456. i++;
  457. }
  458. g.Flush();
  459. g.Dispose();
  460. this.Invoke(new System.Action(() =>
  461. {
  462. this.dataGridView1.DataSource = null;
  463. //注:这样绑定List中的对象必需得用{get;set;}方式定义属性,否则单独格为空内容
  464. this.dataGridView1.DataSource = new BindingSource(defectList, null);
  465. this.groupBox1.Text = $"缺陷明细({defectList.Count}条)";
  466. }));
  467. //
  468. //reloadPic(bmp);
  469. //ucImageView1.loadImage(bmp);
  470. OpenCvSharp.Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);//用bitmap转换为mat
  471. imageBox1.RefreshWindow(mat);
  472. }
  473. private void reDrawByIndex(int index)
  474. {
  475. Bitmap bmp;
  476. Graphics g;
  477. using (System.Drawing.Image img = System.Drawing.Image.FromFile(_imgPath))
  478. {
  479. if (IsIndexedPixelFormat(img.PixelFormat))
  480. {
  481. bmp = new Bitmap(img.Width, img.Height, PixelFormat.Format32bppArgb);
  482. g = Graphics.FromImage(bmp);
  483. g.DrawImage(img, 0, 0);
  484. }
  485. else
  486. {
  487. bmp = new Bitmap(_imgPath);
  488. g = Graphics.FromImage(bmp);
  489. }
  490. }
  491. var list = _order.DefectInfoList;
  492. int x, y, w, h;
  493. int i = 0;
  494. int t_index = 0;
  495. foreach (string code in DefectCodes)
  496. {
  497. var lstDefectCode = list.Where(m => m.Code == code).ToList();
  498. foreach (var info in lstDefectCode)
  499. {
  500. if (t_index == index)
  501. {
  502. x = (int)info.X - 20;
  503. y = (int)info.Y - 20;
  504. w = h = 40;
  505. if (x < 0) x = 0;
  506. if (y < 0) y = 0;
  507. if (w > bmp.Width - 1) w = bmp.Width - 1;
  508. if (h > bmp.Height - 1) h = bmp.Height - 1;
  509. //g.DrawRectangle(new Pen(item.ForeColor, 1.0f), x,y,w,h);
  510. g.FillRectangle(new SolidBrush(Color.LimeGreen), x, y, w, h);
  511. }
  512. else
  513. {
  514. x = (int)info.X - 10;
  515. y = (int)info.Y - 10;
  516. w = h = 20;
  517. if (x < 0) x = 0;
  518. if (y < 0) y = 0;
  519. if (w > bmp.Width - 1) w = bmp.Width - 1;
  520. if (h > bmp.Height - 1) h = bmp.Height - 1;
  521. //g.DrawRectangle(new Pen(item.ForeColor, 1.0f), x,y,w,h);
  522. g.FillEllipse(new SolidBrush(colorList[i]), x, y, w, h);
  523. }
  524. t_index++;
  525. }
  526. i++;
  527. }
  528. g.Flush();
  529. g.Dispose();
  530. //
  531. //reloadPic(bmp);
  532. //ucImageView1.loadImage(bmp);
  533. OpenCvSharp.Mat mat = OpenCvSharp.Extensions.BitmapConverter.ToMat(bmp);//用bitmap转换为mat
  534. imageBox1.RefreshWindow(mat, ImageBox.ImageModeEnum.Part);
  535. }
  536. /// <summary>
  537. /// 判断图片是否索引像素格式,是否是引发异常的像素格式
  538. /// </summary>
  539. /// <param name="imagePixelFormat">图片的像素格式</param>
  540. /// <returns></returns>
  541. private bool IsIndexedPixelFormat(System.Drawing.Imaging.PixelFormat imagePixelFormat)
  542. {
  543. PixelFormat[] pixelFormatArray = {
  544. PixelFormat.Format1bppIndexed
  545. ,PixelFormat.Format4bppIndexed
  546. ,PixelFormat.Format8bppIndexed
  547. ,PixelFormat.Undefined
  548. ,PixelFormat.DontCare
  549. ,PixelFormat.Format16bppArgb1555
  550. ,PixelFormat.Format16bppGrayScale
  551. };
  552. foreach (PixelFormat pf in pixelFormatArray)
  553. {
  554. if (imagePixelFormat == pf)
  555. {
  556. return true;
  557. }
  558. }
  559. return false;
  560. }
  561. #endregion
  562. #region 界面加载
  563. private void DistributionFrm_Load(object sender, EventArgs e)
  564. {
  565. this.gboxDefectList.Tag = 0;
  566. this.pnlBmpList.Controls.Clear();
  567. this.Cursor = Cursors.WaitCursor;
  568. #region 加载图纸缺陷查看
  569. Models.Attachment attachmentFile = _order.ProductInfo.AttachmentList.FirstOrDefault(x => x.Type == 0);
  570. string gbxBmpPath = "";
  571. if (attachmentFile != null)
  572. {
  573. gbxBmpPath = ConfMgr.Instance.ProjectDir + $"\\{attachmentFile.NameTimestamp}";
  574. if (!File.Exists(gbxBmpPath + ".bmp"))
  575. gbxBmpPath = "";
  576. }
  577. if (string.IsNullOrEmpty(gbxBmpPath))
  578. {
  579. MessageBox.Show("图纸文件不存在!", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
  580. //this.Close();
  581. }
  582. else
  583. {
  584. if (!File.Exists(gbxBmpPath + ".jpg"))//转背景后的图纸文件
  585. {
  586. //换背景JPG
  587. Mat mat = Cv2.ImRead(gbxBmpPath + ".bmp");
  588. Cv2.CvtColor(mat, mat, ColorConversionCodes.RGB2GRAY);//转灰度图
  589. for (int i = 0; i < mat.Height; i++)
  590. {
  591. for (int j = 0; j < mat.Width; j++)
  592. {
  593. if (mat.At<byte>(i, j) == 255)//白色
  594. mat.Set<byte>(i, j, 0);
  595. else
  596. mat.Set<byte>(i, j, 255);
  597. }
  598. }
  599. OpenCvSharp.Extensions.BitmapConverter.ToBitmap(mat).Save(gbxBmpPath + ".jpg", ImageFormat.Jpeg);
  600. }
  601. string imagePath = gbxBmpPath + ".jpg";
  602. reDraw(imagePath);
  603. }
  604. #endregion
  605. #if NoUse
  606. #region 加载大图缺陷查看
  607. if (!GetDefectDataFromSN(_order.SN, _order.CreateTime.ToString("yyyMMdd")))
  608. {
  609. //this.Close();
  610. }
  611. #endregion
  612. #endif
  613. pnlBmpList.VerticalScroll.Value = 0;
  614. this.Cursor = Cursors.Default;
  615. }
  616. #endregion
  617. #region 加载小图
  618. private void LoadDefectPic(Bitmap bitmap, string name)
  619. {
  620. {
  621. //加载缺陷小图
  622. //纵向显示
  623. int imgWidth = this.pnlBmpList.ClientSize.Width - 50;
  624. int imgHeight = (int)((bitmap.Height * 1.0f / bitmap.Width) * imgWidth + 0.5);
  625. int splitWidth = 20;
  626. int pnlWidth = this.pnlBmpList.ClientSize.Width;
  627. int index = (int)this.gboxDefectList.Tag;
  628. PictureBox picbox = new PictureBox();
  629. picbox.Width = imgWidth;
  630. picbox.Height = imgHeight;
  631. picbox.Image = (Bitmap)bitmap.Clone();
  632. picbox.Name = "imgDefect_" + index;
  633. picbox.Tag = name;
  634. picbox.Click += new EventHandler(defectBmpBox_Click);
  635. picbox.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
  636. picbox.BorderStyle = BorderStyle.FixedSingle;
  637. //picbox.Margin = new Padding((pnlWidth - picbox.Height) / 2, splitWidth, 0, 0);
  638. picbox.Margin = new Padding((pnlWidth - picbox.Width) / 2, splitWidth, 0, 0);
  639. picbox.MouseHover += simpleTip_MouseHover;
  640. picbox.Visible = true;
  641. this.pnlBmpList.Controls.Add(picbox);
  642. pnlBmpList.VerticalScroll.Value = pnlBmpList.VerticalScroll.Maximum;
  643. this.gboxDefectList.Tag = ++index;
  644. this.gboxDefectList.Text = $"缺陷图像:{index} 张";
  645. }
  646. }
  647. private void defectBmpBox_Click(object sender, EventArgs e)
  648. {
  649. //对应不上,不使用
  650. //PictureBox pb = sender as PictureBox;
  651. //int index = int.Parse(pb.Name.Replace("imgDefect_", ""));
  652. //dgvProcess_CellDoubleClick(null, new DataGridViewCellEventArgs(1, index));
  653. }
  654. private void simpleTip_MouseHover(object sender, EventArgs e)
  655. {
  656. PictureBox pb = sender as PictureBox;
  657. // 创建the ToolTip
  658. ToolTip toolTip1 = new ToolTip();
  659. // 设置显示样式
  660. toolTip1.AutoPopDelay = 5000;//提示信息的可见时间
  661. toolTip1.InitialDelay = 500;//事件触发多久后出现提示
  662. toolTip1.ReshowDelay = 500;//指针从一个控件移向另一个控件时,经过多久才会显示下一个提示框
  663. toolTip1.ShowAlways = true;//是否显示提示框
  664. // 设置伴随的对象.
  665. toolTip1.SetToolTip(pb, pb.Name + "[" + pb.Tag.ToString() + "]");//设置提示按钮和提示内容
  666. }
  667. #endregion
  668. }
  669. }