Source:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Maze-Scanner (Directional)</title> <script type="text/javascript"> onload = function() { // setup a canvas and copy the img element to it var img=document.getElementById('img'), w=img.width, h=img.height, canvas=document.createElement('canvas'), ctx, pixels; canvas.width=w; canvas.height=h; ctx=canvas.getContext('2d'); ctx.drawImage(img,0,0); pixels=ctx.getImageData(0,0, w,h).data; // read bitmap (threshold on red channel) var maze=[]; for (var y=0; y<h; y++) { var m=maze[y]=[], ofs=w*y*4; for (var x=0; x<w; x++) { m[x]= (pixels[ofs+x*4]>128)? 1:0; } } // process directions (1: up, 2: left, 4: down, 8: right) // edges are all zeros by definition (0 < n < length-1) for (var r=1, rl=h-1; r<rl; r++) { for (var c=1, cl=w-1; c<cl; c++) { if (maze[r][c]) { var b=0; if (maze[r-1][c]) b = 1; if (maze[r][c-1]) b |= 2; if (maze[r+1][c]) b |= 4; if (maze[r][c+1]) b |= 8; maze[r][c] = b; } } } // prepare data var data=[]; for (var i=0, ln=1001; i<h; i++, ln++) { data.push(ln+' DATA '+maze[i].join(',')); } // display it document.getElementById('out').innerHTML=data.join('\n'); }; </script> </head> <body> <img id="img" src="maze.gif" /> <pre id="out"></pre> </body> </html>