Showing posts with label Algorithm. Show all posts
Showing posts with label Algorithm. Show all posts

Thursday, June 28, 2012

Code Snippet - Summed Area Table

SUMMED AREA TABLE
Using the method described here, I have written the following code to calculate a summed area table. A sample image table of 5x5 dimensions has been assumed for simplicity. The code snippet and its results are given below.

CODE
// assumed height and width of the input table
#define height 6
#define width 6

// input matrix - 5x5
long matrix[ height - 1][width -1] = {{5,2,3,4,1},{1,5,4,2,3},{2,2,1,3,4},{3,5,6,4,5},{4,1,3,2,6}};
// output matrix - 6x6
long sat[height][width];

void sat_matrix(){
 // formula variables
      int a=0, b=0, c=0, m=0;
      // matrix traversal loop for calculating the SAT
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
                     // following code picks up array elements within bounds and picks "zero"
                     // for values outside bounds.
a = (i-1>=0)?sat[i-1][j]:0;
b = (j-1>=0)?sat[i][j-1]:0;
c = ((i-1>=0)&&(j-1>=0))?sat[i-1][j-1]:0;
m = ((i-1>=0)&&(j-1>=0))?matrix[i-1][j-1]:0;
                      // ACTUAL FORMULA FOR SUMMED AREA TABLE
sat[i][j] = m + a + b - c;
}
}
}

PROCEDURE:
Use the function as it is and write supporting code. The code written was compiled using g++ compiler in cygwin environment

OUTPUT:


Monday, July 19, 2010

Flood-fill Algorithm - Working Demo

This is a working code to demonstrate the Flood-fill or Brushfire or Wavefront Algorithm in C++. The main crux of this code however, is the Flood method.

Flood-Fill algorithm calculates relative cost of moving to a Block of an array and fills all consecutive blocks with numbers corresponding to cost. The Source is tagged as 0 as there is no additional cost to move there.
Here is the code:


#include <iostream.h>
#include <conio.h>


#define GridMaxX 5
#define GridMaxY 5


int Grid[GridMaxX][GridMaxY],r,c;
// r and c are coordinates of filling source.


void DisplayGrid()//Display the grid
{
for(int i=0;i<=GridMaxX-1;i++)
{
for(int j=0;j<=GridMaxY-1;j++)
cout<<"\t";
cout<<"\n\n";
}
}


void Flood()//Flood the grid
{
for(int i=0;i<=GridMaxX-1;i++)
for(int j=0;j<=GridMaxY-1;j++)
Grid[i][j] = (((i-r)>=0)?(i-r):(r-i))+(((j-c)>=0)?(j-c):(c-j));

//x-distance(positive) added to y-distance(positive)
DisplayGrid();
}


void main()
{
clrscr();

//Initialize Grid with junk values of 99.
for(int i=0;i<=GridMaxX-1;i++)
for(int j=0;j<=GridMaxY-1;j++)
Grid[i][j]=99;
DisplayGrid();

//Input the source of Flooding
cout<<"ENTER SOURCE COORDINATES:\nx = ";
cin>>r;
cout<<"\ny = ";
cin>>c;
Flood();
getch();
}