該腳本僅適用于完美迷宮,即只有一個(gè)唯一解、沒(méi)有分段、沒(méi)有圓形區(qū)域和沒(méi)有開(kāi)放區(qū)域的迷宮。
這些完美的迷宮可以使用在線迷宮生成工具生成。
讓我們以這個(gè)簡(jiǎn)單的迷宮作為測(cè)試圖像:
解決完美迷宮的步驟是:
1. 加載源圖像。
2. 將給定圖像轉(zhuǎn)換為二值圖像。
3.提取輪廓
4 進(jìn)行像素膨脹和腐蝕路徑。
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.將給定的圖像轉(zhuǎn)換為二進(jìn)制后:
3.檢測(cè)輪廓后:
4. 膨脹后:
5. 應(yīng)用侵蝕后:
6.從腐蝕中減去膨脹圖像后:
7. 用紅色追蹤路徑(最終輸出):