算法:检查所有像素,若该像素为物体上与背景接触的像素(四连通像素中既有背景像素又有物体像素),则为边界。
程序:
#define M 30
#define N 20
void edge(int image[M][N],int bianyuan[M][N])
{
int i,j
int inner=1,outer=1
for (i=0i<Mi++)/*清除数据*/
for(j=0j<Nj++)
bianyuan[i][j]=0
for(i=1i<M-1i++)
for(j=1j<N-1j++)
{
inner=1/*假设该像素或为物体,或为背景*/
outer=1
if(image[i-1][j]==0||image[i+1][j]==0||image[i][j-1]==0||image[i][j+1]==0)
inner=0
if(image[i-1][j]==1||image[i+1][j]==1||image[i][j-1]==1||image[i][j+1]==1)
outer=0
if(inner==0&&outer==0&&image[i][j]==1)/*像素周围既有物体又有背景*/ bianyuan[i][j]=1/*,且该像素为物体上的像素(image[i][j]==1),则定义为边界*/
}
}
void output(int array[M][N],int n)
{
int i,j
for(i=0i<ni++)
{
printf("\n")
for(j=0j<Nj++)
if(array[i][j]==1)
printf("1")
else
printf(" ")
}
}
void main()
{
int image[M][N]={{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,1,1,1,0,0,0,1,1,1,1,0,0,0,1,1,1,0,0},
{0,1,1,1,1,0,0,1,1,1,1,1,1,0,0,1,1,1,0},
{0,0,1,1,1,0,0,0,0,1,1,1,0,0,0,1,1,1,0},
{0,0,1,1,1,1,0,0,0,1,1,1,1,1,0,1,1,1,0},
{0,1,1,1,1,1,1,0,0,1,1,1,0,0,1,1,1,1,0},
{0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0},
{0,0,0,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,0},
{0,0,1,1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,0},
{0,0,0,0,1,1,1,1,0,0,0,0,0,1,1,1,1,1,0}}
int bianyuan[M][N]={0}
int i,j
printf("\nThe origianl image is:\n")
output(image,10)
edge(image,bianyuan)
printf("\nIts edge is:\n")
output(bianyuan,10)
}
写完了,又看一下,感觉edge函数太罗嗦了,不够简练,想了一下,改成了下面的样子,函数接口不变:
void edge(int image[M][N],int bianyuan[M][N])
{
int i,j
for (i=0i<Mi++)
for(j=0j<Nj++)
bianyuan[i][j]=0
for(i=1i<M-1i++)
for(j=1j<N-1j++)
{
int t=image[i-1][j]+image[i+1][j]+image[i][j-1]+image[i][j+1]
if(t>0&&t<4&&image[i][j]==1)/*周围4个像素值介于1~3之间,*/
bianyuan[i][j]=1/*且当前像素为物体,则其必为边界*/
}
}
希望这段代码对你有所帮助
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)