中值滤波和均值滤波C++代码

均值滤波和中值滤波代码  

2008-11-24 16:07:36|  分类: 编程|举报|字号 订阅

 
 

//------------------均值滤波器

bool FilterAV(unsigned char *image,int height,int width)

{

 int i,j;

 unsigned char *p=(unsigned char*)malloc(height*width);

 for(i=1;i<height-1;i++)

 {

  for(j=1;j<width-1;j++)

  {

   p[i*width+j]=(unsigned char)(((int)image[(i-1)*width+j-1]

      +(int)image[(i-1)*width+j]

      +(int)image[(i-1)*width+j+1]

      +(int)image[i*width+j-1]

      +(int)image[i*width+j]

      +(int)image[i*width+j+1]

      +(int)image[(i+1)*width+j-1]

      +(int)image[(i+1)*width+j]

      +(int)image[(i+1)*width+j+1])/9);

  }

 }

 for(i=1;i<height-1;i++)

 {

  for(j=1;j<width-1;j++)

  {

   image[i*width+j]=p[i*width+j];

  }

 }

 free(p);

 return true;

}

//----------------------------中值滤波器

bool FilterMid(unsigned char *image,int height,int width)

{

 int i,j,k,l;

 int pos;

 unsigned char temp;

 unsigned char psr[9];

 unsigned char *p=(unsigned char*)malloc(height*width);

  for(i=1;i<height-1;i++)

     {

  for(j=1;j<width-1;j++)

  {     //---3*3窗口矩阵

              psr[0]=image[(i-1)*width+j-1];

              psr[1]=image[(i-1)*width+j];

              psr[2]=image[(i-1)*width+j+1];

              psr[3]=image[i*width+j-1];

              psr[4]=image[i*width+j];

              psr[5]=image[i*width+j+1];

              psr[6]=image[(i+1)*width+j-1];

              psr[7]=image[(i+1)*width+j];

              psr[8]=image[(i+1)*width+j+1];

              //--------选择排序

              for(k=0;k<9;k++)

              {

                    pos=k;

                    for(l=k;l<9;l++)

                    {

                        if(psr[l]<psr[pos])

                                pos=l;

                    }

                    temp=psr[k];

                    psr[k]=psr[pos];

                    psr[pos]=temp;

              } 

              //------取中值

              p[i*width+j]=psr[4];

  }

 }

  for(i=1;i<height-1;i++)

     {

  for(j=1;j<width-1;j++)

  {

   image[i*width+j]=p[i*width+j];

  }

  }

  free(p);

  return true;

}

原文地址:https://www.cnblogs.com/ITcode/p/3968568.html