革博士V2程序
25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.

722 satır
29 KiB

  1. #define online
  2. using DocumentFormat.OpenXml.Spreadsheet;
  3. using OpenCvSharp;
  4. using OpenCvSharp.XImgProc;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Security.Cryptography;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace GeBoShi.SysCtrl
  12. {
  13. public static class OpencvUtils
  14. {
  15. public static int image_width = 2048;
  16. public static int image_height = 2048;
  17. #region 图像预处理
  18. public static Mat Resize(Mat mat, int width, int height, out int xw)
  19. {
  20. OpenCvSharp.Size dsize = new OpenCvSharp.Size(width, height);
  21. //Mat mat2 = new Mat();
  22. //ResizeUniform(mat, dsize, out mat2, out xw);
  23. xw = 0;
  24. Mat mat2 = new Mat(height, width, MatType.CV_8UC3, new Scalar(114, 114, 114));
  25. Rect roi = new Rect((width - mat.Cols) / 2, (height - mat.Rows) / 2, mat.Cols, mat.Rows);
  26. mat.CopyTo(new Mat(mat2, roi));
  27. return mat2;
  28. }
  29. /// <summary>
  30. /// 等比例缩放
  31. /// </summary>
  32. /// <param name="src"></param>
  33. /// <param name="dst_size"></param>
  34. /// <param name="dst"></param>
  35. /// <returns></returns>
  36. public static int ResizeUniform(Mat src, Size dst_size, out Mat dst, out int xw)
  37. {
  38. xw = 0;
  39. int w = src.Cols;
  40. int h = src.Rows;
  41. int dst_w = dst_size.Width;
  42. int dst_h = dst_size.Height;
  43. //std::cout << "src: (" << h << ", " << w << ")" << std::endl;
  44. dst = new Mat(dst_h, dst_w, MatType.CV_8UC3, new Scalar(114, 114, 114));
  45. float[] ratio = new float[2];
  46. float ratio_src = w * 1.0f / h;
  47. float ratio_dst = dst_w * 1.0f / dst_h;
  48. int tmp_w = 0;
  49. int tmp_h = 0;
  50. if (ratio_src > ratio_dst)
  51. {
  52. tmp_w = dst_w;
  53. tmp_h = (int)(dst_w * 1.0f / w) * h;
  54. ratio[0] = (float)w / (float)tmp_w;
  55. ratio[1] = (float)h / (float)tmp_h;
  56. }
  57. else if (ratio_src < ratio_dst)
  58. {
  59. tmp_h = dst_h;
  60. tmp_w = (int)((dst_h * 1.0f / h) * w);
  61. ratio[0] = (float)w / (float)tmp_w;
  62. ratio[1] = (float)h / (float)tmp_h;
  63. }
  64. else
  65. {
  66. Cv2.Resize(src, dst, dst_size);
  67. ratio[0] = (float)w / (float)tmp_w;
  68. ratio[1] = (float)h / (float)tmp_h;
  69. return 0;
  70. }
  71. //std::cout << "tmp: (" << tmp_h << ", " << tmp_w << ")" << std::endl;
  72. Mat tmp = new Mat();
  73. Cv2.Resize(src, tmp, new Size(tmp_w, tmp_h));
  74. unsafe
  75. {
  76. if (tmp_w != dst_w)
  77. { //高对齐,宽没对齐
  78. int index_w = (int)((dst_w - tmp_w) / 2.0);
  79. xw = index_w;
  80. //std::cout << "index_w: " << index_w << std::endl;
  81. for (int i = 0; i < dst_h; i++)
  82. {
  83. Buffer.MemoryCopy(IntPtr.Add(tmp.Data, i * tmp_w * 3).ToPointer(), IntPtr.Add(dst.Data, i * dst_w * 3 + index_w * 3).ToPointer(), tmp_w * 3, tmp_w * 3);
  84. }
  85. }
  86. else if (tmp_h != dst_h)
  87. { //宽对齐, 高没有对齐
  88. int index_h = (int)((dst_h - tmp_h) / 2.0);
  89. //std::cout << "index_h: " << index_h << std::endl;
  90. Buffer.MemoryCopy(tmp.Data.ToPointer(), IntPtr.Add(dst.Data, index_h * dst_w * 3).ToPointer(), tmp_w * tmp_h * 3, tmp_w * tmp_h * 3);
  91. }
  92. else
  93. {
  94. }
  95. }
  96. return 0;
  97. }
  98. public static Mat ResizeMat(Mat mat, int width, int height)
  99. {
  100. OpenCvSharp.Size dsize = new OpenCvSharp.Size(width, height);
  101. Mat mat2 = new Mat();
  102. mat2 = mat.Resize(dsize);
  103. //Cv2.Resize(mat, mat2, dsize);
  104. return mat2;
  105. }
  106. /// <summary>
  107. /// 计算合理宽幅
  108. /// </summary>
  109. /// <param name="sumWidth">多个相机图像总宽(外部去除重合部分)</param>
  110. /// <returns></returns>
  111. public static int GetWidthForResize(int sumWidth)
  112. {
  113. //保证计算8x2 16个小图
  114. int count = (int)Math.Round(sumWidth * 1.0f / image_width, 0);
  115. count = 8;
  116. return count * image_width;
  117. //int count = sumWidth / image_width;
  118. ////int remainder = sumWidth % image_width;
  119. //if (count % 2 == 0)
  120. // return count * image_width;
  121. //else
  122. // return count * image_width+ image_width;
  123. }
  124. /// <summary>
  125. /// 裁切指定区域
  126. /// </summary>
  127. /// <param name="mat"></param>
  128. /// <param name="x"></param>
  129. /// <param name="y"></param>
  130. /// <param name="width"></param>
  131. /// <param name="height"></param>
  132. /// <returns></returns>
  133. public static Mat CutImage(Mat mat, int x, int y, int width, int height)
  134. {
  135. Rect roi = new Rect(x, y, width, height);
  136. return new Mat(mat, roi).Clone();
  137. }
  138. #endregion
  139. #region 裁边
  140. /// <summary>
  141. /// 裁边
  142. /// </summary>
  143. /// <param name="mat_rgb"></param>
  144. /// <param name="isLeft"></param>
  145. /// <param name="marginHoleWidth"></param>
  146. /// <param name="marginWidth"></param>
  147. /// <returns></returns>
  148. public static Mat getMaxInsetRect2(Mat mat_rgb, bool isLeft, int marginHoleWidth, out int marginWidth)
  149. {
  150. int bian = 3500;
  151. Rect Roi;
  152. if (!isLeft)
  153. Roi = new Rect(mat_rgb.Width - bian, 0, bian, mat_rgb.Height);
  154. else
  155. Roi = new Rect(0, 0, bian, mat_rgb.Height);
  156. int type = isLeft ? 1 : 0;
  157. int len = 0;
  158. if(!ConfMgr.Instance.SysConfigParams.OpenAIEdge)
  159. len = EdgeClipping2(mat_rgb, type, Roi, isLeft);
  160. else
  161. len = EdgeClipping3(mat_rgb, type, Roi, isLeft);
  162. #if false
  163. //Mat mat_rgb = new Mat("E:\\CPL\\测试代码\\边缘检测\\test\\test\\test\\img\\19.bmp");
  164. Mat image_gray = new Mat();
  165. Cv2.CvtColor(mat_rgb, image_gray, ColorConversionCodes.BGR2GRAY);
  166. //cvtColor(image_RGB, image, COLOR_RGB2GRAY);
  167. int height = image_gray.Rows;
  168. int width = image_gray.Cols;
  169. // 算法定义:取均分5段图片的五条横线,经过一系列处理之后,二值化,找到沿边位置,然后取均值作为直边,在缩进一段有针眼的位置
  170. // 定义每段的行数
  171. int num_rows = 5;
  172. int segment_height = height / num_rows - 1;
  173. // 定义空数组保存结果
  174. int[] total = new int[num_rows];
  175. // 平均截取5行数据并处理图像
  176. for (int i = 0; i < num_rows; i++)
  177. {
  178. // 截取当前行的图像
  179. int start_row = i * segment_height;
  180. Rect roi = new Rect(0, start_row, width, 1);
  181. Mat current_segment = image_gray.Clone(roi);
  182. // 对当前行的图像进行平滑处理
  183. Mat smoothed_image = new Mat();
  184. Cv2.GaussianBlur(current_segment, smoothed_image, new Size(5, 1), 0);
  185. // 计算当前行的灰度直方图
  186. Mat absolute_histo = new Mat();
  187. Cv2.CalcHist(new Mat[] { smoothed_image }, new int[] { 0 }, new Mat(), absolute_histo, 1, new int[] { 256 }, new Rangef[] { new Rangef(0, 256) });
  188. Cv2.GaussianBlur(current_segment, smoothed_image, new Size(19, 1), 0);
  189. // 对图片进行分割i+1
  190. //double otsu_threshold;
  191. //threshold(smoothed_image, smoothed_image, 0, 255, THRESH_BINARY + THRESH_OTSU, &otsu_threshold);
  192. Cv2.Threshold(smoothed_image, smoothed_image, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
  193. // 使用形态学操作进行孔洞填充
  194. Mat kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(25, 1));
  195. Mat filled_image = new Mat();
  196. Cv2.MorphologyEx(smoothed_image, filled_image, MorphTypes.Close, kernel);
  197. // 取较长的一个值作为皮革的宽度
  198. int num_255 = Cv2.CountNonZero(filled_image);
  199. int length_t = (num_255 > width / 2) ? num_255 : width - num_255;
  200. total[i] = (length_t);
  201. API.OutputDebugString($"getMaxInsetRect2: 【{i + 1}】{length_t}={num_255}|{width}");
  202. }
  203. // 取平均值作为宽度
  204. int length = (int)total.Average();
  205. marginWidth = width-length;
  206. #endif
  207. int length = len; //(len > mat_rgb.Width / 2) ? len : mat_rgb.Width - len;
  208. if (isLeft)
  209. marginWidth = length;
  210. else
  211. marginWidth = mat_rgb.Width - length;
  212. // 判断数据是否异常,判断当前线段的宽度是否大于设定像素的偏差
  213. //int abnormal_pxl = 200;
  214. //for (int i = 0; i < num_rows; i++)
  215. //{
  216. // if (Math.Abs(total[i] - length) > abnormal_pxl)
  217. // throw new Exception("数据异常,当段图片的宽度有问题!");
  218. //}
  219. //右侧相机,拍摄产品,边缘位于右侧判断,缩进100像素,去点针眼
  220. //Cv2.Line(mat_rgb, new Point(length - 100, 0), new Point(length - 100, height), new Scalar(255, 0, 0), 20);
  221. ////左侧相机,拍摄产品,边缘位于左侧判断,缩进100像素,去点针眼
  222. //Cv2.Line(mat_rgb, new Point(width - length + 100, 0), new Point(width - length + 100, height), new Scalar(0, 255, 0), 20);
  223. //int decWidth = width - length + marginHoleWidth;
  224. //if (isLeft)
  225. // return cutImage(mat_rgb, decWidth, 0, width- decWidth, height);
  226. //else
  227. // return cutImage(mat_rgb, 0, 0, width - decWidth, height);
  228. //API.OutputDebugString($"getMaxInsetRect2:margin={marginWidth},length={length}({marginHoleWidth}),isLeft={isLeft},mat_rgb={mat_rgb.Width}*{mat_rgb.Height},w={length - marginHoleWidth},h={mat_rgb.Height}");
  229. #if online
  230. if (isLeft)
  231. return CutImage(mat_rgb, length + marginHoleWidth, 0, mat_rgb.Width - length - marginHoleWidth, mat_rgb.Height);
  232. else
  233. return CutImage(mat_rgb, 0, 0, length - marginHoleWidth, mat_rgb.Height);
  234. #else
  235. if (isLeft)
  236. {
  237. Cv2.Line(mat_rgb, new Point(length + marginHoleWidth, 0), new Point(length + marginHoleWidth, mat_rgb.Height), new Scalar(255, 0, 0), 20);
  238. return mat_rgb;
  239. }
  240. else
  241. {
  242. Cv2.Line(mat_rgb, new Point(length - marginHoleWidth, 0), new Point(length - marginHoleWidth, mat_rgb.Height), new Scalar(0, 255, 0), 20);
  243. return mat_rgb;
  244. }
  245. #endif
  246. }
  247. /// <summary>
  248. /// 寻边算法
  249. /// </summary>
  250. /// <param name="image"></param>
  251. /// <param name="FindType"></param>
  252. /// <param name="Roi"></param>
  253. /// <param name="IsLeft"></param>
  254. /// <returns></returns>
  255. private static int EdgeClipping2(Mat image, int FindType, Rect Roi, bool IsLeft)
  256. {
  257. Mat mat_rgb = image.Clone(Roi);
  258. int height = mat_rgb.Rows;
  259. int width = mat_rgb.Cols;
  260. int sf = 10; //缩放比例
  261. int pix = 5; //获取均值区域长宽像素
  262. int pointNum = 15; //获取找遍点数
  263. int offsetGray = 5; //二值化偏差
  264. //按比例缩放
  265. int sf_height = height / sf;
  266. int sf_width = width / sf;
  267. Cv2.Resize(mat_rgb, mat_rgb, new Size(sf_width, sf_height), 0, 0, InterpolationFlags.Linear);
  268. //mat_rgb = mat_rgb.Resize(new Size(sf_width, sf_height));
  269. int[] maxlev = new int[3] { 3, 1, 0 };
  270. int[] srlev = new int[3] { 29, 25, 11 };
  271. int length_t = 0;
  272. Mat[] lineImg = new Mat[3];
  273. List<int> lines = new List<int>();
  274. List<int> total_t = new List<int>();
  275. for (int lv = 0; lv < 3; lv++)
  276. {
  277. lines.Clear();
  278. total_t.Clear();
  279. Mat himg = mat_rgb.Clone();
  280. //mat_rgb = mat_rgb.PyrMeanShiftFiltering(10, 27, 3);
  281. Cv2.PyrMeanShiftFiltering(himg, himg, 10, srlev[lv], maxlev[lv]);//10,17;
  282. //分通道处理
  283. Mat[] mv = Cv2.Split(himg);
  284. for (int cht = 0; cht < 3; cht++)
  285. {
  286. //转灰度图
  287. //mat_rgb = mat_rgb.CvtColor(ColorConversionCodes.BGR2GRAY);
  288. Mat image_gray = new Mat();
  289. image_gray = mv[cht];
  290. //image_gray.ImWrite($"image_gray{cht}.jpg");
  291. Mat image_Canny = new Mat();
  292. Cv2.Canny(image_gray, image_Canny, 32, 64, 3);
  293. //image_Canny.ImWrite($"image_Canny{cht}.jpg");
  294. var lins = Cv2.HoughLinesP(image_Canny, 1, Math.PI / 360, 0, 20, 10);
  295. lineImg[cht] = new Mat(new Size(himg.Cols, himg.Rows), MatType.CV_8UC1, new Scalar());
  296. lines.Add(lins.Length);
  297. foreach (var item in lins)
  298. {
  299. var fdang = Math.Atan2((item.P2.Y - item.P1.Y), (item.P2.X - item.P1.X));
  300. var ang = Math.Abs(fdang * (180 / Math.PI));
  301. if (ang > 60 && ang < 120)
  302. Cv2.Line(lineImg[cht], item.P1.X, item.P1.Y, item.P2.X, item.P2.Y, new Scalar(255, 255, 255), 2);
  303. }
  304. //lineImg[cht].ImWrite($"image_Canny2_{cht}.jpg");
  305. //mat_rgb = mat_rgb.Canny(32, 64);
  306. if (lins.Length >= 1)
  307. break;
  308. }
  309. if (lines.Count > 0 && lines.Max() >= 1)
  310. break;
  311. }
  312. //二值化
  313. Mat image_Otsu = new Mat();
  314. int hDis = sf_height / (pointNum + 2); //去除边缘两点
  315. #if false //二值算法
  316. List<double> LeftAvg = new List<double>();
  317. List<double> RightAvg = new List<double>();
  318. //double thb = Cv2.Threshold(image_gray, image_Otsu, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
  319. #region 多点获取二值化均值
  320. for (int i = 0; i < pointNum; i++)
  321. {
  322. Rect roiLeft = new Rect(0, hDis + hDis * i, pix, pix);
  323. Mat current_segmentL = image_gray.Clone(roiLeft);
  324. //Scalar ttr = current_segmentL.Mean();
  325. LeftAvg.Add(current_segmentL.Mean().Val0);
  326. Rect roiRight = new Rect(sf_width - pix, hDis + hDis * i, pix, pix);
  327. Mat current_segmentR = image_gray.Clone(roiRight);
  328. RightAvg.Add(current_segmentR.Mean().Val0);
  329. }
  330. double thres = 0;
  331. if (IsLeft)
  332. {
  333. if (LeftAvg.Average() > RightAvg.Average())
  334. thres = RightAvg.Max() + offsetGray;
  335. else
  336. thres = RightAvg.Min() - offsetGray;
  337. }
  338. else
  339. {
  340. if (LeftAvg.Average() > RightAvg.Average())
  341. thres = LeftAvg.Min() - offsetGray;
  342. else
  343. thres = LeftAvg.Max() + offsetGray;
  344. }
  345. //double thres = (RightAvg.Average() + )/2;
  346. #endregion
  347. #endif
  348. #if false
  349. double min, max;
  350. image_gray.MinMaxLoc(out min, out max);
  351. double thres = (min + max) / 2;
  352. #endif
  353. #if false //二值化图片
  354. //Cv2.Threshold(image_gray, image_Otsu, 0, 255, ThresholdTypes.Otsu);
  355. double thb = Cv2.Threshold(image_gray, image_Otsu, thres, 255, ThresholdTypes.Binary);
  356. image_Otsu.ImWrite("Otsu1.jpg");
  357. Cv2.MedianBlur(image_Otsu, image_Otsu, 21);
  358. image_Otsu.ImWrite("Otsu2.jpg");
  359. endTime = DateTimeOffset.Now;
  360. Console.WriteLine("灰度图二值化(ms): " + (endTime - startTime).TotalMilliseconds.ToString("0.000"));
  361. startTime = DateTimeOffset.Now;
  362. #else
  363. /*
  364. image_Otsu = image_Canny;
  365. */
  366. #endif
  367. int findex = lines.FindIndex(x => x == lines.Max());
  368. image_Otsu = lineImg[findex];
  369. // 定义空数组保存结果
  370. int[] total = new int[pointNum];
  371. total_t = new List<int>();
  372. //bool isLeft = FindType == 0 ? true : false;
  373. // 平均截取pointNum行数据并处理图像
  374. for (int i = 0; i < pointNum; i++)
  375. {
  376. // 截取当前行的图像
  377. Rect roi = new Rect(0, hDis + hDis * i, sf_width, 1);
  378. //Mat current_segment = image_Otsu.Clone(roi);
  379. Mat current_segment = image_Otsu.Clone(roi);
  380. #if false
  381. #region 预处理
  382. // 对当前行的图像进行平滑处理
  383. Mat smoothed_image2 = new Mat();
  384. Cv2.GaussianBlur(current_segment, smoothed_image2, new Size(5, 1), 0);
  385. // 计算当前行的灰度直方图
  386. Mat absolute_histo2 = new Mat();
  387. Cv2.CalcHist(new Mat[] { smoothed_image2 }, new int[] { 0 }, new Mat(), absolute_histo2, 1, new int[] { 256 }, new Rangef[] { new Rangef(0, 256) });
  388. Cv2.GaussianBlur(current_segment, smoothed_image2, new Size(9, 1), 0);
  389. // 对图片进行分割
  390. //double otsu_threshold;
  391. //threshold(smoothed_image, smoothed_image, 0, 255, THRESH_BINARY + THRESH_OTSU, &otsu_threshold);
  392. double otsu_threshold2 = Cv2.Threshold(smoothed_image2, smoothed_image2, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
  393. // 使用形态学操作进行孔洞填充
  394. Mat kernel3 = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(5, 1));
  395. Mat filled_image3 = new Mat();
  396. Cv2.MorphologyEx(smoothed_image2, filled_image3, MorphTypes.Close, kernel3);
  397. #endregion
  398. #else
  399. //Mat filled_image3 = current_segment.Clone();
  400. Mat filled_image3 = current_segment;
  401. #endif
  402. #if true
  403. //从左到右判断边和从右到左判断边
  404. int numX = 0;
  405. byte tempVal = 0;
  406. if (!IsLeft)
  407. {
  408. tempVal = filled_image3.At<byte>(0, 0);
  409. //filled_image3.
  410. for (int j = 0; j < filled_image3.Cols; j++)
  411. {
  412. if (filled_image3.At<byte>(0, j) != tempVal)
  413. {
  414. numX = j;
  415. break;
  416. }
  417. }
  418. }
  419. else
  420. {
  421. tempVal = filled_image3.At<byte>(0, filled_image3.Cols - 1);
  422. for (int j = filled_image3.Cols - 1; j >= 0; j--)
  423. {
  424. if (filled_image3.At<byte>(0, j) != tempVal)
  425. {
  426. numX = j;
  427. break;
  428. }
  429. }
  430. }
  431. //int numX = 0;
  432. //byte tempVal = 0;
  433. //unsafe
  434. //{
  435. // byte* ptr = (byte*)filled_image3.Data;
  436. // if (isLeft)
  437. // {
  438. // tempVal = ptr[0];
  439. // for (int j = 0; j < filled_image3.Cols; j++)
  440. // {
  441. // if (ptr[j] != tempVal)
  442. // {
  443. // numX = j;
  444. // break;
  445. // }
  446. // }
  447. // }
  448. // else
  449. // {
  450. // tempVal = ptr[filled_image3.Cols - 1];
  451. // //tempVal = filled_image3.At<byte>(0, filled_image3.Cols - 1);
  452. // for (int j = filled_image3.Cols - 1; j >= 0; j--)
  453. // {
  454. // if (ptr[j] != tempVal)
  455. // {
  456. // numX = j;
  457. // break;
  458. // }
  459. // }
  460. // }
  461. //}
  462. #else
  463. int numX = Cv2.CountNonZero(filled_image3);
  464. #endif
  465. //int length_t = (numX > (sf_width / 2)) ? numX :sf_width - numX;
  466. length_t = numX;
  467. total[i] = (length_t);
  468. if (length_t > 0)
  469. total_t.Add(length_t);
  470. current_segment.Dispose();
  471. }
  472. // 取平均值作为宽度
  473. int length = 0;
  474. if(total_t.Count> 0)
  475. length = (int)total_t.Average();
  476. //endTime = DateTimeOffset.Now;
  477. //Console.WriteLine("计算边(ms): " + (endTime - startTime).TotalMilliseconds.ToString("0.000"));
  478. // 判断数据是否异常,判断当前线段的宽度是否大于设定像素的偏差
  479. //int abnormal_pxl = 100 / 4;
  480. //for (int i = 0; i < pointNum; i++)
  481. //{
  482. // if (Math.Abs(total[i] - length) > abnormal_pxl)
  483. // Console.WriteLine("数据异常!");
  484. // //出现数据异常,当段图片的宽度有问题
  485. //}
  486. //乘上换算系数还原
  487. length = length * sf + Roi.X;
  488. //if ((length > 6520 && length < 6530) || (length > 1570 && length < 1590))
  489. // ;
  490. //else
  491. // ;
  492. mat_rgb.Dispose();
  493. //himg.Dispose();
  494. //image_gray.Dispose();
  495. //image_Canny.Dispose();
  496. //image_Otsu.Dispose();
  497. return length;
  498. }
  499. private static StructuredEdgeDetection _edgeDetect;
  500. public static void LoadEdgeMode()
  501. {
  502. if(_edgeDetect == null)
  503. _edgeDetect = OpenCvSharp.XImgProc.CvXImgProc.CreateStructuredEdgeDetection("model.yml");
  504. }
  505. /// <summary>
  506. /// 模型寻边
  507. /// </summary>
  508. /// <param name="image"></param>
  509. /// <param name="FindType"></param>
  510. /// <param name="Roi"></param>
  511. /// <param name="IsLeft"></param>
  512. /// <returns></returns>
  513. private static int EdgeClipping3(Mat image, int FindType, Rect Roi, bool IsLeft)
  514. {
  515. Mat mat_rgb = image.Clone(Roi);
  516. int height = mat_rgb.Rows;
  517. int width = mat_rgb.Cols;
  518. int sf = 10; //缩放比例
  519. int pix = 5; //获取均值区域长宽像素
  520. int pointNum = 15; //获取找遍点数
  521. int offsetGray = 5; //二值化偏差
  522. int length_t = 0;
  523. List<int> lines = new List<int>();
  524. List<int> total_t = new List<int>();
  525. //按比例缩放
  526. double sf_height = height / sf;
  527. double sf_width = width / sf;
  528. Cv2.Resize(mat_rgb, mat_rgb, new Size(sf_width, sf_height), 0, 0, InterpolationFlags.Linear);
  529. Mat himg = new Mat();
  530. Mat edgeimg = new Mat();
  531. Cv2.CvtColor(mat_rgb, edgeimg, ColorConversionCodes.BGR2RGB);
  532. Mat edges = new Mat();
  533. edgeimg.ConvertTo(edgeimg, MatType.CV_32F, 1 / 255.0);
  534. if(_edgeDetect == null)
  535. LoadEdgeMode();
  536. //Cv2.Normalize(edgeimg, edgeimg, 1.0, 0, NormTypes.L2, -1);
  537. _edgeDetect.DetectEdges(edgeimg, edges);
  538. Mat image_Otsu = new Mat();
  539. int hDis = (int)sf_height / (pointNum + 2); //去除边缘两点
  540. edges.ConvertTo(image_Otsu, MatType.CV_8U, 255.0);
  541. Cv2.Threshold(image_Otsu, image_Otsu, 0, 255, ThresholdTypes.Otsu);
  542. // 定义空数组保存结果
  543. int[] total = new int[pointNum];
  544. // 平均截取pointNum行数据并处理图像
  545. for (int i = 0; i < pointNum; i++)
  546. {
  547. // 截取当前行的图像
  548. Rect roi = new Rect(0, hDis + hDis * i, (int)sf_width, 1);
  549. Mat current_segment = image_Otsu.Clone(roi);
  550. //Mat filled_image3 = current_segment.Clone();
  551. Mat filled_image3 = current_segment;
  552. #if true
  553. //从左到右判断边和从右到左判断边
  554. int numX = 0;
  555. int tm = 0;
  556. byte tempVal = 0;
  557. bool findOne = false;
  558. if (IsLeft)
  559. {
  560. tempVal = filled_image3.At<byte>(0, 0);
  561. //filled_image3.
  562. for (int j = 0; j < filled_image3.Cols; j++)
  563. {
  564. if (filled_image3.At<byte>(0, j) != tempVal)
  565. {
  566. if (!findOne)
  567. {
  568. tm = j;
  569. findOne = true;
  570. tempVal = filled_image3.At<byte>(0, j);
  571. }
  572. else
  573. {
  574. //numX = j;
  575. numX = (tm + j) / 2;
  576. break;
  577. }
  578. }
  579. }
  580. }
  581. else
  582. {
  583. tempVal = filled_image3.At<byte>(0, filled_image3.Cols - 1);
  584. for (int j = filled_image3.Cols - 1; j >= 0; j--)
  585. {
  586. if (filled_image3.At<byte>(0, j) != tempVal)
  587. {
  588. if (!findOne)
  589. {
  590. tm = j;
  591. findOne = true;
  592. tempVal = filled_image3.At<byte>(0, j);
  593. }
  594. else
  595. {
  596. //numX = j;
  597. numX = (tm + j) / 2;
  598. break;
  599. }
  600. }
  601. }
  602. }
  603. #else
  604. int numX = Cv2.CountNonZero(filled_image3);
  605. #endif
  606. //length_t = (numX > (sf_width / 2)) ? numX :(int)(sf_width - numX);
  607. length_t = numX;
  608. total[i] = (length_t);
  609. if (length_t > 0)
  610. total_t.Add(length_t);
  611. }
  612. // 取平均值作为宽度
  613. int length = 0;
  614. if (total_t.Count > 0)
  615. {
  616. length = (int)total_t.Average();
  617. if (IsLeft)
  618. length = length - ConfMgr.Instance.SysConfigParams.Crop_offset;
  619. else
  620. length = length + ConfMgr.Instance.SysConfigParams.Crop_offset;
  621. }
  622. //乘上换算系数还原
  623. length = length * sf + Roi.X;
  624. return length;
  625. }
  626. #endregion
  627. #region 合并
  628. /// <summary>
  629. /// 合并MAT(宽高必需一致)
  630. /// </summary>
  631. /// <param name="mats"></param>
  632. /// <param name="isHorizontal"></param>
  633. /// <returns></returns>
  634. public static Mat MergeImage_sameSize(Mat[] mats, bool isHorizontal = true)
  635. {
  636. Mat matOut = new Mat();
  637. if (isHorizontal)
  638. Cv2.HConcat(mats, matOut);//横向拼接
  639. else
  640. Cv2.VConcat(mats, matOut);//纵向拼接
  641. return matOut;
  642. }
  643. #endregion
  644. }
  645. }