革博士程序V1仓库
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

1246 řádky
56 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Xaml;
  7. using DocumentFormat.OpenXml.Vml;
  8. using OpenCvSharp;
  9. using OpenCvSharp.XImgProc;
  10. namespace LeatherApp.Utils
  11. {
  12. public class OpenCVUtil
  13. {
  14. #region 模型寻边
  15. private static StructuredEdgeDetection _edgeDetect;
  16. public static void LoadEdgeMode()
  17. {
  18. if (_edgeDetect == null)
  19. _edgeDetect = OpenCvSharp.XImgProc.CvXImgProc.CreateStructuredEdgeDetection("model.yml");
  20. }
  21. /// <summary>
  22. /// 模型寻边
  23. /// </summary>
  24. /// <param name="image"></param>
  25. /// <param name="FindType"></param>
  26. /// <param name="Roi"></param>
  27. /// <param name="IsLeft"></param>
  28. /// <returns></returns>
  29. private static int EdgeClipping3(Mat image, int FindType, Rect Roi, bool IsLeft)
  30. {
  31. Mat mat_rgb = image.Clone(Roi);
  32. int height = mat_rgb.Rows;
  33. int width = mat_rgb.Cols;
  34. int sf = 10; //缩放比例
  35. int pix = 5; //获取均值区域长宽像素
  36. int pointNum = 15; //获取找遍点数
  37. int offsetGray = 5; //二值化偏差
  38. int length_t = 0;
  39. List<int> lines = new List<int>();
  40. List<int> total_t = new List<int>();
  41. //按比例缩放
  42. double sf_height = height / sf;
  43. double sf_width = width / sf;
  44. Cv2.Resize(mat_rgb, mat_rgb, new Size(sf_width, sf_height), 0, 0, InterpolationFlags.Linear);
  45. Mat himg = new Mat();
  46. Mat edgeimg = new Mat();
  47. Cv2.CvtColor(mat_rgb, edgeimg, ColorConversionCodes.BGR2RGB);
  48. Mat edges = new Mat();
  49. edgeimg.ConvertTo(edgeimg, MatType.CV_32F, 1 / 255.0);
  50. if (_edgeDetect == null)
  51. LoadEdgeMode();
  52. //Cv2.Normalize(edgeimg, edgeimg, 1.0, 0, NormTypes.L2, -1);
  53. _edgeDetect.DetectEdges(edgeimg, edges);
  54. Mat image_Otsu = new Mat();
  55. int hDis = (int)sf_height / (pointNum + 2); //去除边缘两点
  56. edges.ConvertTo(image_Otsu, MatType.CV_8U, 255.0);
  57. Cv2.Threshold(image_Otsu, image_Otsu, 0, 255, ThresholdTypes.Otsu);
  58. // 定义空数组保存结果
  59. int[] total = new int[pointNum];
  60. // 平均截取pointNum行数据并处理图像
  61. for (int i = 0; i < pointNum; i++)
  62. {
  63. // 截取当前行的图像
  64. Rect roi = new Rect(0, hDis + hDis * i, (int)sf_width, 1);
  65. Mat current_segment = image_Otsu.Clone(roi);
  66. //Mat filled_image3 = current_segment.Clone();
  67. Mat filled_image3 = current_segment;
  68. #if true
  69. //从左到右判断边和从右到左判断边
  70. int numX = 0;
  71. int tm = 0;
  72. byte tempVal = 0;
  73. bool findOne = false;
  74. if (!IsLeft)
  75. {
  76. tempVal = filled_image3.At<byte>(0, 0);
  77. //filled_image3.
  78. for (int j = 0; j < filled_image3.Cols; j++)
  79. {
  80. if (filled_image3.At<byte>(0, j) != tempVal)
  81. {
  82. if (!findOne)
  83. {
  84. tm = j;
  85. findOne = true;
  86. tempVal = filled_image3.At<byte>(0, j);
  87. }
  88. else
  89. {
  90. //numX = j;
  91. numX = (tm + j) / 2;
  92. break;
  93. }
  94. }
  95. }
  96. }
  97. else
  98. {
  99. tempVal = filled_image3.At<byte>(0, filled_image3.Cols - 1);
  100. for (int j = filled_image3.Cols - 1; j >= 0; j--)
  101. {
  102. if (filled_image3.At<byte>(0, j) != tempVal)
  103. {
  104. if (!findOne)
  105. {
  106. tm = j;
  107. findOne = true;
  108. tempVal = filled_image3.At<byte>(0, j);
  109. }
  110. else
  111. {
  112. //numX = j;
  113. numX = (tm + j) / 2;
  114. break;
  115. }
  116. }
  117. }
  118. }
  119. #else
  120. int numX = Cv2.CountNonZero(filled_image3);
  121. #endif
  122. //length_t = (numX > (sf_width / 2)) ? numX :(int)(sf_width - numX);
  123. length_t = numX;
  124. total[i] = (length_t);
  125. if (length_t > 0)
  126. total_t.Add(length_t);
  127. }
  128. // 取平均值作为宽度
  129. int length = 0;
  130. if (total_t.Count > 0)
  131. {
  132. length = (int)total_t.Average();
  133. if (IsLeft)
  134. length = length - 0;
  135. else
  136. length = length + 0;
  137. }
  138. //乘上换算系数还原
  139. length = length * sf + Roi.X;
  140. return length;
  141. }
  142. #endregion
  143. public static Mat resize(Mat mat, int width, int height, out int xw, out int xh)
  144. {
  145. OpenCvSharp.Size dsize = new OpenCvSharp.Size(width, height);
  146. //Mat mat2 = new Mat();
  147. //Cv2.Resize(mat, mat2, dsize);
  148. //ResizeUniform(mat, dsize, out mat2, out xw, out xh);
  149. xw = (width - mat.Cols) / 2;
  150. xh = (height - mat.Rows) / 2;
  151. Mat mat2 = new Mat(height, width, MatType.CV_8UC3, new Scalar(114, 114, 114));
  152. Rect roi = new Rect((width - mat.Cols) / 2, (height - mat.Rows) / 2, mat.Cols, mat.Rows);
  153. mat.CopyTo(new Mat(mat2, roi));
  154. return mat2;
  155. }
  156. public static int ResizeUniform(Mat src, Size dst_size, out Mat dst, out int xw, out int xh)
  157. {
  158. xw = xh = 0;
  159. int w = src.Cols;
  160. int h = src.Rows;
  161. int dst_w = dst_size.Width;
  162. int dst_h = dst_size.Height;
  163. //std::cout << "src: (" << h << ", " << w << ")" << std::endl;
  164. dst = new Mat(dst_h, dst_w, MatType.CV_8UC3, new Scalar(114, 114, 114));
  165. float[] ratio = new float[2];
  166. float ratio_src = w * 1.0f / h;
  167. float ratio_dst = dst_w * 1.0f / dst_h;
  168. int tmp_w = 0;
  169. int tmp_h = 0;
  170. if (ratio_src > ratio_dst)
  171. {
  172. tmp_w = dst_w;
  173. tmp_h = (int)(dst_w * 1.0f / w) * h;
  174. ratio[0] = (float)w / (float)tmp_w;
  175. ratio[1] = (float)h / (float)tmp_h;
  176. }
  177. else if (ratio_src < ratio_dst)
  178. {
  179. tmp_h = dst_h;
  180. tmp_w = (int)((dst_h * 1.0f / h) * w);
  181. ratio[0] = (float)w / (float)tmp_w;
  182. ratio[1] = (float)h / (float)tmp_h;
  183. }
  184. else
  185. {
  186. Cv2.Resize(src, dst, dst_size);
  187. ratio[0] = (float)w / (float)tmp_w;
  188. ratio[1] = (float)h / (float)tmp_h;
  189. return 0;
  190. }
  191. //std::cout << "tmp: (" << tmp_h << ", " << tmp_w << ")" << std::endl;
  192. Mat tmp = new Mat();
  193. Cv2.Resize(src, tmp, new Size(tmp_w, tmp_h));
  194. unsafe
  195. {
  196. if (tmp_w != dst_w)
  197. { //高对齐,宽没对齐
  198. int index_w = (int)((dst_w - tmp_w) / 2.0);
  199. xw = index_w;
  200. //std::cout << "index_w: " << index_w << std::endl;
  201. for (int i = 0; i < dst_h; i++)
  202. {
  203. 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);
  204. }
  205. }
  206. else if (tmp_h != dst_h)
  207. { //宽对齐, 高没有对齐
  208. int index_h = (int)((dst_h - tmp_h) / 2.0);
  209. xh = index_h;
  210. //std::cout << "index_h: " << index_h << std::endl;
  211. 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);
  212. }
  213. else
  214. {
  215. }
  216. }
  217. return 0;
  218. }
  219. public static Mat CreateLetterbox(Mat mat, OpenCvSharp.Size sz, Scalar color, out float ratio, out OpenCvSharp.Point diff, out OpenCvSharp.Point diff2, bool auto = true, bool scaleFill = false, bool scaleup = true)
  220. {
  221. //Mat mat = new Mat();
  222. //Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2RGB);
  223. ratio = Math.Min((float)sz.Width / (float)mat.Width, (float)sz.Height / (float)mat.Height);
  224. if (!scaleup)
  225. {
  226. ratio = Math.Min(ratio, 1f);
  227. }
  228. OpenCvSharp.Size dsize = new OpenCvSharp.Size((int)Math.Round((float)mat.Width * ratio), (int)Math.Round((float)mat.Height * ratio));
  229. int num = sz.Width - dsize.Width;
  230. int num2 = sz.Height - dsize.Height;
  231. float num3 = (float)sz.Height / (float)sz.Width;
  232. float num4 = (float)mat.Height / (float)mat.Width;
  233. if (auto && num3 != num4)
  234. {
  235. bool flag = false;
  236. }
  237. else if (scaleFill)
  238. {
  239. num = 0;
  240. num2 = 0;
  241. dsize = sz;
  242. }
  243. int num5 = (int)Math.Round((float)num / 2f);
  244. int num6 = (int)Math.Round((float)num2 / 2f);
  245. int num7 = 0;
  246. int num8 = 0;
  247. if (num5 * 2 != num)
  248. {
  249. num7 = num - num5 * 2;
  250. }
  251. if (num6 * 2 != num2)
  252. {
  253. num8 = num2 - num6 * 2;
  254. }
  255. if (mat.Width != dsize.Width || mat.Height != dsize.Height)
  256. {
  257. Cv2.Resize(mat, mat, dsize);
  258. }
  259. Cv2.CopyMakeBorder(mat, mat, num6 + num8, num6, num5, num5 + num7, BorderTypes.Constant, color);
  260. diff = new OpenCvSharp.Point(num5, num6);
  261. diff2 = new OpenCvSharp.Point(num7, num8);
  262. return mat;
  263. }
  264. /// <summary>
  265. /// 裁切指定区域
  266. /// </summary>
  267. /// <param name="mat"></param>
  268. /// <param name="x"></param>
  269. /// <param name="y"></param>
  270. /// <param name="width"></param>
  271. /// <param name="height"></param>
  272. /// <returns></returns>
  273. public static Mat cutImage(Mat mat, int x, int y, int width, int height)
  274. {
  275. Rect roi = new Rect(x, y, width, height);
  276. return new Mat(mat, roi).Clone();
  277. }
  278. /// <summary>
  279. /// 合并MAT(宽高必需一致)
  280. /// </summary>
  281. /// <param name="mats"></param>
  282. /// <param name="isHorizontal"></param>
  283. /// <returns></returns>
  284. public static Mat mergeImage_sameSize(Mat[] mats, bool isHorizontal = true)
  285. {
  286. Mat matOut = new Mat();
  287. if (isHorizontal)
  288. Cv2.HConcat(mats, matOut);//横向拼接
  289. else
  290. Cv2.VConcat(mats, matOut);//纵向拼接
  291. return matOut;
  292. }
  293. /// <summary>
  294. /// 合并MAT-纵向
  295. /// </summary>
  296. /// <param name="mat1"></param>
  297. /// <param name="mat2"></param>
  298. /// <returns></returns>
  299. public static Mat mergeImageV(Mat mat1,Mat mat2 )
  300. {
  301. Mat matOut = new Mat();
  302. //push_back 方法将图像2拷贝到图像1的最后一行
  303. Mat img_merge = new Mat();//要先设置大小吗
  304. img_merge.PushBack(mat1);
  305. img_merge.PushBack(mat2);
  306. return matOut;
  307. }
  308. /// <summary>
  309. /// 合并MAT-横向
  310. /// </summary>
  311. /// <param name="mat1"></param>
  312. /// <param name="mat2"></param>
  313. /// <returns></returns>
  314. public static Mat mergeImageH(Mat[] mats)
  315. {
  316. Stitcher stitcher = Stitcher.Create(Stitcher.Mode.Scans);
  317. Mat pano = new Mat();
  318. var status = stitcher.Stitch(mats, pano);
  319. if (status == Stitcher.Status.OK)
  320. return pano;
  321. else
  322. return null;
  323. // //1.新建一个要合并的图像
  324. // Size size = new Size(image1.Cols + image2.Cols, Math.Max(image1.Rows, image1.Rows));
  325. //Mat img_merge=new Mat();
  326. //img_merge.Create(size,new MatType( image1.Depth()));
  327. ////img_merge = Scalar.All(0);
  328. //Mat outImg_left, outImg_right;
  329. ////2.在新建合并图像中设置感兴趣区域
  330. //outImg_left = img_merge.a(Rect(0, 0, image1.cols, image1.rows));
  331. //outImg_right = img_merge(Rect(image1.cols, 0, image1.cols, image1.rows));
  332. ////3.将待拷贝图像拷贝到感性趣区域中
  333. //image1.copyTo(outImg_left);
  334. //image2.copyTo(outImg_right);
  335. //namedWindow("image1", 0);
  336. //Cv2.ImShow("image1", img_merge);
  337. }
  338. /// <summary>
  339. /// 获取最小外接矩形(正矩形)
  340. /// </summary>
  341. /// <returns></returns>
  342. public static Mat getMimOutRect(Mat srcImg)
  343. {
  344. try
  345. {
  346. //Mat srcImg = new Mat(@"E:\D\AutoCode\LeatherProject\LeatherApp\bin\Debug\testpic\2\11.bmp");
  347. Mat grayImg = new Mat();
  348. Mat binaryImg = new Mat();
  349. Cv2.CvtColor(srcImg, grayImg, ColorConversionCodes.BGR2GRAY);
  350. //Cv2.ImShow("src", srcImg);
  351. //toImg(this.pictureBox1, grayImg);
  352. //
  353. //double thresh = 30;//小于此值(超小超是所选黑色越多)转为maxval色
  354. //double maxval = 255;//上面值转为255白色
  355. double thresh = 80;//小于此值(超小超是所选黑色越多)转为maxval色
  356. double maxval = 255;//上面值转为255白色
  357. Cv2.Threshold(grayImg, binaryImg, thresh, maxval, ThresholdTypes.Binary);//转化黑白二值图 thresh:阀值
  358. //颜色反转
  359. //byte grayPixel = 0;
  360. //for (int r = 0; r < binary.Rows; r++)
  361. //{
  362. // for (int c = 0; c < binary.Cols; c++)
  363. // {
  364. // grayPixel = binary.At<byte>(r, c);
  365. // binary.Set<byte>(r, c, (byte)(255 - grayPixel));
  366. // }
  367. //}
  368. //FindContours让轮廓
  369. OpenCvSharp.Point[][] contours; //轮廓查找结果变量
  370. HierarchyIndex[] hierarchy; //轮廓拓扑结构变量
  371. //====RetrievalModes:
  372. //CV_RETR_EXTERNAL表示只检测外轮廓
  373. //CV_RETR_LIST检测的轮廓不建立等级关系
  374. //CV_RETR_CCOMP建立两个等级的轮廓,上面的一层为外边界,里面的一层为内孔的边界信息。如果内孔内还有一个连通物体,这个物体的边界也在顶层。
  375. //CV_RETR_TREE建立一个等级树结构的轮廓。具体参考contours.c这个demo
  376. //====ContourApproximationModes:
  377. //CV_CHAIN_APPROX_NONE存储所有的轮廓点,相邻的两个点的像素位置差不超过1,即max(abs(x1 - x2),abs(y2 - y1))== 1
  378. //CV_CHAIN_APPROX_SIMPLE压缩水平方向,垂直方向,对角线方向的元素,只保留该方向的终点坐标,例如一个矩形轮廓只需4个点来保存轮廓信息
  379. //CV_CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS使用teh - Chinl chain 近似算法
  380. Cv2.FindContours(binaryImg, out contours, out hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple);
  381. //DrawContours将结果画出并返回结果
  382. Mat dst_Image = Mat.Zeros(grayImg.Size(), srcImg.Type());
  383. Random rnd = new Random();
  384. int maxIndex = 0, maxLength = 0;
  385. for (int i = 0; i < contours.Length; i++)
  386. {
  387. if (contours[i].Length > maxLength)
  388. {
  389. maxLength = contours[i].Length;
  390. maxIndex = i;
  391. }
  392. }
  393. Scalar color = new Scalar(rnd.Next(0, 0), rnd.Next(0, 255), rnd.Next(0, 255));
  394. //var rectMin = Cv2.MinAreaRect(contours[i]);
  395. //这里有三个参数 分别是中心位置,旋转角度,缩放程度
  396. //Cv2.WarpAffine(srcImg, rectMin.Center, (height, width))
  397. //Rect rect = rectMin.BoundingRect();//
  398. Rect rect = Cv2.BoundingRect(contours[maxIndex]);// 获取矩形边界框
  399. //OpenCvSharp.Point pt1 = new OpenCvSharp.Point(rect.X, rect.Y);
  400. //OpenCvSharp.Point pt2 = new OpenCvSharp.Point(rect.X + rect.Width, rect.Y + rect.Height); //定义矩形对顶点
  401. //Cv2.Rectangle(srcImg, pt1, pt2, color, 1); //绘制矩形边框
  402. //Cv2.Line(srcImg, pt1, pt2, color, 1); //矩形单个对角线相,两点
  403. //Cv2.DrawContours(srcImg, contours, maxIndex, color, 2, LineTypes.Link8, hierarchy);
  404. //toImg(this.pictureBox1, srcImg);
  405. //return cutImage(srcImg, rect.X, rect.Y, rect.Width, rect.Height);
  406. return cutImage(srcImg, rect.X, 0, rect.Width, rect.Height);
  407. //
  408. //建立轮廓接受数组
  409. //Point[][] contours;
  410. //HierarchyIndex[] hierarchy;
  411. //Cv2.FindContours(binary, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone);
  412. //最小外接矩形接收数组
  413. //RotatedRect[] rotateRect = new RotatedRect[contours.Length];
  414. //Point[][] contours_poly = new Point[contours.Length][];
  415. //int maxPointCount = 0, index = -1;
  416. //for (int x = 0; x < contours.Length; x++)
  417. //{
  418. // if (maxPointCount < contours[x].Length)
  419. // {
  420. // maxPointCount = contours[x].Length;
  421. // index = x;
  422. // }
  423. //}
  424. }
  425. catch (Exception ex)
  426. {
  427. return null;
  428. }
  429. }
  430. #region 获取最大内接矩形
  431. /// <summary>
  432. /// 获取最大内接矩形(高度使用原图值未裁剪)
  433. /// </summary>
  434. /// <param name="srcImg"></param>
  435. /// <returns></returns>
  436. public static Mat getMaxInsetRect(Mat srcImg, double thresh = 45, double maxval = 255)
  437. {
  438. API.OutputDebugString("--------start:"+DateTime.Now.ToString("mm:ss fff"));
  439. var dst = new Mat();
  440. //转灰度
  441. Cv2.CvtColor(srcImg, dst, ColorConversionCodes.RGB2GRAY);
  442. API.OutputDebugString("--------转灰度:" + DateTime.Now.ToString("mm:ss fff"));
  443. //转化黑白二值图 thresh:阀值
  444. //double thresh = 50;//小于此值(超小超是所选黑色越多)转为maxval色
  445. //double maxval = 255;//上面值转为255白色
  446. Cv2.Threshold(dst, dst, thresh, maxval, ThresholdTypes.Binary);
  447. API.OutputDebugString("--------黑白二值图:" + DateTime.Now.ToString("mm:ss fff"));
  448. //取轮廓
  449. Cv2.FindContours(dst, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
  450. int maxIndex = 0, maxLength = 0;
  451. for (int i = 0; i < contours.Length; i++)
  452. {
  453. if (contours[i].Length > maxLength)
  454. {
  455. maxLength = contours[i].Length;
  456. maxIndex = i;
  457. }
  458. }
  459. API.OutputDebugString("--------取全部轮廓:" + DateTime.Now.ToString("mm:ss fff"));
  460. List<List<Point>> approxContours = new List<List<Point>>();
  461. //先求出多边形的近似轮廓,减少轮廓数量,方便后面计算
  462. var approxContour = Cv2.ApproxPolyDP(contours[maxIndex], 20, true);
  463. API.OutputDebugString("--------减少轮廓数量:" + DateTime.Now.ToString("mm:ss fff"));
  464. approxContours.Add(approxContour.ToList());
  465. //绘制边缘
  466. //DrawContour(srcImg, approxContour, Scalar.Red, 20);
  467. //return srcImg;
  468. Rect rect = GetMaxInscribedRect(srcImg, approxContour.ToList());
  469. API.OutputDebugString("--------取最大内切矩形:" + DateTime.Now.ToString("mm:ss fff"));
  470. var result= cutImage(srcImg, rect.X, 0, rect.Width, srcImg.Height);
  471. API.OutputDebugString("--------裁剪完成:" + DateTime.Now.ToString("mm:ss fff"));
  472. return result;
  473. }
  474. public static Mat getMaxInsetRect2(Mat mat_rgb,bool isLeft,int marginHoleWidth,out int marginWidth)
  475. {
  476. int bian = 3500;
  477. Rect Roi;
  478. if (!isLeft)
  479. Roi = new Rect(mat_rgb.Width - bian, 0, bian, mat_rgb.Height);
  480. else
  481. Roi = new Rect(0, 0, bian, mat_rgb.Height);
  482. int type = isLeft ? 1 : 0;
  483. int len = EdgeClipping3(mat_rgb, type, Roi, isLeft);
  484. #if false
  485. //Mat mat_rgb = new Mat("E:\\CPL\\测试代码\\边缘检测\\test\\test\\test\\img\\19.bmp");
  486. Mat image_gray = new Mat();
  487. Cv2.CvtColor(mat_rgb, image_gray, ColorConversionCodes.BGR2GRAY);
  488. //cvtColor(image_RGB, image, COLOR_RGB2GRAY);
  489. int height = image_gray.Rows;
  490. int width = image_gray.Cols;
  491. // 算法定义:取均分5段图片的五条横线,经过一系列处理之后,二值化,找到沿边位置,然后取均值作为直边,在缩进一段有针眼的位置
  492. // 定义每段的行数
  493. int num_rows = 5;
  494. int segment_height = height / num_rows - 1;
  495. // 定义空数组保存结果
  496. int[] total = new int[num_rows];
  497. // 平均截取5行数据并处理图像
  498. for (int i = 0; i < num_rows; i++)
  499. {
  500. // 截取当前行的图像
  501. int start_row = i * segment_height;
  502. Rect roi = new Rect(0, start_row, width, 1);
  503. Mat current_segment = image_gray.Clone(roi);
  504. // 对当前行的图像进行平滑处理
  505. Mat smoothed_image = new Mat();
  506. Cv2.GaussianBlur(current_segment, smoothed_image, new Size(5, 1), 0);
  507. // 计算当前行的灰度直方图
  508. Mat absolute_histo = new Mat();
  509. Cv2.CalcHist(new Mat[] { smoothed_image }, new int[] { 0 }, new Mat(), absolute_histo, 1, new int[] { 256 }, new Rangef[] { new Rangef(0, 256) });
  510. Cv2.GaussianBlur(current_segment, smoothed_image, new Size(19, 1), 0);
  511. // 对图片进行分割i+1
  512. //double otsu_threshold;
  513. //threshold(smoothed_image, smoothed_image, 0, 255, THRESH_BINARY + THRESH_OTSU, &otsu_threshold);
  514. Cv2.Threshold(smoothed_image, smoothed_image, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
  515. // 使用形态学操作进行孔洞填充
  516. Mat kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(25, 1));
  517. Mat filled_image = new Mat();
  518. Cv2.MorphologyEx(smoothed_image, filled_image, MorphTypes.Close, kernel);
  519. // 取较长的一个值作为皮革的宽度
  520. int num_255 = Cv2.CountNonZero(filled_image);
  521. int length_t = (num_255 > width / 2) ? num_255 : width - num_255;
  522. total[i] = (length_t);
  523. API.OutputDebugString($"getMaxInsetRect2: 【{i + 1}】{length_t}={num_255}|{width}");
  524. }
  525. // 取平均值作为宽度
  526. int length = (int)total.Average();
  527. marginWidth = width-length;
  528. #endif
  529. int length = (len > mat_rgb.Width / 2) ? len : mat_rgb.Width - len;
  530. marginWidth = mat_rgb.Width - length;
  531. // 判断数据是否异常,判断当前线段的宽度是否大于设定像素的偏差
  532. //int abnormal_pxl = 200;
  533. //for (int i = 0; i < num_rows; i++)
  534. //{
  535. // if (Math.Abs(total[i] - length) > abnormal_pxl)
  536. // throw new Exception("数据异常,当段图片的宽度有问题!");
  537. //}
  538. //右侧相机,拍摄产品,边缘位于右侧判断,缩进100像素,去点针眼
  539. //Cv2.Line(mat_rgb, new Point(length - 100, 0), new Point(length - 100, height), new Scalar(255, 0, 0), 20);
  540. ////左侧相机,拍摄产品,边缘位于左侧判断,缩进100像素,去点针眼
  541. //Cv2.Line(mat_rgb, new Point(width - length + 100, 0), new Point(width - length + 100, height), new Scalar(0, 255, 0), 20);
  542. //int decWidth = width - length + marginHoleWidth;
  543. //if (isLeft)
  544. // return cutImage(mat_rgb, decWidth, 0, width- decWidth, height);
  545. //else
  546. // return cutImage(mat_rgb, 0, 0, width - decWidth, height);
  547. 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}");
  548. if (isLeft)
  549. return cutImage(mat_rgb, mat_rgb.Width - length + marginHoleWidth, 0, length - marginHoleWidth, mat_rgb.Height);
  550. else
  551. return cutImage(mat_rgb, 0, 0, length - marginHoleWidth, mat_rgb.Height);
  552. //if (isLeft)
  553. // return cutImage(mat_rgb, length + marginHoleWidth, 0, length - marginHoleWidth, mat_rgb.Height);
  554. //else
  555. // return cutImage(mat_rgb, 0, 0, length - marginHoleWidth, mat_rgb.Height);
  556. }
  557. /// <summary>
  558. ///
  559. /// </summary>
  560. /// <param name="image">图片</param>
  561. /// <param name="FindType">0:从左往右找边,1:从右往左找边</param>
  562. /// <param name="Roi">寻找区域</param>
  563. /// <returns></returns>
  564. public static int EdgeClipping(Mat image, int FindType, Rect Roi)
  565. {
  566. DateTimeOffset startTime = DateTimeOffset.Now;
  567. Mat mat_rgb = image.Clone(Roi);
  568. int height = mat_rgb.Rows;
  569. int width = mat_rgb.Cols;
  570. int sf = 10; //缩放比例
  571. int pix = 5; //获取均值区域长宽像素
  572. int pointNum = 15; //获取找遍点数
  573. //按比例缩放
  574. int sf_height = height / sf;
  575. int sf_width = width / sf;
  576. Cv2.Resize(mat_rgb, mat_rgb, new Size(sf_width, sf_height), 0, 0, InterpolationFlags.Linear);
  577. Mat himg = new Mat();
  578. himg = mat_rgb.Clone();
  579. DateTimeOffset endTime = DateTimeOffset.Now;
  580. Console.WriteLine("图片缩小(ms): " + (endTime - startTime).TotalMilliseconds.ToString("0.000"));
  581. startTime = DateTimeOffset.Now;
  582. //滤过去除多余噪声
  583. //Cv2.EdgePreservingFilter(himg, himg, EdgePreservingMethods.RecursFilter);
  584. //Cv2.PyrMeanShiftFiltering(himg, himg, 10, 500, 3);
  585. Cv2.PyrMeanShiftFiltering(himg, himg, 1, 2, 1);
  586. //himg.ImWrite("himg.jpg");
  587. endTime = DateTimeOffset.Now;
  588. Console.WriteLine("滤过去除多余噪声(ms): " + (endTime - startTime).TotalMilliseconds.ToString("0.000"));
  589. startTime = DateTimeOffset.Now;
  590. //转灰度图
  591. Mat image_gray = new Mat();
  592. Cv2.CvtColor(himg, image_gray, ColorConversionCodes.BGR2GRAY);
  593. //image_gray.ImWrite("image_gray.jpg");
  594. //二值化
  595. Mat image_Otsu = new Mat();
  596. int hDis = sf_height / (pointNum + 2); //去除边缘两点
  597. #if false
  598. List<double> LeftAvg = new List<double>();
  599. List<double> RightAvg = new List<double>();
  600. //double thb = Cv2.Threshold(image_gray, image_Otsu, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
  601. #region 多点获取二值化均值
  602. for (int i = 0; i < pointNum; i++)
  603. {
  604. Rect roiLeft = new Rect(0, hDis + hDis * i, pix, pix);
  605. Mat current_segmentL = image_gray.Clone(roiLeft);
  606. //Scalar ttr = current_segmentL.Mean();
  607. LeftAvg.Add(current_segmentL.Mean().Val0);
  608. Rect roiRight = new Rect(sf_width - pix, hDis + hDis * i, pix, pix);
  609. Mat current_segmentR = image_gray.Clone(roiRight);
  610. RightAvg.Add(current_segmentR.Mean().Val0);
  611. }
  612. double thres = (RightAvg.Average() + LeftAvg.Average())/2;
  613. #endregion
  614. #else
  615. double min, max;
  616. image_gray.MinMaxLoc(out min, out max);
  617. double thres = (min + max) / 2;
  618. #endif
  619. //Cv2.Threshold(image_gray, image_Otsu, 0, 255, ThresholdTypes.Otsu);
  620. double thb = Cv2.Threshold(image_gray, image_Otsu, thres, 255, ThresholdTypes.Binary);
  621. //image_Otsu.ImWrite("Otsu1.jpg");
  622. endTime = DateTimeOffset.Now;
  623. Console.WriteLine("灰度图二值化(ms): " + (endTime - startTime).TotalMilliseconds.ToString("0.000"));
  624. startTime = DateTimeOffset.Now;
  625. // 定义空数组保存结果
  626. int[] total = new int[pointNum];
  627. List<int> total_t = new List<int>();
  628. bool isLeft = FindType == 0 ? true : false;
  629. // 平均截取pointNum行数据并处理图像
  630. for (int i = 0; i < pointNum; i++)
  631. {
  632. // 截取当前行的图像
  633. Rect roi = new Rect(0, hDis + hDis * i, sf_width, 1);
  634. Mat current_segment = image_Otsu.Clone(roi);
  635. #if false
  636. #region 预处理
  637. // 对当前行的图像进行平滑处理
  638. Mat smoothed_image2 = new Mat();
  639. Cv2.GaussianBlur(current_segment, smoothed_image2, new Size(5, 1), 0);
  640. // 计算当前行的灰度直方图
  641. Mat absolute_histo2 = new Mat();
  642. Cv2.CalcHist(new Mat[] { smoothed_image2 }, new int[] { 0 }, new Mat(), absolute_histo2, 1, new int[] { 256 }, new Rangef[] { new Rangef(0, 256) });
  643. Cv2.GaussianBlur(current_segment, smoothed_image2, new Size(9, 1), 0);
  644. // 对图片进行分割
  645. //double otsu_threshold;
  646. //threshold(smoothed_image, smoothed_image, 0, 255, THRESH_BINARY + THRESH_OTSU, &otsu_threshold);
  647. double otsu_threshold2 = Cv2.Threshold(smoothed_image2, smoothed_image2, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
  648. // 使用形态学操作进行孔洞填充
  649. Mat kernel3 = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(5, 1));
  650. Mat filled_image3 = new Mat();
  651. Cv2.MorphologyEx(smoothed_image2, filled_image3, MorphTypes.Close, kernel3);
  652. #endregion
  653. #else
  654. Mat filled_image3 = current_segment.Clone();
  655. #endif
  656. #if true
  657. //从左到右判断边和从右到左判断边
  658. int numX = 0;
  659. byte tempVal = 0;
  660. if (isLeft)
  661. {
  662. tempVal = filled_image3.At<byte>(0, 0);
  663. for (int j = 0; j < filled_image3.Cols; j++)
  664. {
  665. if (filled_image3.At<byte>(0, j) != tempVal)
  666. {
  667. numX = j;
  668. break;
  669. }
  670. }
  671. }
  672. else
  673. {
  674. tempVal = filled_image3.At<byte>(0, filled_image3.Cols - 1);
  675. for (int j = filled_image3.Cols - 1; j >= 0; j--)
  676. {
  677. if (filled_image3.At<byte>(0, j) != tempVal)
  678. {
  679. numX = j;
  680. break;
  681. }
  682. }
  683. }
  684. #else
  685. int numX = Cv2.CountNonZero(filled_image3);
  686. #endif
  687. //int length_t = (numX > (sf_width / 2)) ? numX :sf_width - numX;
  688. int length_t = numX;
  689. total[i] = (length_t);
  690. if (length_t > 0)
  691. total_t.Add(length_t);
  692. }
  693. // 取平均值作为宽度
  694. int length = (int)total_t.Average();
  695. endTime = DateTimeOffset.Now;
  696. Console.WriteLine("计算边(ms): " + (endTime - startTime).TotalMilliseconds.ToString("0.000"));
  697. // 判断数据是否异常,判断当前线段的宽度是否大于设定像素的偏差
  698. //int abnormal_pxl = 100 / 4;
  699. //for (int i = 0; i < pointNum; i++)
  700. //{
  701. // if (Math.Abs(total[i] - length) > abnormal_pxl)
  702. // Console.WriteLine("数据异常!");
  703. // //出现数据异常,当段图片的宽度有问题
  704. //}
  705. //乘上换算系数还原
  706. length = length * sf + Roi.X;
  707. return length;
  708. }
  709. public static int EdgeClipping2(Mat image, int FindType, Rect Roi, bool IsLeft)
  710. {
  711. DateTimeOffset startTime = DateTimeOffset.Now;
  712. Mat mat_rgb = image.Clone(Roi);
  713. int height = mat_rgb.Rows;
  714. int width = mat_rgb.Cols;
  715. int sf = 10; //缩放比例
  716. int pix = 5; //获取均值区域长宽像素
  717. int pointNum = 15; //获取找遍点数
  718. int offsetGray = 5; //二值化偏差
  719. //按比例缩放
  720. int sf_height = height / sf;
  721. int sf_width = width / sf;
  722. Cv2.Resize(mat_rgb, mat_rgb, new Size(sf_width, sf_height), 0, 0, InterpolationFlags.Linear);
  723. Mat himg = new Mat();
  724. himg = mat_rgb.Clone();
  725. DateTimeOffset endTime = DateTimeOffset.Now;
  726. Console.WriteLine("图片缩小(ms): " + (endTime - startTime).TotalMilliseconds.ToString("0.000"));
  727. startTime = DateTimeOffset.Now;
  728. //滤过去除多余噪声
  729. //Cv2.EdgePreservingFilter(himg, himg, EdgePreservingMethods.NormconvFilter);
  730. //Cv2.PyrMeanShiftFiltering(himg, himg, 1, 2, 1);
  731. Cv2.PyrMeanShiftFiltering(himg, himg, 10, 17, 2);
  732. //himg.ImWrite("himg.jpg");
  733. endTime = DateTimeOffset.Now;
  734. Console.WriteLine("滤过去除多余噪声(ms): " + (endTime - startTime).TotalMilliseconds.ToString("0.000"));
  735. startTime = DateTimeOffset.Now;
  736. //转灰度图
  737. Mat image_gray = new Mat();
  738. Cv2.CvtColor(himg, image_gray, ColorConversionCodes.BGR2GRAY);
  739. //image_gray.ImWrite("image_gray.jpg");
  740. Mat image_Canny = new Mat();
  741. Cv2.Canny(image_gray, image_Canny, 32, 64);
  742. //image_Canny.ImWrite("image_Canny.jpg");
  743. //二值化
  744. Mat image_Otsu = new Mat();
  745. int hDis = sf_height / (pointNum + 2); //去除边缘两点
  746. #if false //二值算法
  747. List<double> LeftAvg = new List<double>();
  748. List<double> RightAvg = new List<double>();
  749. //double thb = Cv2.Threshold(image_gray, image_Otsu, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
  750. #region 多点获取二值化均值
  751. for (int i = 0; i < pointNum; i++)
  752. {
  753. Rect roiLeft = new Rect(0, hDis + hDis * i, pix, pix);
  754. Mat current_segmentL = image_gray.Clone(roiLeft);
  755. //Scalar ttr = current_segmentL.Mean();
  756. LeftAvg.Add(current_segmentL.Mean().Val0);
  757. Rect roiRight = new Rect(sf_width - pix, hDis + hDis * i, pix, pix);
  758. Mat current_segmentR = image_gray.Clone(roiRight);
  759. RightAvg.Add(current_segmentR.Mean().Val0);
  760. }
  761. double thres = 0;
  762. if (IsLeft)
  763. {
  764. if (LeftAvg.Average() > RightAvg.Average())
  765. thres = RightAvg.Max() + offsetGray;
  766. else
  767. thres = RightAvg.Min() - offsetGray;
  768. }
  769. else
  770. {
  771. if (LeftAvg.Average() > RightAvg.Average())
  772. thres = LeftAvg.Min() - offsetGray;
  773. else
  774. thres = LeftAvg.Max() + offsetGray;
  775. }
  776. //double thres = (RightAvg.Average() + )/2;
  777. #endregion
  778. #endif
  779. #if false
  780. double min, max;
  781. image_gray.MinMaxLoc(out min, out max);
  782. double thres = (min + max) / 2;
  783. #endif
  784. #if false //二值化图片
  785. //Cv2.Threshold(image_gray, image_Otsu, 0, 255, ThresholdTypes.Otsu);
  786. double thb = Cv2.Threshold(image_gray, image_Otsu, thres, 255, ThresholdTypes.Binary);
  787. image_Otsu.ImWrite("Otsu1.jpg");
  788. Cv2.MedianBlur(image_Otsu, image_Otsu, 21);
  789. image_Otsu.ImWrite("Otsu2.jpg");
  790. endTime = DateTimeOffset.Now;
  791. Console.WriteLine("灰度图二值化(ms): " + (endTime - startTime).TotalMilliseconds.ToString("0.000"));
  792. startTime = DateTimeOffset.Now;
  793. #else
  794. image_Otsu = image_Canny;
  795. #endif
  796. // 定义空数组保存结果
  797. int[] total = new int[pointNum];
  798. List<int> total_t = new List<int>();
  799. bool isLeft = FindType == 0 ? true : false;
  800. // 平均截取pointNum行数据并处理图像
  801. for (int i = 0; i < pointNum; i++)
  802. {
  803. // 截取当前行的图像
  804. Rect roi = new Rect(0, hDis + hDis * i, sf_width, 1);
  805. Mat current_segment = image_Otsu.Clone(roi);
  806. #if false
  807. #region 预处理
  808. // 对当前行的图像进行平滑处理
  809. Mat smoothed_image2 = new Mat();
  810. Cv2.GaussianBlur(current_segment, smoothed_image2, new Size(5, 1), 0);
  811. // 计算当前行的灰度直方图
  812. Mat absolute_histo2 = new Mat();
  813. Cv2.CalcHist(new Mat[] { smoothed_image2 }, new int[] { 0 }, new Mat(), absolute_histo2, 1, new int[] { 256 }, new Rangef[] { new Rangef(0, 256) });
  814. Cv2.GaussianBlur(current_segment, smoothed_image2, new Size(9, 1), 0);
  815. // 对图片进行分割
  816. //double otsu_threshold;
  817. //threshold(smoothed_image, smoothed_image, 0, 255, THRESH_BINARY + THRESH_OTSU, &otsu_threshold);
  818. double otsu_threshold2 = Cv2.Threshold(smoothed_image2, smoothed_image2, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
  819. // 使用形态学操作进行孔洞填充
  820. Mat kernel3 = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(5, 1));
  821. Mat filled_image3 = new Mat();
  822. Cv2.MorphologyEx(smoothed_image2, filled_image3, MorphTypes.Close, kernel3);
  823. #endregion
  824. #else
  825. //Mat filled_image3 = current_segment.Clone();
  826. Mat filled_image3 = current_segment;
  827. #endif
  828. #if true
  829. //从左到右判断边和从右到左判断边
  830. int numX = 0;
  831. byte tempVal = 0;
  832. if (isLeft)
  833. {
  834. tempVal = filled_image3.At<byte>(0, 0);
  835. for (int j = 0; j < filled_image3.Cols; j++)
  836. {
  837. if (filled_image3.At<byte>(0, j) != tempVal)
  838. {
  839. numX = j;
  840. break;
  841. }
  842. }
  843. }
  844. else
  845. {
  846. tempVal = filled_image3.At<byte>(0, filled_image3.Cols - 1);
  847. for (int j = filled_image3.Cols - 1; j >= 0; j--)
  848. {
  849. if (filled_image3.At<byte>(0, j) != tempVal)
  850. {
  851. numX = j;
  852. break;
  853. }
  854. }
  855. }
  856. #else
  857. int numX = Cv2.CountNonZero(filled_image3);
  858. #endif
  859. //int length_t = (numX > (sf_width / 2)) ? numX :sf_width - numX;
  860. int length_t = numX;
  861. total[i] = (length_t);
  862. if (length_t > 0)
  863. total_t.Add(length_t);
  864. }
  865. // 取平均值作为宽度
  866. int length = (int)total_t.Average();
  867. endTime = DateTimeOffset.Now;
  868. Console.WriteLine("计算边(ms): " + (endTime - startTime).TotalMilliseconds.ToString("0.000"));
  869. // 判断数据是否异常,判断当前线段的宽度是否大于设定像素的偏差
  870. //int abnormal_pxl = 100 / 4;
  871. //for (int i = 0; i < pointNum; i++)
  872. //{
  873. // if (Math.Abs(total[i] - length) > abnormal_pxl)
  874. // Console.WriteLine("数据异常!");
  875. // //出现数据异常,当段图片的宽度有问题
  876. //}
  877. //乘上换算系数还原
  878. length = length * sf + Roi.X;
  879. return length;
  880. }
  881. private static Rect GetMaxInscribedRect(Mat src, List<Point> contour)
  882. {
  883. //根据轮廓让点与下一个点之间形成一个矩形,然后让每个矩形都与当前所有矩形相交,求出相交的矩形,
  884. //再把这些矩形所有的角放到一个集合里,筛选出在轮廓内并且非重复的点,
  885. //最后让这些点两两组合成一个矩形,判断是否为内部矩形,算出面积,找出最大内接矩形。
  886. //比如一共4个点,第1个与第2个形成矩形(矩形1),第1与第3(矩形2),
  887. //第1与第4(矩形3),第2与第3(矩形4),第2与第4(矩形5),第3与第4(矩形6),
  888. //由于矩形1为第一个元素,没有相交矩形,所以直接放入allPoint中,
  889. //接着把矩形2的四个角,以及矩形2和矩形1相交矩形的四个角,放入allPoint中,
  890. //矩形3以此类推,其本身四个角,以及和矩形1相交矩形的四个角,以及和矩形2相交矩形的四个角
  891. Rect maxInscribedRect = new Rect();
  892. List<Rect> allRect = new List<Rect>();
  893. List<Point> allPoint = new List<Point>(contour);
  894. //根据轮廓让点与下一个点之间形成一个矩形
  895. for (int i = 0; i < contour.Count; i++)
  896. {
  897. for (int j = i + 1; j < contour.Count; j++)
  898. {
  899. var p1 = contour[i];
  900. var p2 = contour[j];
  901. if (p1.Y == p2.Y || p1.X == p2.X)
  902. continue;
  903. var tempRect = FromTowPoint(p1, p2);
  904. allPoint.AddRange(GetAllCorner(tempRect));
  905. //让每个矩形都与当前所有矩形相交,求出相交的矩形,再把这些矩形所有的角放到一个集合里
  906. foreach (var rect in allRect)
  907. {
  908. var intersectR = tempRect.Intersect(rect);
  909. if (intersectR != Rect.Empty)
  910. allPoint.AddRange(GetAllCorner(intersectR));
  911. }
  912. allRect.Add(tempRect);
  913. }
  914. }
  915. //去除重复的点,再让这些点两两组合成一个矩形,判断是否为内部矩形,算出面积,找出最大内接矩形
  916. List<Point> distinctPoints = allPoint.Distinct().ToList();
  917. for (int i = 0; i < distinctPoints.Count; i++)
  918. {
  919. for (int j = i + 1; j < distinctPoints.Count; j++)
  920. {
  921. var tempRect = FromTowPoint(distinctPoints[i], distinctPoints[j]);
  922. //只要矩形包含一个轮廓内的点,就不算多边形的内部矩形;只要轮廓不包含该矩形,该矩形就不算多边形的内部矩形
  923. if (!ContainPoints(contour, GetAllCorner(tempRect)) || ContainsAnyPt(tempRect, contour))
  924. continue;
  925. //src.Rectangle(tempRect, Scalar.RandomColor(), 2);
  926. if (tempRect.Width * tempRect.Height > maxInscribedRect.Width * maxInscribedRect.Height)
  927. maxInscribedRect = tempRect;
  928. }
  929. }
  930. //src.Rectangle(maxInscribedRect, Scalar.Yellow, 2);
  931. return maxInscribedRect == Rect.Empty ? Cv2.BoundingRect(contour) : maxInscribedRect;
  932. }
  933. public static Point[] GetAllCorner(Rect rect)
  934. {
  935. Point[] result = new Point[4];
  936. result[0] = rect.Location;
  937. result[1] = new Point(rect.X + rect.Width, rect.Y);
  938. result[2] = rect.BottomRight;
  939. result[3] = new Point(rect.X, rect.Y + rect.Height);
  940. return result;
  941. }
  942. private static bool ContainPoint(List<Point> contour, Point p1)
  943. {
  944. return Cv2.PointPolygonTest(contour, p1, false) > 0;
  945. }
  946. private static bool ContainPoints(List<Point> contour, IEnumerable<Point> points)
  947. {
  948. foreach (var point in points)
  949. {
  950. if (Cv2.PointPolygonTest(contour, point, false) < 0)
  951. return false;
  952. }
  953. return true;
  954. }
  955. private static void DrawContour(Mat mat, Point[] contour, Scalar color, int thickness)
  956. {
  957. for (int i = 0; i < contour.Length; i++)
  958. {
  959. if (i + 1 < contour.Length)
  960. Cv2.Line(mat, contour[i], contour[i + 1], color, thickness);
  961. }
  962. }
  963. /// <summary>
  964. /// 是否有任意一个点集合中的点包含在矩形内,在矩形边界上不算包含
  965. /// </summary>
  966. /// <param name="rect"></param>
  967. /// <param name="points"></param>
  968. /// <returns></returns>
  969. public static bool ContainsAnyPt(Rect rect, IEnumerable<Point> points)
  970. {
  971. foreach (var point in points)
  972. {
  973. if (point.X > rect.X && point.X < rect.X + rect.Width && point.Y < rect.BottomRight.Y && point.Y > rect.Y)
  974. return true;
  975. }
  976. return false;
  977. }
  978. /// <summary>
  979. /// 用任意两点组成一个矩形
  980. /// </summary>
  981. /// <param name="p1"></param>
  982. /// <param name="p2"></param>
  983. /// <returns></returns>
  984. public static Rect FromTowPoint(Point p1, Point p2)
  985. {
  986. if (p1.X == p2.X || p1.Y == p2.Y)
  987. return Rect.Empty;
  988. if (p1.X > p2.X && p1.Y < p2.Y)
  989. {
  990. (p1, p2) = (p2, p1);
  991. }
  992. else if (p1.X > p2.X && p1.Y > p2.Y)
  993. {
  994. (p1.X, p2.X) = (p2.X, p1.X);
  995. }
  996. else if (p1.X < p2.X && p1.Y < p2.Y)
  997. {
  998. (p1.Y, p2.Y) = (p2.Y, p1.Y);
  999. }
  1000. return Rect.FromLTRB(p1.X, p2.Y, p2.X, p1.Y);
  1001. }
  1002. #endregion
  1003. public static Mat CannyOperator(Mat srcImg, double threshold1 = 100, double threshold2 = 200)
  1004. {
  1005. var dst = new Mat();// srcImg.Rows, srcImg.Cols,MatType.CV_8UC1);
  1006. //转灰度
  1007. Cv2.CvtColor(srcImg, dst, ColorConversionCodes.RGB2GRAY);
  1008. //滤波
  1009. Cv2.Blur(dst, dst, new OpenCvSharp.Size(2, 2));
  1010. //double threshold1 = 255, threshold2 = 0;
  1011. Cv2.Canny(srcImg, dst, threshold1, threshold2);
  1012. //Cv2.ImShow("dst", dst);
  1013. return dst;
  1014. }
  1015. public static Mat LaplacianOperator(Mat srcImg, double threshold1 = 10, double threshold2 = 255)
  1016. {
  1017. Mat LaplacianImg = new Mat();
  1018. Mat gussImage = new Mat();
  1019. //高斯滤波: 每个像素点的值都由本身与和邻近区域的其他像素值经过加权平均后得到,加权系数越靠近中心越大,越远离中心越小
  1020. /* src:输入图像
  1021. dst:输出图像
  1022. ksize:高斯核的大小。ksize。宽度和高度可以不同,但它们都必须是正的和奇数的。或者,它们可以是0然后用sigma来计算
  1023. sigmaX:表示高斯核在X轴方向的标准偏差
  1024. sigmaY :表示高斯核在Y轴方向的标准偏差值,如果sigmaY 为0,则sigmaY =sigmaX,如果两个sigma都为零,则用ksize计算
  1025. borderType :一般用默认值
  1026. */
  1027. Cv2.GaussianBlur(srcImg, gussImage, new OpenCvSharp.Size(3, 3), 0, 0, BorderTypes.Default);
  1028. Mat grayImage = new Mat();
  1029. Cv2.CvtColor(gussImage, grayImage, ColorConversionCodes.RGB2GRAY); //灰度图
  1030. //Laplacian运算, 计算二阶导数
  1031. /*src 源图像
  1032. dst 输出图像,将具有与src相同的大小和相同数量的通道
  1033. ddepth 目标图像的所需深度 默认填 -1,与源图一致
  1034. ksize 用于计算二阶导数滤波器的孔径大小,卷积核大小,奇数
  1035. scale 计算的拉普拉斯值的可选缩放因子(默认情况下不应用缩放)
  1036. delta 可选的增量值,在将结果存储到dst之前添加到结果中
  1037. borderType 边缘处理方法
  1038. */
  1039. Cv2.Laplacian(grayImage, LaplacianImg, -1, 3); //参数:1,源图像;2,输出图像;3,目标图像的所需深度 默认填 -1,与源图一致;4,用于计算二阶导数滤波器的卷积核大小,需奇数。
  1040. //阈值操作:可根据灰度的差异来分割图像
  1041. /* src:输入图像
  1042. dst:输出图像
  1043. thresh:阈值
  1044. maxval:阈值最大
  1045. type:阈值类型,详解见下
  1046. Binary:阈值二值化(大于阈值的让它等于最大值,小于的等于最小值)
  1047. BinaryInv:阈值反二值化(二值化阈值相反,大于阈值为最小值,小于阈值为最大值)
  1048. Trunc:截断(大于阈值的就等于阈值,小的不变)
  1049. ToZero:阈值归零(当大于阈值的不变,小于阈值的归零)
  1050. ToZeroIv:阈值归零取反(与阈值取零相反,大于时为最小值,小于时保持不变)
  1051. */
  1052. Mat dst = new Mat();
  1053. Cv2.Threshold(LaplacianImg, dst, threshold1, threshold2, ThresholdTypes.Binary);
  1054. return dst;
  1055. }
  1056. //Sobel算子主要用来检测离散微分边缘算子,Sobel算子对噪声灰常敏感,一般需要先把图片进行高斯降噪
  1057. public static Mat SobelOperator(Mat src_img, double threshold1 = 10, double threshold2 = 250)
  1058. {
  1059. Mat dst = new Mat();
  1060. //高斯滤波
  1061. Cv2.GaussianBlur(src_img, dst, new OpenCvSharp.Size(3, 3), 0, 0, BorderTypes.Default);
  1062. Mat grayImage = new Mat();
  1063. Cv2.CvtColor(dst, grayImage, ColorConversionCodes.BGR2GRAY); //转换为灰度图
  1064. Mat X = new Mat();
  1065. Mat Y = new Mat();
  1066. /*src:输入图像
  1067. dst:输出图像
  1068. ddepth:输出图像深度
  1069. xorder:X方向的差分阶数
  1070. yorder:Y方向的差分阶数
  1071. ksize :表示Sobel核大小,只能为奇数
  1072. scale: 计算导数值时候的缩放因子,默认为1
  1073. delta :表示存入目标图前可选的delta值
  1074. borderType :边界模式,一般为默认
  1075. */
  1076. Cv2.Sobel(grayImage, X, MatType.CV_16S, 1, 0, 3); //Sobel边缘查找,参数:1,输入;2,输出X方向梯度图像;3,输出图像的深度;4,X方向几阶导数;5,Y方向几阶导数;6,卷积核大小,必须为奇数。
  1077. Cv2.Sobel(grayImage, Y, MatType.CV_16S, 0, 1, 3); //输出Y方向梯度图像
  1078. #region 方式1:像素操作进行相加
  1079. int width = X.Cols;
  1080. int hight = Y.Rows;
  1081. Mat output = new Mat(X.Size(), X.Type());
  1082. for (int x = 0; x < hight; x++) //合并X和Y,G= (Gx*Gx +Gy*Gy)的开平方根
  1083. {
  1084. for (int y = 0; y < width; y++)
  1085. {
  1086. int xg = X.At<byte>(x, y); //获取像素点的值
  1087. int yg = Y.At<byte>(x, y);
  1088. double v1 = Math.Pow(xg, 2); //平方
  1089. double v2 = Math.Pow(yg, 2);
  1090. int val = (int)Math.Sqrt(v1 + v2); //开平方根
  1091. if (val > 255) //确保像素值在 0至255之间
  1092. {
  1093. val = 255;
  1094. }
  1095. if (val < 0)
  1096. {
  1097. val = 0;
  1098. }
  1099. byte xy = (byte)val;
  1100. output.Set<byte>(x, y, xy); //为图像设置像素值
  1101. }
  1102. }
  1103. Mat tmp = new Mat(output.Size(), MatType.CV_8UC1);
  1104. #endregion
  1105. #region 方式2:利用现有API实现(X梯度+Y梯度)
  1106. //Mat Abs_X = new Mat();
  1107. //Mat Abs_Y = new Mat();
  1108. //Mat Result = new Mat();
  1109. //Cv2.ConvertScaleAbs(X, Abs_X, 1.0);//缩放,计算绝对值并将结果转换为8位。
  1110. //Cv2.ConvertScaleAbs(Y, Abs_Y, 1.0);//缩放,计算绝对值并将结果转换为8位。
  1111. //Cv2.AddWeighted(Abs_X, 0.5, Abs_Y, 0.5, 0, Result);//以不同的权重将两幅图片叠加
  1112. #endregion
  1113. //阈值
  1114. Mat result = new Mat();
  1115. Cv2.Threshold(tmp, result, threshold1, threshold2, ThresholdTypes.Binary);
  1116. return result;
  1117. }
  1118. //Scharr算子是对Sobel算子的优化,特别在核为3*3时
  1119. public static Mat ScharrOperator(Mat srcImg, double threshold1 = 10, double threshold2 = 250)
  1120. {
  1121. Mat dst = new Mat();
  1122. Cv2.GaussianBlur(srcImg, dst, new OpenCvSharp.Size(3, 3), 0, 0, BorderTypes.Default);
  1123. Mat grayImage = new Mat();
  1124. Cv2.CvtColor(dst, grayImage, ColorConversionCodes.BGR2GRAY); //转换为灰度图
  1125. Mat grad_x = new Mat();
  1126. Mat grad_x2 = new Mat();
  1127. Mat grad_y = new Mat();
  1128. Mat grad_y2 = new Mat();
  1129. Cv2.Scharr(grayImage, grad_x, MatType.CV_16S, 1, 0);
  1130. Cv2.Scharr(grayImage, grad_y, MatType.CV_16S, 0, 1);
  1131. Cv2.ConvertScaleAbs(grad_x, grad_x2);
  1132. Cv2.ConvertScaleAbs(grad_y, grad_y2);
  1133. Mat result = new Mat();
  1134. Cv2.AddWeighted(grad_x2, 0.5, grad_y2, 0.5, 0, result);
  1135. //阈值
  1136. Cv2.Threshold(result, result, threshold1, threshold2, ThresholdTypes.Binary);
  1137. //Cv2.ImShow("Scharr", result);
  1138. return result;
  1139. }
  1140. }
  1141. }