This article mainly introduces how to use Python code to solve the image maze. This article selects several answers to StackOverflow-related popularity questions. For more information, see: the original article is a question about how to use a program to read and solve the Maze Image on StackOverflow. Several participants enthusiastically discussed and gave their own code, it involves processing images using Python and the breadth-first (BFS) algorithm.
Problem by Whymarrh:
Given a JPEG image like above, how can we better convert this image into a suitable data structure and solve this maze?
My first instinct is to read this image one by one in pixels and store it in a list or array containing Boolean elements. True indicates a white pixel, false indicates a non-white pixel (or color can be processed as a binary image ). However, there is a problem with this approach, that is, given images are often not perfectly "Pixel ". If an unexpected white pixel appears on the wall of the maze due to image conversion, an unexpected path may be created.
After thinking, I came up with another method: first, convert the image into an SVG file that can be scaled. the file consists of a list of vector lines on the canvas, vector lines are read in the order of the list. The Read result is still a Boolean value. True indicates the wall, and False indicates the area that can pass. However, this method may cause cracks if the image cannot be accurately converted, especially if the wall cannot be completely connected.
Another problem with converting an image to SVG is that the line is not a perfect line. Because the SVG line is a cubic besell curve, and the List of Boolean values indexed by integer increases the difficulty of curve conversion, all points on the labyrinth line must be calculated on the curve, however, the index value in the list may not be perfect.
Assuming that the above methods can indeed be implemented (although most likely none), they are not competent when a large image is given. Is there a better way to balance efficiency and complexity?
This will discuss how to solve the maze. If I use either of the above two methods, I will eventually get a matrix. According to this question and answer (http://stackoverflow.com/questions/3097556/programming-theory-solve-a-maze/3097677#3097677), A better expression of the maze should be the structure of the tree, and the use of A * search algorithm to solve the maze. How can we create a maze tree from a maze image? Is there a better method?
The question to sum up is: how to convert the maze picture? What kind of data structure is converted? What kind of data structure can be used to help or impede the maze?
Answer by Mikhail:
Here is my solution:
1. convert the image to a grayscale image (not a binary value) and adjust the weights of different colors to make the final grayscale look more unified, you can simply adjust Photoshop images-> Adjust-> control bar in the black/white menu.
2. convert the grayscale image obtained in the previous step to a binary image. you can set an appropriate threshold value in the PS Image> Adjust> threshold menu.
3. make sure that the threshold value is set correctly. Use the magic wand tool (parameter settings: tolerance 0, sampling point, continuous, and ing) to select a blank area and check that the edge of the selected area is not a false edge generated by incorrect threshold settings. In fact, the gap between start and end in this maze should be from the blank area of China Unicom.
4. artificially add borders outside the maze to ensure that the maze Rover ^_^ will not run from start to the end of the maze. :)
5. select the language to implement the breadth-first search algorithm (BFS) and run the program at start. The following code is implemented using Matlab. As Thomas mentioned, there is no need to worry about the representation of an image. you can run it directly on a binary image.
The following is the BFS code implemented using MATLAB:
function path = solve_maze(img_file) %% Init data img = imread(img_file); img = rgb2gray(img); maze = img > 0; start = [985 398]; finish = [26 399]; %% Init BFS n = numel(maze); Q = zeros(n, 2); M = zeros([size(maze) 2]); front = 0; back = 1; function push(p, d) q = p + d; if maze(q(1), q(2)) && M(q(1), q(2), 1) == 0 front = front + 1; Q(front, = q; M(q(1), q(2), = reshape(p, [1 1 2]); end end push(start, [0 0]); d = [0 1; 0 -1; 1 0; -1 0]; %% Run BFS while back <= front p = Q(back, ; back = back + 1; for i = 1:4 push(p, d(i, ); end end %% Extracting path path = finish; while true q = path(end, ; p = reshape(M(q(1), q(2), , 1, 2); path(end + 1, = p; if isequal(p, start) break; end endend
This is a simple implementation. it should be easy to rewrite to Python or other languages. The following is the running result of the program:
Questioner update:
I used Python to implement the Mikhail method, and used the numpy library. thanks to Thomas for his suggestion. I think this algorithm is correct, but the effect is not as expected. the following code uses the PyPNG library to process images.
Sorry, the code provided by the questioner does not run through the program, and it seems that the code indentation is a bit problematic. the code of the other participants below can be executed and the effect is very good.
import png, numpy, Queue, operator, itertools def is_white(coord, image): """ Returns whether (x, y) is approx. a white pixel.""" a = True for i in xrange(3): if not a: break a = image[coord[1]][coord[0] * 3 + i] > 240 return a def bfs(s, e, i, visited): """ Perform a breadth-first search. """ frontier = Queue.Queue() while s != e: for d in [(-1, 0), (0, -1), (1, 0), (0, 1)]: np = tuple(map(operator.add, s, d)) if is_white(np, i) and np not in visited: frontier.put(np) visited.append(s) s = frontier.get() return visited def main(): r = png.Reader(filename = "thescope-134.png") rows, cols, pixels, meta = r.asDirect() assert meta['planes'] == 3 # ensure the file is RGB image2d = numpy.vstack(itertools.imap(numpy.uint8, pixels)) start, end = (402, 985), (398, 27) print bfs(start, end, image2d, [])
Answer by Joseph Kern:
#!/usr/bin/env python import sys from Queue import Queuefrom PIL import Image start = (400,984)end = (398,25) def iswhite(value): if value == (255,255,255): return True def getadjacent(n): x,y = n return [(x-1,y),(x,y-1),(x+1,y),(x,y+1)] def BFS(start, end, pixels): queue = Queue() queue.put([start]) # Wrapping the start tuple in a list while not queue.empty(): path = queue.get() pixel = path[-1] if pixel == end: return path for adjacent in getadjacent(pixel): x,y = adjacent if iswhite(pixels[x,y]): pixels[x,y] = (127,127,127) # see note new_path = list(path) new_path.append(adjacent) queue.put(new_path) print "Queue has been exhausted. No answer was found." if __name__ == '__main__': # invoke: python mazesolver.py [.jpg|.png|etc.] base_img = Image.open(sys.argv[1]) base_pixels = base_img.load() path = BFS(start, end, base_pixels) path_img = Image.open(sys.argv[1]) path_pixels = path_img.load() for position in path: x,y = position path_pixels[x,y] = (255,0,0) # red path_img.save(sys.argv[2])
Dynamic execution results:
Answer: by Jim
Tree Search is too complicated, and the maze itself is separate from the solution path. Because of this, you can use the connected area search algorithm to Mark connected areas in the maze. this will search these pixels twice iteratively. If you want a better solution, you can use binary operations for structural units to fill in dead paths in each connected area.
The following shows the relevant MATLAB code and running results:
% read in and invert the imageim = 255 - imread('maze.jpg'); % sharpen it to address small fuzzy channels% threshold to binary 15%% run connected componentsresult = bwlabel(im2bw(imfilter(im,fspecial('unsharp')),0.15)); % purge small components (e.g. letters)for i = 1:max(reshape(result,1,1002*800)) [count,~] = size(find(result==i)); if count < 500 result(result==i) = 0; endend % close dead-end channelsclosed = zeros(1002,800);for i = 1:max(reshape(result,1,1002*800)) k = zeros(1002,800); k(result==i) = 1; k = imclose(k,strel('square',8)); closed(k==1) = i;end % do outputout = 255 - im;for x = 1:1002 for y = 1:800 if closed(x,y) == 0 out(x,y,:) = 0; end endendimshow(out);
Answer: by Stefano
Stefano provides the code maze-solver-python (GitHub) for generating GIF and AVI files during the search process)