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

645 строки
32 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using OpenCvSharp;
  7. namespace LeatherApp.Utils
  8. {
  9. public class OpenCVUtil
  10. {
  11. public static Mat resize(Mat mat, int width, int height)
  12. {
  13. OpenCvSharp.Size dsize = new OpenCvSharp.Size(width, height);
  14. Mat mat2 = new Mat();
  15. Cv2.Resize(mat, mat2, dsize);
  16. return mat2;
  17. }
  18. 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)
  19. {
  20. //Mat mat = new Mat();
  21. //Cv2.CvtColor(mat, mat, ColorConversionCodes.BGR2RGB);
  22. ratio = Math.Min((float)sz.Width / (float)mat.Width, (float)sz.Height / (float)mat.Height);
  23. if (!scaleup)
  24. {
  25. ratio = Math.Min(ratio, 1f);
  26. }
  27. OpenCvSharp.Size dsize = new OpenCvSharp.Size((int)Math.Round((float)mat.Width * ratio), (int)Math.Round((float)mat.Height * ratio));
  28. int num = sz.Width - dsize.Width;
  29. int num2 = sz.Height - dsize.Height;
  30. float num3 = (float)sz.Height / (float)sz.Width;
  31. float num4 = (float)mat.Height / (float)mat.Width;
  32. if (auto && num3 != num4)
  33. {
  34. bool flag = false;
  35. }
  36. else if (scaleFill)
  37. {
  38. num = 0;
  39. num2 = 0;
  40. dsize = sz;
  41. }
  42. int num5 = (int)Math.Round((float)num / 2f);
  43. int num6 = (int)Math.Round((float)num2 / 2f);
  44. int num7 = 0;
  45. int num8 = 0;
  46. if (num5 * 2 != num)
  47. {
  48. num7 = num - num5 * 2;
  49. }
  50. if (num6 * 2 != num2)
  51. {
  52. num8 = num2 - num6 * 2;
  53. }
  54. if (mat.Width != dsize.Width || mat.Height != dsize.Height)
  55. {
  56. Cv2.Resize(mat, mat, dsize);
  57. }
  58. Cv2.CopyMakeBorder(mat, mat, num6 + num8, num6, num5, num5 + num7, BorderTypes.Constant, color);
  59. diff = new OpenCvSharp.Point(num5, num6);
  60. diff2 = new OpenCvSharp.Point(num7, num8);
  61. return mat;
  62. }
  63. /// <summary>
  64. /// 裁切指定区域
  65. /// </summary>
  66. /// <param name="mat"></param>
  67. /// <param name="x"></param>
  68. /// <param name="y"></param>
  69. /// <param name="width"></param>
  70. /// <param name="height"></param>
  71. /// <returns></returns>
  72. public static Mat cutImage(Mat mat, int x, int y, int width, int height)
  73. {
  74. Rect roi = new Rect(x, y, width, height);
  75. return new Mat(mat, roi).Clone();
  76. }
  77. /// <summary>
  78. /// 合并MAT(宽高必需一致)
  79. /// </summary>
  80. /// <param name="mats"></param>
  81. /// <param name="isHorizontal"></param>
  82. /// <returns></returns>
  83. public static Mat mergeImage_sameSize(Mat[] mats, bool isHorizontal = true)
  84. {
  85. Mat matOut = new Mat();
  86. if (isHorizontal)
  87. Cv2.HConcat(mats, matOut);//横向拼接
  88. else
  89. Cv2.VConcat(mats, matOut);//纵向拼接
  90. return matOut;
  91. }
  92. /// <summary>
  93. /// 合并MAT-纵向
  94. /// </summary>
  95. /// <param name="mat1"></param>
  96. /// <param name="mat2"></param>
  97. /// <returns></returns>
  98. public static Mat mergeImageV(Mat mat1,Mat mat2 )
  99. {
  100. Mat matOut = new Mat();
  101. //push_back 方法将图像2拷贝到图像1的最后一行
  102. Mat img_merge = new Mat();//要先设置大小吗
  103. img_merge.PushBack(mat1);
  104. img_merge.PushBack(mat2);
  105. return matOut;
  106. }
  107. /// <summary>
  108. /// 合并MAT-横向
  109. /// </summary>
  110. /// <param name="mat1"></param>
  111. /// <param name="mat2"></param>
  112. /// <returns></returns>
  113. public static Mat mergeImageH(Mat[] mats)
  114. {
  115. Stitcher stitcher = Stitcher.Create(Stitcher.Mode.Scans);
  116. Mat pano = new Mat();
  117. var status = stitcher.Stitch(mats, pano);
  118. if (status == Stitcher.Status.OK)
  119. return pano;
  120. else
  121. return null;
  122. // //1.新建一个要合并的图像
  123. // Size size = new Size(image1.Cols + image2.Cols, Math.Max(image1.Rows, image1.Rows));
  124. //Mat img_merge=new Mat();
  125. //img_merge.Create(size,new MatType( image1.Depth()));
  126. ////img_merge = Scalar.All(0);
  127. //Mat outImg_left, outImg_right;
  128. ////2.在新建合并图像中设置感兴趣区域
  129. //outImg_left = img_merge.a(Rect(0, 0, image1.cols, image1.rows));
  130. //outImg_right = img_merge(Rect(image1.cols, 0, image1.cols, image1.rows));
  131. ////3.将待拷贝图像拷贝到感性趣区域中
  132. //image1.copyTo(outImg_left);
  133. //image2.copyTo(outImg_right);
  134. //namedWindow("image1", 0);
  135. //Cv2.ImShow("image1", img_merge);
  136. }
  137. /// <summary>
  138. /// 获取最小外接矩形(正矩形)
  139. /// </summary>
  140. /// <returns></returns>
  141. public static Mat getMimOutRect(Mat srcImg)
  142. {
  143. try
  144. {
  145. //Mat srcImg = new Mat(@"E:\D\AutoCode\LeatherProject\LeatherApp\bin\Debug\testpic\2\11.bmp");
  146. Mat grayImg = new Mat();
  147. Mat binaryImg = new Mat();
  148. Cv2.CvtColor(srcImg, grayImg, ColorConversionCodes.BGR2GRAY);
  149. //Cv2.ImShow("src", srcImg);
  150. //toImg(this.pictureBox1, grayImg);
  151. //
  152. //double thresh = 30;//小于此值(超小超是所选黑色越多)转为maxval色
  153. //double maxval = 255;//上面值转为255白色
  154. double thresh = 80;//小于此值(超小超是所选黑色越多)转为maxval色
  155. double maxval = 255;//上面值转为255白色
  156. Cv2.Threshold(grayImg, binaryImg, thresh, maxval, ThresholdTypes.Binary);//转化黑白二值图 thresh:阀值
  157. //颜色反转
  158. //byte grayPixel = 0;
  159. //for (int r = 0; r < binary.Rows; r++)
  160. //{
  161. // for (int c = 0; c < binary.Cols; c++)
  162. // {
  163. // grayPixel = binary.At<byte>(r, c);
  164. // binary.Set<byte>(r, c, (byte)(255 - grayPixel));
  165. // }
  166. //}
  167. //FindContours让轮廓
  168. OpenCvSharp.Point[][] contours; //轮廓查找结果变量
  169. HierarchyIndex[] hierarchy; //轮廓拓扑结构变量
  170. //====RetrievalModes:
  171. //CV_RETR_EXTERNAL表示只检测外轮廓
  172. //CV_RETR_LIST检测的轮廓不建立等级关系
  173. //CV_RETR_CCOMP建立两个等级的轮廓,上面的一层为外边界,里面的一层为内孔的边界信息。如果内孔内还有一个连通物体,这个物体的边界也在顶层。
  174. //CV_RETR_TREE建立一个等级树结构的轮廓。具体参考contours.c这个demo
  175. //====ContourApproximationModes:
  176. //CV_CHAIN_APPROX_NONE存储所有的轮廓点,相邻的两个点的像素位置差不超过1,即max(abs(x1 - x2),abs(y2 - y1))== 1
  177. //CV_CHAIN_APPROX_SIMPLE压缩水平方向,垂直方向,对角线方向的元素,只保留该方向的终点坐标,例如一个矩形轮廓只需4个点来保存轮廓信息
  178. //CV_CHAIN_APPROX_TC89_L1,CV_CHAIN_APPROX_TC89_KCOS使用teh - Chinl chain 近似算法
  179. Cv2.FindContours(binaryImg, out contours, out hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple);
  180. //DrawContours将结果画出并返回结果
  181. Mat dst_Image = Mat.Zeros(grayImg.Size(), srcImg.Type());
  182. Random rnd = new Random();
  183. int maxIndex = 0, maxLength = 0;
  184. for (int i = 0; i < contours.Length; i++)
  185. {
  186. if (contours[i].Length > maxLength)
  187. {
  188. maxLength = contours[i].Length;
  189. maxIndex = i;
  190. }
  191. }
  192. Scalar color = new Scalar(rnd.Next(0, 0), rnd.Next(0, 255), rnd.Next(0, 255));
  193. //var rectMin = Cv2.MinAreaRect(contours[i]);
  194. //这里有三个参数 分别是中心位置,旋转角度,缩放程度
  195. //Cv2.WarpAffine(srcImg, rectMin.Center, (height, width))
  196. //Rect rect = rectMin.BoundingRect();//
  197. Rect rect = Cv2.BoundingRect(contours[maxIndex]);// 获取矩形边界框
  198. //OpenCvSharp.Point pt1 = new OpenCvSharp.Point(rect.X, rect.Y);
  199. //OpenCvSharp.Point pt2 = new OpenCvSharp.Point(rect.X + rect.Width, rect.Y + rect.Height); //定义矩形对顶点
  200. //Cv2.Rectangle(srcImg, pt1, pt2, color, 1); //绘制矩形边框
  201. //Cv2.Line(srcImg, pt1, pt2, color, 1); //矩形单个对角线相,两点
  202. //Cv2.DrawContours(srcImg, contours, maxIndex, color, 2, LineTypes.Link8, hierarchy);
  203. //toImg(this.pictureBox1, srcImg);
  204. //return cutImage(srcImg, rect.X, rect.Y, rect.Width, rect.Height);
  205. return cutImage(srcImg, rect.X, 0, rect.Width, rect.Height);
  206. //
  207. //建立轮廓接受数组
  208. //Point[][] contours;
  209. //HierarchyIndex[] hierarchy;
  210. //Cv2.FindContours(binary, out contours, out hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxNone);
  211. //最小外接矩形接收数组
  212. //RotatedRect[] rotateRect = new RotatedRect[contours.Length];
  213. //Point[][] contours_poly = new Point[contours.Length][];
  214. //int maxPointCount = 0, index = -1;
  215. //for (int x = 0; x < contours.Length; x++)
  216. //{
  217. // if (maxPointCount < contours[x].Length)
  218. // {
  219. // maxPointCount = contours[x].Length;
  220. // index = x;
  221. // }
  222. //}
  223. }
  224. catch (Exception ex)
  225. {
  226. return null;
  227. }
  228. }
  229. #region 获取最大内接矩形
  230. /// <summary>
  231. /// 获取最大内接矩形(高度使用原图值未裁剪)
  232. /// </summary>
  233. /// <param name="srcImg"></param>
  234. /// <returns></returns>
  235. public static Mat getMaxInsetRect(Mat srcImg, double thresh = 45, double maxval = 255)
  236. {
  237. API.OutputDebugString("--------start:"+DateTime.Now.ToString("mm:ss fff"));
  238. var dst = new Mat();
  239. //转灰度
  240. Cv2.CvtColor(srcImg, dst, ColorConversionCodes.RGB2GRAY);
  241. API.OutputDebugString("--------转灰度:" + DateTime.Now.ToString("mm:ss fff"));
  242. //转化黑白二值图 thresh:阀值
  243. //double thresh = 50;//小于此值(超小超是所选黑色越多)转为maxval色
  244. //double maxval = 255;//上面值转为255白色
  245. Cv2.Threshold(dst, dst, thresh, maxval, ThresholdTypes.Binary);
  246. API.OutputDebugString("--------黑白二值图:" + DateTime.Now.ToString("mm:ss fff"));
  247. //取轮廓
  248. Cv2.FindContours(dst, out var contours, out var hierarchy, RetrievalModes.External, ContourApproximationModes.ApproxSimple);
  249. int maxIndex = 0, maxLength = 0;
  250. for (int i = 0; i < contours.Length; i++)
  251. {
  252. if (contours[i].Length > maxLength)
  253. {
  254. maxLength = contours[i].Length;
  255. maxIndex = i;
  256. }
  257. }
  258. API.OutputDebugString("--------取全部轮廓:" + DateTime.Now.ToString("mm:ss fff"));
  259. List<List<Point>> approxContours = new List<List<Point>>();
  260. //先求出多边形的近似轮廓,减少轮廓数量,方便后面计算
  261. var approxContour = Cv2.ApproxPolyDP(contours[maxIndex], 20, true);
  262. API.OutputDebugString("--------减少轮廓数量:" + DateTime.Now.ToString("mm:ss fff"));
  263. approxContours.Add(approxContour.ToList());
  264. //绘制边缘
  265. //DrawContour(srcImg, approxContour, Scalar.Red, 20);
  266. //return srcImg;
  267. Rect rect = GetMaxInscribedRect(srcImg, approxContour.ToList());
  268. API.OutputDebugString("--------取最大内切矩形:" + DateTime.Now.ToString("mm:ss fff"));
  269. var result= cutImage(srcImg, rect.X, 0, rect.Width, srcImg.Height);
  270. API.OutputDebugString("--------裁剪完成:" + DateTime.Now.ToString("mm:ss fff"));
  271. return result;
  272. }
  273. public static Mat getMaxInsetRect2(Mat mat_rgb,bool isLeft,int marginHoleWidth,out int marginWidth)
  274. {
  275. //Mat mat_rgb = new Mat("E:\\CPL\\测试代码\\边缘检测\\test\\test\\test\\img\\19.bmp");
  276. Mat image_gray = new Mat();
  277. Cv2.CvtColor(mat_rgb, image_gray, ColorConversionCodes.BGR2GRAY);
  278. //cvtColor(image_RGB, image, COLOR_RGB2GRAY);
  279. int height = image_gray.Rows;
  280. int width = image_gray.Cols;
  281. // 算法定义:取均分5段图片的五条横线,经过一系列处理之后,二值化,找到沿边位置,然后取均值作为直边,在缩进一段有针眼的位置
  282. // 定义每段的行数
  283. int num_rows = 5;
  284. int segment_height = height / num_rows - 1;
  285. // 定义空数组保存结果
  286. int[] total = new int[num_rows];
  287. // 平均截取5行数据并处理图像
  288. for (int i = 0; i < num_rows; i++)
  289. {
  290. // 截取当前行的图像
  291. int start_row = i * segment_height;
  292. Rect roi = new Rect(0, start_row, width, 1);
  293. Mat current_segment = image_gray.Clone(roi);
  294. // 对当前行的图像进行平滑处理
  295. Mat smoothed_image = new Mat();
  296. Cv2.GaussianBlur(current_segment, smoothed_image, new Size(5, 1), 0);
  297. // 计算当前行的灰度直方图
  298. Mat absolute_histo = new Mat();
  299. Cv2.CalcHist(new Mat[] { smoothed_image }, new int[] { 0 }, new Mat(), absolute_histo, 1, new int[] { 256 }, new Rangef[] { new Rangef(0, 256) });
  300. Cv2.GaussianBlur(current_segment, smoothed_image, new Size(9, 1), 0);
  301. // 对图片进行分割i+1
  302. //double otsu_threshold;
  303. //threshold(smoothed_image, smoothed_image, 0, 255, THRESH_BINARY + THRESH_OTSU, &otsu_threshold);
  304. Cv2.Threshold(smoothed_image, smoothed_image, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);
  305. // 使用形态学操作进行孔洞填充
  306. Mat kernel = Cv2.GetStructuringElement(MorphShapes.Rect, new Size(5, 1));
  307. Mat filled_image = new Mat();
  308. Cv2.MorphologyEx(smoothed_image, filled_image, MorphTypes.Close, kernel);
  309. // 取较长的一个值作为皮革的宽度
  310. int num_255 = Cv2.CountNonZero(filled_image);
  311. int length_t = (num_255 > width / 2) ? num_255 : width - num_255;
  312. total[i] = (length_t);
  313. API.OutputDebugString($"getMaxInsetRect2: 【{i + 1}】{length_t}={num_255}|{width}");
  314. }
  315. // 取平均值作为宽度
  316. int length = (int)total.Average();
  317. marginWidth = width-length;
  318. // 判断数据是否异常,判断当前线段的宽度是否大于设定像素的偏差
  319. //int abnormal_pxl = 200;
  320. //for (int i = 0; i < num_rows; i++)
  321. //{
  322. // if (Math.Abs(total[i] - length) > abnormal_pxl)
  323. // throw new Exception("数据异常,当段图片的宽度有问题!");
  324. //}
  325. //右侧相机,拍摄产品,边缘位于右侧判断,缩进100像素,去点针眼
  326. //Cv2.Line(mat_rgb, new Point(length - 100, 0), new Point(length - 100, height), new Scalar(255, 0, 0), 20);
  327. ////左侧相机,拍摄产品,边缘位于左侧判断,缩进100像素,去点针眼
  328. //Cv2.Line(mat_rgb, new Point(width - length + 100, 0), new Point(width - length + 100, height), new Scalar(0, 255, 0), 20);
  329. //int decWidth = width - length + marginHoleWidth;
  330. //if (isLeft)
  331. // return cutImage(mat_rgb, decWidth, 0, width- decWidth, height);
  332. //else
  333. // return cutImage(mat_rgb, 0, 0, width - decWidth, height);
  334. API.OutputDebugString($"getMaxInsetRect2:margin={marginWidth},length={length}({marginHoleWidth}),isLeft={isLeft},mat_rgb={mat_rgb.Width}*{mat_rgb.Height},w={length - marginHoleWidth},h={height}");
  335. if (isLeft)
  336. return cutImage(mat_rgb, width - length+ marginHoleWidth, 0, length- marginHoleWidth, height);
  337. else
  338. return cutImage(mat_rgb, 0, 0, length- marginHoleWidth, height);
  339. }
  340. private static Rect GetMaxInscribedRect(Mat src, List<Point> contour)
  341. {
  342. //根据轮廓让点与下一个点之间形成一个矩形,然后让每个矩形都与当前所有矩形相交,求出相交的矩形,
  343. //再把这些矩形所有的角放到一个集合里,筛选出在轮廓内并且非重复的点,
  344. //最后让这些点两两组合成一个矩形,判断是否为内部矩形,算出面积,找出最大内接矩形。
  345. //比如一共4个点,第1个与第2个形成矩形(矩形1),第1与第3(矩形2),
  346. //第1与第4(矩形3),第2与第3(矩形4),第2与第4(矩形5),第3与第4(矩形6),
  347. //由于矩形1为第一个元素,没有相交矩形,所以直接放入allPoint中,
  348. //接着把矩形2的四个角,以及矩形2和矩形1相交矩形的四个角,放入allPoint中,
  349. //矩形3以此类推,其本身四个角,以及和矩形1相交矩形的四个角,以及和矩形2相交矩形的四个角
  350. Rect maxInscribedRect = new Rect();
  351. List<Rect> allRect = new List<Rect>();
  352. List<Point> allPoint = new List<Point>(contour);
  353. //根据轮廓让点与下一个点之间形成一个矩形
  354. for (int i = 0; i < contour.Count; i++)
  355. {
  356. for (int j = i + 1; j < contour.Count; j++)
  357. {
  358. var p1 = contour[i];
  359. var p2 = contour[j];
  360. if (p1.Y == p2.Y || p1.X == p2.X)
  361. continue;
  362. var tempRect = FromTowPoint(p1, p2);
  363. allPoint.AddRange(GetAllCorner(tempRect));
  364. //让每个矩形都与当前所有矩形相交,求出相交的矩形,再把这些矩形所有的角放到一个集合里
  365. foreach (var rect in allRect)
  366. {
  367. var intersectR = tempRect.Intersect(rect);
  368. if (intersectR != Rect.Empty)
  369. allPoint.AddRange(GetAllCorner(intersectR));
  370. }
  371. allRect.Add(tempRect);
  372. }
  373. }
  374. //去除重复的点,再让这些点两两组合成一个矩形,判断是否为内部矩形,算出面积,找出最大内接矩形
  375. List<Point> distinctPoints = allPoint.Distinct().ToList();
  376. for (int i = 0; i < distinctPoints.Count; i++)
  377. {
  378. for (int j = i + 1; j < distinctPoints.Count; j++)
  379. {
  380. var tempRect = FromTowPoint(distinctPoints[i], distinctPoints[j]);
  381. //只要矩形包含一个轮廓内的点,就不算多边形的内部矩形;只要轮廓不包含该矩形,该矩形就不算多边形的内部矩形
  382. if (!ContainPoints(contour, GetAllCorner(tempRect)) || ContainsAnyPt(tempRect, contour))
  383. continue;
  384. //src.Rectangle(tempRect, Scalar.RandomColor(), 2);
  385. if (tempRect.Width * tempRect.Height > maxInscribedRect.Width * maxInscribedRect.Height)
  386. maxInscribedRect = tempRect;
  387. }
  388. }
  389. //src.Rectangle(maxInscribedRect, Scalar.Yellow, 2);
  390. return maxInscribedRect == Rect.Empty ? Cv2.BoundingRect(contour) : maxInscribedRect;
  391. }
  392. public static Point[] GetAllCorner(Rect rect)
  393. {
  394. Point[] result = new Point[4];
  395. result[0] = rect.Location;
  396. result[1] = new Point(rect.X + rect.Width, rect.Y);
  397. result[2] = rect.BottomRight;
  398. result[3] = new Point(rect.X, rect.Y + rect.Height);
  399. return result;
  400. }
  401. private static bool ContainPoint(List<Point> contour, Point p1)
  402. {
  403. return Cv2.PointPolygonTest(contour, p1, false) > 0;
  404. }
  405. private static bool ContainPoints(List<Point> contour, IEnumerable<Point> points)
  406. {
  407. foreach (var point in points)
  408. {
  409. if (Cv2.PointPolygonTest(contour, point, false) < 0)
  410. return false;
  411. }
  412. return true;
  413. }
  414. private static void DrawContour(Mat mat, Point[] contour, Scalar color, int thickness)
  415. {
  416. for (int i = 0; i < contour.Length; i++)
  417. {
  418. if (i + 1 < contour.Length)
  419. Cv2.Line(mat, contour[i], contour[i + 1], color, thickness);
  420. }
  421. }
  422. /// <summary>
  423. /// 是否有任意一个点集合中的点包含在矩形内,在矩形边界上不算包含
  424. /// </summary>
  425. /// <param name="rect"></param>
  426. /// <param name="points"></param>
  427. /// <returns></returns>
  428. public static bool ContainsAnyPt(Rect rect, IEnumerable<Point> points)
  429. {
  430. foreach (var point in points)
  431. {
  432. if (point.X > rect.X && point.X < rect.X + rect.Width && point.Y < rect.BottomRight.Y && point.Y > rect.Y)
  433. return true;
  434. }
  435. return false;
  436. }
  437. /// <summary>
  438. /// 用任意两点组成一个矩形
  439. /// </summary>
  440. /// <param name="p1"></param>
  441. /// <param name="p2"></param>
  442. /// <returns></returns>
  443. public static Rect FromTowPoint(Point p1, Point p2)
  444. {
  445. if (p1.X == p2.X || p1.Y == p2.Y)
  446. return Rect.Empty;
  447. if (p1.X > p2.X && p1.Y < p2.Y)
  448. {
  449. (p1, p2) = (p2, p1);
  450. }
  451. else if (p1.X > p2.X && p1.Y > p2.Y)
  452. {
  453. (p1.X, p2.X) = (p2.X, p1.X);
  454. }
  455. else if (p1.X < p2.X && p1.Y < p2.Y)
  456. {
  457. (p1.Y, p2.Y) = (p2.Y, p1.Y);
  458. }
  459. return Rect.FromLTRB(p1.X, p2.Y, p2.X, p1.Y);
  460. }
  461. #endregion
  462. public static Mat CannyOperator(Mat srcImg, double threshold1 = 100, double threshold2 = 200)
  463. {
  464. var dst = new Mat();// srcImg.Rows, srcImg.Cols,MatType.CV_8UC1);
  465. //转灰度
  466. Cv2.CvtColor(srcImg, dst, ColorConversionCodes.RGB2GRAY);
  467. //滤波
  468. Cv2.Blur(dst, dst, new OpenCvSharp.Size(2, 2));
  469. //double threshold1 = 255, threshold2 = 0;
  470. Cv2.Canny(srcImg, dst, threshold1, threshold2);
  471. //Cv2.ImShow("dst", dst);
  472. return dst;
  473. }
  474. public static Mat LaplacianOperator(Mat srcImg, double threshold1 = 10, double threshold2 = 255)
  475. {
  476. Mat LaplacianImg = new Mat();
  477. Mat gussImage = new Mat();
  478. //高斯滤波: 每个像素点的值都由本身与和邻近区域的其他像素值经过加权平均后得到,加权系数越靠近中心越大,越远离中心越小
  479. /* src:输入图像
  480. dst:输出图像
  481. ksize:高斯核的大小。ksize。宽度和高度可以不同,但它们都必须是正的和奇数的。或者,它们可以是0然后用sigma来计算
  482. sigmaX:表示高斯核在X轴方向的标准偏差
  483. sigmaY :表示高斯核在Y轴方向的标准偏差值,如果sigmaY 为0,则sigmaY =sigmaX,如果两个sigma都为零,则用ksize计算
  484. borderType :一般用默认值
  485. */
  486. Cv2.GaussianBlur(srcImg, gussImage, new OpenCvSharp.Size(3, 3), 0, 0, BorderTypes.Default);
  487. Mat grayImage = new Mat();
  488. Cv2.CvtColor(gussImage, grayImage, ColorConversionCodes.RGB2GRAY); //灰度图
  489. //Laplacian运算, 计算二阶导数
  490. /*src 源图像
  491. dst 输出图像,将具有与src相同的大小和相同数量的通道
  492. ddepth 目标图像的所需深度 默认填 -1,与源图一致
  493. ksize 用于计算二阶导数滤波器的孔径大小,卷积核大小,奇数
  494. scale 计算的拉普拉斯值的可选缩放因子(默认情况下不应用缩放)
  495. delta 可选的增量值,在将结果存储到dst之前添加到结果中
  496. borderType 边缘处理方法
  497. */
  498. Cv2.Laplacian(grayImage, LaplacianImg, -1, 3); //参数:1,源图像;2,输出图像;3,目标图像的所需深度 默认填 -1,与源图一致;4,用于计算二阶导数滤波器的卷积核大小,需奇数。
  499. //阈值操作:可根据灰度的差异来分割图像
  500. /* src:输入图像
  501. dst:输出图像
  502. thresh:阈值
  503. maxval:阈值最大
  504. type:阈值类型,详解见下
  505. Binary:阈值二值化(大于阈值的让它等于最大值,小于的等于最小值)
  506. BinaryInv:阈值反二值化(二值化阈值相反,大于阈值为最小值,小于阈值为最大值)
  507. Trunc:截断(大于阈值的就等于阈值,小的不变)
  508. ToZero:阈值归零(当大于阈值的不变,小于阈值的归零)
  509. ToZeroIv:阈值归零取反(与阈值取零相反,大于时为最小值,小于时保持不变)
  510. */
  511. Mat dst = new Mat();
  512. Cv2.Threshold(LaplacianImg, dst, threshold1, threshold2, ThresholdTypes.Binary);
  513. return dst;
  514. }
  515. //Sobel算子主要用来检测离散微分边缘算子,Sobel算子对噪声灰常敏感,一般需要先把图片进行高斯降噪
  516. public static Mat SobelOperator(Mat src_img, double threshold1 = 10, double threshold2 = 250)
  517. {
  518. Mat dst = new Mat();
  519. //高斯滤波
  520. Cv2.GaussianBlur(src_img, dst, new OpenCvSharp.Size(3, 3), 0, 0, BorderTypes.Default);
  521. Mat grayImage = new Mat();
  522. Cv2.CvtColor(dst, grayImage, ColorConversionCodes.BGR2GRAY); //转换为灰度图
  523. Mat X = new Mat();
  524. Mat Y = new Mat();
  525. /*src:输入图像
  526. dst:输出图像
  527. ddepth:输出图像深度
  528. xorder:X方向的差分阶数
  529. yorder:Y方向的差分阶数
  530. ksize :表示Sobel核大小,只能为奇数
  531. scale: 计算导数值时候的缩放因子,默认为1
  532. delta :表示存入目标图前可选的delta值
  533. borderType :边界模式,一般为默认
  534. */
  535. Cv2.Sobel(grayImage, X, MatType.CV_16S, 1, 0, 3); //Sobel边缘查找,参数:1,输入;2,输出X方向梯度图像;3,输出图像的深度;4,X方向几阶导数;5,Y方向几阶导数;6,卷积核大小,必须为奇数。
  536. Cv2.Sobel(grayImage, Y, MatType.CV_16S, 0, 1, 3); //输出Y方向梯度图像
  537. #region 方式1:像素操作进行相加
  538. int width = X.Cols;
  539. int hight = Y.Rows;
  540. Mat output = new Mat(X.Size(), X.Type());
  541. for (int x = 0; x < hight; x++) //合并X和Y,G= (Gx*Gx +Gy*Gy)的开平方根
  542. {
  543. for (int y = 0; y < width; y++)
  544. {
  545. int xg = X.At<byte>(x, y); //获取像素点的值
  546. int yg = Y.At<byte>(x, y);
  547. double v1 = Math.Pow(xg, 2); //平方
  548. double v2 = Math.Pow(yg, 2);
  549. int val = (int)Math.Sqrt(v1 + v2); //开平方根
  550. if (val > 255) //确保像素值在 0至255之间
  551. {
  552. val = 255;
  553. }
  554. if (val < 0)
  555. {
  556. val = 0;
  557. }
  558. byte xy = (byte)val;
  559. output.Set<byte>(x, y, xy); //为图像设置像素值
  560. }
  561. }
  562. Mat tmp = new Mat(output.Size(), MatType.CV_8UC1);
  563. #endregion
  564. #region 方式2:利用现有API实现(X梯度+Y梯度)
  565. //Mat Abs_X = new Mat();
  566. //Mat Abs_Y = new Mat();
  567. //Mat Result = new Mat();
  568. //Cv2.ConvertScaleAbs(X, Abs_X, 1.0);//缩放,计算绝对值并将结果转换为8位。
  569. //Cv2.ConvertScaleAbs(Y, Abs_Y, 1.0);//缩放,计算绝对值并将结果转换为8位。
  570. //Cv2.AddWeighted(Abs_X, 0.5, Abs_Y, 0.5, 0, Result);//以不同的权重将两幅图片叠加
  571. #endregion
  572. //阈值
  573. Mat result = new Mat();
  574. Cv2.Threshold(tmp, result, threshold1, threshold2, ThresholdTypes.Binary);
  575. return result;
  576. }
  577. //Scharr算子是对Sobel算子的优化,特别在核为3*3时
  578. public static Mat ScharrOperator(Mat srcImg, double threshold1 = 10, double threshold2 = 250)
  579. {
  580. Mat dst = new Mat();
  581. Cv2.GaussianBlur(srcImg, dst, new OpenCvSharp.Size(3, 3), 0, 0, BorderTypes.Default);
  582. Mat grayImage = new Mat();
  583. Cv2.CvtColor(dst, grayImage, ColorConversionCodes.BGR2GRAY); //转换为灰度图
  584. Mat grad_x = new Mat();
  585. Mat grad_x2 = new Mat();
  586. Mat grad_y = new Mat();
  587. Mat grad_y2 = new Mat();
  588. Cv2.Scharr(grayImage, grad_x, MatType.CV_16S, 1, 0);
  589. Cv2.Scharr(grayImage, grad_y, MatType.CV_16S, 0, 1);
  590. Cv2.ConvertScaleAbs(grad_x, grad_x2);
  591. Cv2.ConvertScaleAbs(grad_y, grad_y2);
  592. Mat result = new Mat();
  593. Cv2.AddWeighted(grad_x2, 0.5, grad_y2, 0.5, 0, result);
  594. //阈值
  595. Cv2.Threshold(result, result, threshold1, threshold2, ThresholdTypes.Binary);
  596. //Cv2.ImShow("Scharr", result);
  597. return result;
  598. }
  599. }
  600. }