我想做一个关于形态学图像处理的专题,写一写我的想法,并且公开实现这些算法的代码。因为形态学图像处理的最基础方法就是腐蚀和膨胀,因此就从这两个方法开始。
腐蚀:
把结构元素S平移x后得到Sx,若Sx包含于X,我们记下这个x点,所有满足上述条件的x点组成的集合称做X被S腐蚀(Erosion)的结果。用公式表示为:
腐蚀的方法是,拿S的原点和X上的点一个一个地对比,如果S上的所有点都在X的范围内,则S的原点对应的点保留,否则将该点去掉。以下是详细的代码,并且附上测试图片:
#include
#include
#include
#include
#include
unsigned char **get_matrix_space(int m,int n)
{
int i;
unsigned char **a;
a=(unsigned char **)calloc(m,sizeof(unsigned char *));
for(i=0;ireturn a;
}
main(){
FILE *fs,*fd;
unsigned char c1,c2,**ps,**pd,**get_matrix_space(int,int);
int width,height,L,i,j,l,m,match;
if((fs= fopen("sourcea.pgm","rb")) ==NULL){
printf("can't open %s/n","source.pgm");
exit(1);
}
if((fd = fopen("destination.pgm","wb")) ==NULL){
printf("can't open %s/n","destination.pgm");
exit(1);
}
fscanf(fs,"%c%c/n%d%d/n%d/n",&c1,&c2,&width,&height,&L);
ps=get_matrix_space(height,width);
pd=get_matrix_space(height,width);
for(i=0;i for(j=0;j fread(&ps[i][j],sizeof(unsigned char),1,fs);
pd[i][j] = 0;
}
}
///////////////////////
match = 1;
for(i=0;i for(j=0;j for(m=i;m for(l=j;l if(ps[m][l]!=255){
match = 0;
}
}
}
if(match != 0){
pd[i][j]=255;
}
match = 1;
}
}
//////////////////////
fprintf(fd,"%c%c/n%d %d/n%d/n",'P','5',width,height,L);
for(i=0;i for(j=0;j fwrite(&pd[i][j],sizeof(unsigned char),1,fd);
}
}
}
膨胀:
把结构元素S平移x后得到Sx,若Sx与X相交不为空,我们记下这个x点,所有满足上述条件的x点组成的集合称做X被S膨胀((dilation))的结果。用公式表示为:
膨胀的方法是,拿S的原点和X上的点一个一个地对比,如果S上有一个点落在X的范围内,则S的原点对应的点就为图像。以下是详细的代码,并且附上测试图片:
#include
#include
#include
#include
#include
unsigned char **get_matrix_space(int m,int n)
{
int i;
unsigned char **a;
a=(unsigned char **)calloc(m,sizeof(unsigned char *));
for(i=0;ireturn a;
}
main(){
FILE *fs,*fd;
unsigned char c1,c2,**ps,**pd,**v,**get_matrix_space(int,int);
int width,height,L,i,j,l,m,windowSize,match;
if((fs= fopen("source.pgm","rb")) ==NULL){
printf("can't open %s/n","source.pgm");
exit(1);
}
if((fd = fopen("destination.pgm","wb")) ==NULL){
printf("can't open %s/n","destination.pgm");
exit(1);
}
fscanf(fs,"%c%c/n%d%d/n%d/n",&c1,&c2,&width,&height,&L);
ps=get_matrix_space(height,width);
pd=get_matrix_space(height,width);
for(i=0;i for(j=0;j fread(&ps[i][j],sizeof(unsigned char),1,fs);
}
}
match = 0;
//////////////////////
//用2x2方块作为膨胀的结构元素。
for(i=0;i for(j=0;j for(l=i;l for(m=j;m if(ps[l][m]==255){
match = 1;
}
}
}
if(match == 1){
pd[i][j] = 255;
match = 0;
}
}
}
//////////////////////
fprintf(fd,"%c%c/n%d %d/n%d/n",'P','5',width,height,L);
for(i=0;i for(j=0;j fwrite(&pd[i][j],sizeof(unsigned char),1,fd);
}
}
}
原文地址:http://blog.csdn.net/vincentzhao2009/archive/2009/10/24/4723469.aspx