代码原创:梁毅军(西安交大图像所)liang.yijun@live.cn
void Label(byte [,] f, int x,int y,byte L)//8邻域递归标记
{
f[x,y] = L;
if (f[x+1,y]==255) Label(f,x+1,y,L);
if (f[x-1,y]==255) Label(f,x-1,y,L);
if (f[x,y+1]==255) Label(f,x,y+1,L);
if (f[x,y-1]==255) Label(f,x,y-1,L);
if (f[x+1,y+1]==255) Label(f,x+1,y+1,L);
if (f[x-1,y+1]==255) Label(f,x-1,y+1,L);
if (f[x+1,y-1]==255) Label(f,x+1,y-1,L);
if (f[x-1,y-1]==255) Label(f,x-1,y-1,L);
}
ARGB [,] ToColor(byte [,]f)
{
int w = f.GetLength(0);
int h = f.GetLength(1);
ARGB [,] g = new ARGB[w,h];
ARGB [] tab = new ARGB[256];
tab[0].R = 0;
tab[0].G = 0;
tab[0].B = 0;
tab[1].R = 255;
tab[1].G = 0;
tab[1].B = 0;
tab[2].R = 0;
tab[2].G = 255;
tab[2].B = 0;
tab[3].R = 0;
tab[3].G = 0;
tab[3].B = 255;
tab[4].R = 255;
tab[4].G = 255;
tab[4].B = 255;
tab[5].R = 255;
tab[5].G = 0;
tab[5].B = 255;
tab[6].R = 255;
tab[6].G = 255;
tab[6].B = 0;
tab[7].R = 128;
tab[7].G = 0;
tab[7].B = 0;
tab[8].R = 0;
tab[8].G = 128;
tab[8].B = 0;
tab[9].R = 0;
tab[9].G = 0;
tab[9].B = 128;
for (int y=0;y<h;y++)
for (int x=0;x<w;x++)
g[x,y] = tab[f[x,y]];
return g;
}
void main()
{
byte [,]f = LoadImg();
if (f==null) return;
ShowImg("",f);
int w = f.GetLength(0);
int h = f.GetLength(1);
byte L = 1;
for (int y=0;y<h;y++)
for (int x=0;x<w;x++)
{
if (f[x,y]==255)
{
Label(f,x,y,L);
L+=1;
}
}
ShowImg("Label",ToColor(f));
}