Skip to content

Instantly share code, notes, and snippets.

@tokoro10g
Last active May 15, 2019 08:12
Show Gist options
  • Save tokoro10g/57d88b5aafd8ab0e62bf56cf74e99373 to your computer and use it in GitHub Desktop.
Save tokoro10g/57d88b5aafd8ab0e62bf56cf74e99373 to your computer and use it in GitHub Desktop.
NTFウェブサイトの迷路シートの画像から迷路データを抽出するMATLABスクリプト
clear
close all
filename = 'MM2017HX_pre.png';
url = ['http://www.ntf.or.jp/mouse/micromouse2017/' filename];
if ~exist(filename, 'file')
websave(filename,url);
end
IM = imread(filename);
IM = imresize(IM, [600 nan]);
% adjust this constant if it fails
BW = rgb2gray(IM)>200;
BW = imdilate(BW, ones(3)); BW = imerode(BW, ones(3));
%imshow(BW);pause
%% Locate the bounding box of the maze
BW2 = imfill(~BW,'holes');
BW2 = imerode(BW2, ones(7)); BW2 = imdilate(BW2, ones(7));
%imshow(BW2);pause
s = regionprops(BW2, 'BoundingBox','FilledArea');
[~,idx] = max([s.FilledArea]);
bb = s(idx).BoundingBox;
%% Crop image
M = imcrop(imerode(BW,eye(3)),bb);
imshow(M)
hold on;
%% Determine the number of cells
accum_y = all(imdilate(M,ones(1,32)),2);
ny = nnz(diff(accum_y)==-1);
accum_x = all(imdilate(M,ones(32,1)),1);
nx = nnz(diff(accum_x)==-1);
n = max(ny,nx);
fprintf('assuming the size of maze is %d x %d\n', n, n);
%% Detect walls for each cell
[h, w] = size(M);
cur_y = round(linspace(3,h-2,n+1));
cur_x = round(linspace(3,w-2,n+1));
[X,Y] = meshgrid(cur_x,cur_y);
plot(X,Y,'*');
mazedat = zeros(n);
for k=1:n
for l=1:n
y = round([cur_y(k), (cur_y(k+1)+cur_y(k))/2, cur_y(k+1), (cur_y(k+1)+cur_y(k))/2]);
x = round([(cur_x(l+1)+cur_x(l))/2, cur_x(l+1), (cur_x(l+1)+cur_x(l))/2, cur_x(l)]);
data = diag(~M(y,x));
mazedat(k,l) = [1 2 4 8]*data; % N: 1, E: 2, S: 4, W: 8
end
end
%% Serialize data
for k=1:n
fprintf('%x ',mazedat(k,:)); fprintf('\n');
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment