该脚本仅适用于完美迷宫,即只有一个唯一解、没有分段、没有圆形区域和没有开放区域的迷宫。
这些完美的迷宫可以使用在线迷宫生成工具生成。
让我们以这个简单的迷宫作为测试图像:
解决完美迷宫的步骤是:
1. 加载源图像。
2. 将给定图像转换为二值图像。
3.提取轮廓
4 进行像素膨胀和腐蚀路径。
5.从膨胀图像中减去腐蚀图像得到最终输出即迷宫的解。
//Opencv C++ Program to solve mazes using mathematical morphology
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <cmath>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat src = imread("C:\\Users\\arjun\\Desktop\\opencv-maze-generator.png");
if (!src.data) { printf("Error loading src \n"); return -1; }
//Convert the given image into Binary Image
Mat bw;
cvtColor(src, bw, CV_BGR2GRAY);
threshold(bw, bw, 10, 255, CV_THRESH_BINARY_INV);
//Detect Contours in an Image
vector<std::vector<cv::Point> > contours;
findContours(bw, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);
if (contours.size() != 2)
{
// "Perfect maze" should have 2 walls
std::cout << "This is not a 'perfect maze' with just 2 walls!" << std::endl;
return -1;
}
Mat path = Mat::zeros(src.size(), CV_8UC1);
drawContours(path, contours, 0, CV_RGB(255, 255, 255), CV_FILLED);
//Dilate the Image
Mat kernel = Mat::ones(21, 21, CV_8UC1);
dilate(path, path, kernel);
//Erode the Image
Mat path_erode;
erode(path, path_erode, kernel);
//Subtract Eroded Image from the Dilate One
absdiff(path, path_erode, path);
//Draw the Path by Red Color
vector<Mat> channels;
split(src, channels);
channels &= ~path;
channels &= ~path;
channels |= path;
Mat dst;
merge(channels, dst);
imshow("solution", dst);
waitKey(0);
return 0;
}
1.输入:
2.将给定的图像转换为二进制后:
3.检测轮廓后:
4. 膨胀后:
5. 应用侵蚀后:
6.从腐蚀中减去膨胀图像后:
7. 用红色追踪路径(最终输出):