I want to do flood fill for 2D images, but I keep getting the same results.
The program is quite simple. It reads a 2D image from a txt file containing 0s and 1s and applies the depth-first variant of the flood fill algorithm:
void floodFill (int u, int v, int label,Image &img, ImageLabels &imgL)
{
struct Point { int x; int y; int l;};
Point p = {0 , 0 , 1};
u = p.x;
v = p.y;
label = p.l;
vector <Point> stack;
stack.push_back(p);
while (!stack.empty())
{
Point p = stack.back();
stack.pop_back();
Point one = {(p.x+1), p.y, label};
Point two = {p.x,(p.y+1), label};
Point three = {p.x,(p.y-1), label};
Point four = {(p.x-1),p.y, label};
if ((p.x>=0) && (p.x<img.size()) && (p.y>=0) && (p.y<img[0].size()) && img[p.x][p.y]==1)
{
stack.push_back(one);
stack.push_back(two);
stack.push_back(three);
stack.push_back(four);
img[p.x][p.y] = label;
}
}
}
Here is the image labeling code:
void imageLabeling(Image &img, ImageLabels &imgL)
{
long int numLines=img.size();
long int numCols=img[0].size();
int u=0;
int v=0;
int label=1;
imgL.resize(numLines);
for (unsigned int i=0; i<numLines; i++)
imgL[i].resize(numCols);
for (unsigned int i=0; i <numLines; i++)
for (unsigned int j=0; j <numCols; j++)
imgL[i][j]=0;
for (int i=0; i<numLines; i++)
for (int j=0; j<numCols; j++)
{
if(img[i][j]=='1'&&imgL[i][j]==0)
{
imgL[i][j]=label;
floodFill (u,v,label,img,imgL);
label++;
}
}
}