求用C语言用Sobels算子方法编写图像边缘提取的程序算法!(急)
发布网友
发布时间:2022-04-23 04:47
我来回答
共1个回答
热心网友
时间:2023-10-15 06:24
定义:每个像素的取值均为0或1,称这样的图像为二值图像。
算法:检查所有像素,若该像素为物体上与背景接触的像素(四连通像素中既有背景像素又有物体像素),则为边界。
程序:
#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=0;i<M;i++)/*清除数据*/
for(j=0;j<N;j++)
bianyuan[i][j]=0;
for(i=1;i<M-1;i++)
for(j=1;j<N-1;j++)
{
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=0;i<n;i++)
{
printf("\n");
for(j=0;j<N;j++)
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=0;i<M;i++)
for(j=0;j<N;j++)
bianyuan[i][j]=0;
for(i=1;i<M-1;i++)
for(j=1;j<N-1;j++)
{
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; /*且当前像素为物体,则其必为边界*/
}
}
希望这段代码对你有所帮助