高斯平滑 高斯模糊 高斯滤波器 ( Gaussian Smoothing, Gaussian Blur, Gaussian Filter ) C++ 实现



发展到如今这个平滑算法的时候, 我已经彻底不知道如何去命名这篇文章了, 只好罗列出一些关键字来方便搜索了.算法

在以前咱们提到过了均值滤波器, 就是说某像素的颜色, 由以其为中心的九宫格的像素平均值来决定. 在这个基础上又发展成了带权的平均滤波器, 这里的高斯平滑或者说滤波器就是这样一种带权的平均滤波器. 那么这些权重如何分布呢? 咱们先来看几个经典的模板例子:ide

尝试了使用这些滤波器对咱们原来的图进行操做, 获得了这样的一组结果:spa

原图:code

raw

3x3 高斯:orm

3x3

5x5 高斯:ip

5x5

 

单纯从效果来看, 两个模板都起到了平滑的做用, 只是程度有深浅的区分. 那么从理论上来讲为何能起到平滑的做用呢? 很显然, 像素的颜色不只由自身决定了, 同时有其周围的像素加权决定, 客观上减少了和周围像素的差别. 同时这些权重的设定知足了越近权重越大的规律. 从理论来说, 这些权重的分布知足了著名的所谓高斯分布:element

  这就是1维的计算公式rem

这就是2维的计算公式input

x, y表示的就是当前点到对应点的距离, 而那些具体的模板就是由这里公式中的一些特例计算而来. 须要说明的是不仅有这么一些特例, 从wikipedia能够方便地找到那些复杂的模板好比像:it

Sample Gaussian matrix

This is a sample matrix, produced by sampling the Gaussian filter kernel (with σ = 0.84089642) at the midpoints of each pixel and then normalising. Note that the center element (at [4, 4]) has the largest value, decreasing symmetrically as distance from the center increases.

0.00000067 0.00002292 0.00019117 0.00038771 0.00019117 0.00002292 0.00000067
0.00002292 0.00078633 0.00655965 0.01330373 0.00655965 0.00078633 0.00002292
0.00019117 0.00655965 0.05472157 0.11098164 0.05472157 0.00655965 0.00019117
0.00038771 0.01330373 0.11098164 0.22508352 0.11098164 0.01330373 0.00038771
0.00019117 0.00655965 0.05472157 0.11098164 0.05472157 0.00655965 0.00019117
0.00002292 0.00078633 0.00655965 0.01330373 0.00655965 0.00078633 0.00002292
0.00000067 0.00002292 0.00019117 0.00038771 0.00019117 0.00002292 0.00000067

是否是看到就头大了:) 不过不要紧, 对于通常的应用来讲, 前面的例子已经能够完成任务了.  代码的话咱们仍是给一份5x5的example:

/**
** method to remove noise from the corrupted image by gaussian filter 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 gaussianFilter2 (unsigned char* corrupted, unsigned char* smooth, int width, int height)
{
	int templates[25] = { 1, 4, 7, 4, 1, 
						  4, 16, 26, 16, 4, 
						  7, 26, 41, 26, 7,
						  4, 16, 26, 16, 4, 
						  1, 4, 7, 4, 1 };		
	
	memcpy ( smooth, corrupted, width*height*sizeof(unsigned char) );
	for (int j=2;j<height-2;j++)
	{
		for (int i=2;i<width-2;i++)
		{
			int sum = 0;
			int index = 0;
			for ( int m=j-2; m<j+3; m++)
			{
				for (int n=i-2; n<i+3; n++)
				{
					sum += corrupted [ m*width + n] * templates[index++] ;
				}
			}
			sum /= 273;
			if (sum > 255)
				sum = 255;
			smooth [ j*width+i ] = sum;
		}
	}
}
附带说一些,很明显,和均值滤波器相似, 这个滤波器没有消除校验噪声的做用.
相关文章
相关标签/搜索