分享

均值滤波器 ( Mean Filter ) C++ 实现

 bobohoo 2010-12-14
 
均值滤波器就是在图像处理的时候, “把每个像素都用周围的8个像素来做均值操作 ”, 比如说这里有一个例子:
 sample
        非常明显, 这个3*3区域像素的颜色值分别是5,3,6,2,1,9,8,4,7那么中间的1这个像素的过滤后的值就是这些值的平均值, 也就是前面的计算方法: (5+3+6+2+1+9+8+4+7)/9=5一目了然。
        那么这个均值滤波器有什么用处呢?主要还是平滑图像的用处, 有的图像的锐度很高,用这样的均值算法,可以把锐度降低。使得图像看上去更加自然,下面就有几幅图我们可以看出一些端倪:
原图:
                                                                         
平滑处理之后:
 
       这里还是可以明显的感觉到不同的, 没有好坏之分,就是第二幅图片看上去更为平滑。  那这里均值平滑是否具有去除噪声的功能呢? 我们搞来了椒盐噪声(就是随机的白点,黑点)来试试手:
噪声图(5%):  
                
平滑处理之后:
 
       首先这里的噪声还是比较小的, 只有5%,从均值的效果来看的话, 我可以说几乎没有用,其实直观的想也可以判断, 因为这里的处理并没有剔除这些噪声点, 而只是微弱地降低了噪声,所以效果可以想见的。。
一段处理的代码:
view plaincopy to clipboardprint?
/** 
** method to remove noise from the corrupted image by mean value 
* @param corrupted input grayscale binary array with corrupted info 
* @param smooth output data for smooth result, the memory need to be allocated outside of the function 
* @param width width of the input grayscale image 
* @param height height of the input grayscale image 
*/ 
void meanFilter (unsigned char* corrupted, unsigned char* smooth, int width, int height)  
{  
      
    memcpy ( smooth, corrupted, width*height*sizeof(unsigned char) );  
      
    for (int j=1;j<height-1;j++)  
    {  
        for (int i=1;i<width-1;i++)  
        {  
            smooth [ j*width+i ] = (    corrupted [ (j-1)*width+(i-1) ] + corrupted [ (j-1)*width+i] + corrupted [ (j-1)*width+(i+1) ] +   
                                       corrupted [ j*width+(i-1) ]     + corrupted [ j*width+i]     + corrupted [ j*width+(i+1) ] +  
                                        corrupted [ (j+1)*width+(i-1) ] + corrupted [ (j+1)*width+i] + corrupted [ (j+1)*width+(i+1) ] ) / 9;  
        }  
    }  

/**
** method to remove noise from the corrupted image by mean value
* @param corrupted input grayscale binary array with corrupted info
* @param smooth output data for smooth result, the memory need to be allocated outside of the function
* @param width width of the input grayscale image
* @param height height of the input grayscale image
*/
void meanFilter (unsigned char* corrupted, unsigned char* smooth, int width, int height)
{
 
 memcpy ( smooth, corrupted, width*height*sizeof(unsigned char) );
 
 for (int j=1;j<height-1;j++)
 {
  for (int i=1;i<width-1;i++)
  {
   smooth [ j*width+i ] = ( corrupted [ (j-1)*width+(i-1) ] + corrupted [ (j-1)*width+i] + corrupted [ (j-1)*width+(i+1) ] +
          corrupted [ j*width+(i-1) ]  + corrupted [ j*width+i]  + corrupted [ j*width+(i+1) ] +
          corrupted [ (j+1)*width+(i-1) ] + corrupted [ (j+1)*width+i] + corrupted [ (j+1)*width+(i+1) ] ) / 9;
  }
 }
}
一般处理的时候通常还有边界上的一些处理, 这里就简单的从1...width-1来处理, 所以第一个和最后一个像素就简单的抛掉了, 如果只是简单的看看效果还是没有问题的!
 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多