革博士V2程序
Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

OpenCVUtil.cs 50 KiB

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