Flood fill algorithm in c++

Flood Fill Algorithm-

Flood fill algorithm is used to color the polygon.This comes under seed fill algorithm.To color a polygon we use either 4-connected method or 8-connected method.

 

4-connected method-

In this method, we choose a seed pixel and color it with new color after this we color the neighbourhood pixels and so on.


8-connected method-

In this method, we choose a seed pixel and color it with new color after this we color all eight neighbourhood pixels and so on.

we can see this by this picture-

Source-https://www.cs.auckland.ac.nz/courses/compsci773s1c/lectures/ImageProcessing-html/neighbourhoods.gif

Here is the c++ program for flood fill algorithm-



#include<bits/stdc++.h>
#include<graphics.h>
using namespace std;
//function to implement floodfill algorithm
void floodfill(int x,int y,int old,int newcol)
{
 //getpixel() gives the color of pixel (x,y)
 int curr=getpixel(x,y);
 //if the color of current pixel is same as the old color then color this to new color
 if(curr==old)
 {
  delay(10);
  //color the current pixel with new color
  putpixel(x,y,newcol);
  //repeat the process for 8 neighbouring pixels
  floodfill(x-1,y,old,newcol);
  floodfill(x+1,y,old,newcol);
  floodfill(x,y-1,old,newcol);
  floodfill(x,y+1,old,newcol);
  floodfill(x+1,y+1,old,newcol);
  floodfill(x-1,y+1,old,newcol);
  floodfill(x-1,y-1,old,newcol);
  floodfill(x+1,y-1,old,newcol);
 }
}
int main ()
{
 int gd,gm;
 detectgraph(&gd,&gm);
 initgraph(&gd,&gm," ");
 //function to draw rectangle
 rectangle(100,100,200,200);
 //call the function with the points that exist inside the polygon we are going to color
 floodfill(110,110,0,2);
 getch();
return 0;
}
OUTPUT-
To execute this program-
  • Save the above-given code with .cpp extension i.e.(file.cpp).
  •  open the terminal and write the command         
    g++ file.cpp -lgraph
  • After this execute ./a.out file and you will see the output shown below-
  

Comments

  1. I’ve been surfing online more than three hours today, yet I never found any interesting article like yours. It’s pretty worth enough for me. In my opinion, if all webmasters and bloggers made good content as you did, the web will be a lot more useful than ever before. flood defences

    ReplyDelete

Post a Comment