C# 查找迷宫路径

C# 查找迷宫路径_第1张图片

1.导入图像,并且将图像转灰度

using var img = new Image(_path);
using var grayImg = img.Convert();

2.自动二值化图像

using var inputGrayOut = new Image(grayImg.Size);
// 计算OTSU阈值
var threshold = CvInvoke.Threshold(grayImg, inputGrayOut, 0, 255, ThresholdType.BinaryInv | ThresholdType.Otsu);
// 二值化图像
using var binaryImage = inputGrayOut.ThresholdBinary(new Gray(threshold), new Gray(255));

C# 查找迷宫路径_第2张图片 

3.图像裁剪,只留下迷宫区域,如果不裁剪会出现最外围的路径

 using var dilated2 = new Mat();
CvInvoke.Dilate(binaryImage, dilated2, kernel, new Point(-1, -1), trackBar2.Value, BorderType.Default, new MCvScalar());
using Mat hierarchy3 = new Mat();
using VectorOfVectorOfPoint contours3 = new VectorOfVectorOfPoint();
CvInvoke.FindContours(dilated2, contours3, hierarchy3, RetrType.External, ChainApproxMethod.ChainApproxSimple);
using var binaryImage2=binaryImage.Copy(CvInvoke.BoundingRectangle(contours3[0]));

4.查找轮廓,并绘制在全黑图像上

using VectorOfVectorOfPoint contours = new VectorOfVectorOfPoint();
using Mat hierarchy = new Mat();
CvInvoke.FindContours(binaryImage2, contours, hierarchy, RetrType.External, ChainApproxMethod.ChainApproxSimple);
// 绘制在全黑图像上
using var draw = new Image(binaryImage2.Size);
CvInvoke.DrawContours(draw, contours, 0, new Bgr(255, 255, 255).MCvScalar,1);

C# 查找迷宫路径_第3张图片 

5.膨胀

 using var dilated = new Mat();
CvInvoke.Dilate(draw, dilated, kernel, new Point(-1, -1), trackBar2.Value, BorderType.Default, new MCvScalar());

C# 查找迷宫路径_第4张图片 

6.腐蚀

 using var eroded = new Mat();
 CvInvoke.Erode(dilated, eroded, kernel, new Point(-1, -1), trackBar2.Value, BorderType.Default, new MCvScalar());

C# 查找迷宫路径_第5张图片 

7.膨胀腐蚀相减

 using var diff = new Mat();
CvInvoke.AbsDiff(dilated, eroded, diff);

C# 查找迷宫路径_第6张图片 

8.在差异图diff中查找轮廓,并在原图上绘制轮廓(寻找最大边框绘画)

 using VectorOfVectorOfPoint contours2 = new VectorOfVectorOfPoint();
  using var hierarchy2 = new Mat();
//CvInvoke.CvtColor(diff, diff, ColorConversion.Bgr2Gray);
 CvInvoke.FindContours(diff, contours2, hierarchy2, RetrType.External, ChainApproxMethod.ChainApproxSimple);
            double maxArea = 0;
            int maxAreaIndex = 0;
            for (int i = 0; i < contours2.Size; i++)
            {
                double area = CvInvoke.ContourArea(contours2[i]);
                if (area > maxArea)
                {
                    maxArea = area;
                    maxAreaIndex = i;
                }
            }

            CvInvoke.DrawContours(img, contours2, maxAreaIndex, new Bgr(0, 0, 255).MCvScalar, 2);

C# 查找迷宫路径_第7张图片

你可能感兴趣的:(c#,开发语言)