我想为 2D 图像进行洪水填充,但我一直得到相同的结果。
该程序非常简单。它从包含 0 和 1 的 txt 文件中读取 2D 图像,并应用洪水填充算法的深度优先变体:
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;
}
}
}
这是图像标记代码:
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++;
}
}
}