效果
项目
代码
using OpenCvSharp;
using System;
using System.Drawing;
using System.Windows.Forms;namespace OpenCvSharp_实现迷宫解密
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){pictureBox1.Image = new Bitmap("test.png");}private void button1_Click(object sender, EventArgs e){//读取图片Mat src = Cv2.ImRead("test.png");//BGR2GRAYMat gray = new Mat();Cv2.CvtColor(src, gray, ColorConversionCodes.BGR2GRAY);//Cv2.ImShow("gray", gray);//1、对图像进行二值化处理//反转 产生一个二进制的图像与白色的墙壁和黑色的背景Mat thresh = new Mat();Cv2.Threshold(gray, thresh, 127, 255, ThresholdTypes.BinaryInv);// Cv2.ImShow("thresh", thresh);//2、对二值化后的图像进行轮廓检测并标注OpenCvSharp.Point[][] contours;HierarchyIndex[] hierarchly;Cv2.FindContours(thresh, out contours, out hierarchly, RetrievalModes.External, ContourApproximationModes.ApproxNone);Mat dc = Mat.Zeros(src.Size(), MatType.CV_8UC1);Cv2.DrawContours(dc, contours, 0, new Scalar(255, 255, 255), 6);//3、对图像阈值进行处理Cv2.Threshold(dc, thresh, 240, 255, ThresholdTypes.Binary);//Cv2.ImShow("thresh2", thresh);//4、对图像进行扩展操作/*扩张是数学形态领域的两个基本操作者之一,另一个是侵蚀。它通常应用于二进制图像,但有一些版本可用于灰度图像。操作者对二进制图像的基本效果是逐渐扩大前景像素区域的边界(通常为白色像素)。因此,前景像素的面积大小增加,而这些区域内的孔变小。*/Mat kernel = Mat.Ones(10, 10, MatType.CV_8UC1);Mat dilation = new Mat();Cv2.Dilate(thresh, dilation, kernel);//Cv2.ImShow("dilation", dilation);//5、对图像进行侵蚀操作/*侵蚀是第二个形态运算符。它也适用于二进制图像。操作者对二进制图像的基本效果是消除前景像素区域的边界(通常为白色像素)。因此,前景像素的面积缩小,并且这些区域内的孔变大。*/Mat erosion = new Mat();Cv2.Erode(dilation, erosion, kernel);//Cv2.ImShow("erosion", erosion);//6、分迷宫通道找出路径Mat diff = new Mat();Cv2.Absdiff(dilation, erosion, diff);Mat[] channels = Cv2.Split(src);channels[0] &= ~diff;channels[1] &= ~diff;channels[2] |= diff;Mat dst = new Mat();Cv2.Merge(channels, dst);//Cv2.ImShow("solution", dst);pictureBox2.Image = new Bitmap(dst.ToMemoryStream());}}
}
Demo下载