# Using marching squares algorithm to trace the contour of an image

Did you ever wonder how graphic softwares can trace the contour of an image? No? Actually, I never cared about it, but since I needed to do it for a more complex project, I discovered the magic world of marching squares algorithm to trace the contour of an image.

The idea of the process is simple:

1) Find a pixel placed on the edge of the image (this has nothing to do with marching squares, which assumes you already found such pixel). This will be the current pixel to analyze

2) Consider a 2×2 pixel square which includes the current pixel which generally is located in the top left or the right bottom of the square.

3) At this time you have 4 pixels, and each one of them can be transparent or opaque. So we will have 16 possible 2×2 squares, although the cases with all transparent pixels or all opaque pixels will never occur as we are moving around the edge of the image.

4) According to the number and position of opaque pixels in the 2×2 square, we can guess the direction of the contour, move the current pixel in such direction, and continue from step 2 until you reach again the pixel found at step 1

Now, how can we find the starting pixel needed at step 1? This is just a matter of brute force, we need to scan the image pixel by pixel until we find an opaque pixel.

Let’s see this fully commented code:

```package {
import flash.display.Sprite;
import flash.display.BitmapData;
import flash.display.Bitmap;
import flash.geom.Matrix;
import flash.geom.Point;
public class Main extends Sprite {
private var bitmapData:BitmapData=new BitmapData(640,480,true,0x00000000);
// tolerance is the amount of alpha for a pixel to be considered solid
private var tolerance:Number=0x01;
public function Main() {
// adding a png image with transparency
bitmapData.draw(new Logo(278,429),new Matrix(1,0,0,1,100,40));
var bitmap:Bitmap=new Bitmap(bitmapData);
// at the end of this function, marchingVector will contain the points tracing the contour
var marchingVector:Vector.<Point>=marchingSquares(bitmapData);
}

public function marchingSquares(bitmapData:BitmapData):Vector.<Point> {
var contourVector:Vector.<Point> = new Vector.<Point>();
// this is the canvas we'll use to draw the contour
var canvas:Sprite=new Sprite();
canvas.graphics.lineStyle(2,0x00ff00);
// getting the starting pixel
var startPoint:Point=getStartingPixel(bitmapData);
// if we found a starting pixel we can begin
if (startPoint!=null) {
// moving the graphic pen to the starting pixel
canvas.graphics.moveTo(startPoint.x,startPoint.y);
// pX and pY are the coordinates of the starting point
var pX:Number=startPoint.x;
var pY:Number=startPoint.y;
// stepX and stepY can be -1, 0 or 1 and represent the step in pixels to reach
// next contour point
var stepX:Number;
var stepY:Number;
// we also need to save the previous step, that's why we use prevX and prevY
var prevX:Number;
var prevY:Number;
// closedLoop will be true once we traced the full contour
var closedLoop:Boolean=false;
while (!closedLoop) {
// the core of the script is getting the 2x2 square value of each pixel
var squareValue:Number=getSquareValue(pX,pY);
switch (squareValue) {
/* going UP with these cases:

+---+---+   +---+---+   +---+---+
| 1 |   |   | 1 |   |   | 1 |   |
+---+---+   +---+---+   +---+---+
|   |   |   | 4 |   |   | 4 | 8 |
+---+---+  	+---+---+  	+---+---+

*/
case 1 :
case 5 :
case 13 :
stepX=0;
stepY=-1;
break;
/* going DOWN with these cases:

+---+---+   +---+---+   +---+---+
|   |   |   |   | 2 |   | 1 | 2 |
+---+---+   +---+---+   +---+---+
|   | 8 |   |   | 8 |   |   | 8 |
+---+---+  	+---+---+  	+---+---+

*/
case 8 :
case 10 :
case 11 :
stepX=0;
stepY=1;
break;
/* going LEFT with these cases:

+---+---+   +---+---+   +---+---+
|   |   |   |   |   |   |   | 2 |
+---+---+   +---+---+   +---+---+
| 4 |   |   | 4 | 8 |   | 4 | 8 |
+---+---+  	+---+---+  	+---+---+

*/
case 4 :
case 12 :
case 14 :
stepX=-1;
stepY=0;
break;
/* going RIGHT with these cases:

+---+---+   +---+---+   +---+---+
|   | 2 |   | 1 | 2 |   | 1 | 2 |
+---+---+   +---+---+   +---+---+
|   |   |   |   |   |   | 4 |   |
+---+---+  	+---+---+  	+---+---+

*/
case 2 :
case 3 :
case 7 :
stepX=1;
stepY=0;
break;
case 6 :
/* special saddle point case 1:

+---+---+
|   | 2 |
+---+---+
| 4 |   |
+---+---+

going LEFT if coming from UP
else going RIGHT

*/
if (prevX==0&&prevY==-1) {
stepX=-1;
stepY=0;
}
else {
stepX=1;
stepY=0;
}
break;
case 9 :
/* special saddle point case 2:

+---+---+
| 1 |   |
+---+---+
|   | 8 |
+---+---+

going UP if coming from RIGHT
else going DOWN

*/
if (prevX==1&&prevY==0) {
stepX=0;
stepY=-1;
}
else {
stepX=0;
stepY=1;
}
break;
}
// moving onto next point
pX+=stepX;
pY+=stepY;
// saving contour point
contourVector.push(new Point(pX, pY));
prevX=stepX;
prevY=stepY;
//  drawing the line
canvas.graphics.lineTo(pX,pY);
// if we returned to the first point visited, the loop has finished
if (pX==startPoint.x&&pY==startPoint.y) {
closedLoop=true;
}
}
}
return contourVector;
}

private function getStartingPixel(bitmapData:BitmapData):Point {
// finding the starting pixel is a matter of brute force, we need to scan
// the image pixel by pixel until we find a non-transparent pixel
var zeroPoint:Point=new Point(0,0);
var offsetPoint:Point=new Point(0,0);
for (var i:Number=0; i<bitmapData.height; i++) {
for (var j:Number=0; j<bitmapData.width; j++) {
offsetPoint.x=j;
offsetPoint.y=i;
if (bitmapData.hitTest(zeroPoint,tolerance,offsetPoint)) {
return offsetPoint;
}
}
}
return null;
}

private function getSquareValue(pX:Number,pY:Number):Number {
/*

checking the 2x2 pixel grid, assigning these values to each pixel, if not transparent

+---+---+
| 1 | 2 |
+---+---+
| 4 | 8 | <- current pixel (pX,pY)
+---+---+

*/
var squareValue:Number=0;
// checking upper left pixel
if (getAlphaValue(bitmapData.getPixel32(pX-1,pY-1))>=tolerance) {
squareValue+=1;
}
// checking upper pixel
if (getAlphaValue(bitmapData.getPixel32(pX,pY-1))>tolerance) {
squareValue+=2;
}
// checking left pixel
if (getAlphaValue(bitmapData.getPixel32(pX-1,pY))>tolerance) {
squareValue+=4;
}
// checking the pixel itself
if (getAlphaValue(bitmapData.getPixel32(pX,pY))>tolerance) {
squareValue+=8;
}
return squareValue;
}

private function getAlphaValue(n:Number):Number {
// given an ARGB color value, returns the alpha 0 -> 255
return n >> 24 & 0xFF;
}
}
}```

And this is the result:

The green line is the contour traced by the algorithm. Next time, I am showing you how to use this algorithm with Box2D to create interesting things.

214 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 10000000
// 2 Cars
// 2048
// Avoider
// Ballz
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Breakout
// Bricks
// Columns
// CubesOut
// Dots
// DROP'd
// Dudeski
// Eskiv
// Filler
// Fling
// Globe
// HookPod
// Hundreds
// InkTd
// Iromeku
// Lumines
// Magick
// MagOrMin
// Maze
// Memdot
// Nano War
// Nodes
// o:anquan
// Ononmin
// Pacco
// Phyballs
// Platform
// Poker
// Pool
// Poux
// Pudi
// qomp
// Racing
// Renju
// SameGame
// Security
// Sling
// Slingy
// Sokoban
// Splitter
// Sproing
// Stack
// Stringy
// Sudoku
// Tetris
// Threes
// Toony
// Turn
// TwinSpin
// vvvvvv
// Wordle
// Worms
// Yanga
// Zhed
// zNumbers