# 理解高斯滤波(Gaussian Filter)

1D的高斯函数

image.png

2D的高斯函数

image.png

### 生成高斯kernel

// Function to create Gaussian filter; sigma is standard deviation
Matrix getGaussian(int height, int width, double sigma)
{
Matrix kernel(height, Array(width));
// sum is for normalization
double sum=0.0;
int i,j;

// generating the kernel
for (i=0 ; i<height ; i++) {
for (j=0 ; j<width ; j++) {
// using gaussian function to generate gaussian filter
kernel[i][j] = exp(-(i*i+j*j)/(2*sigma*sigma))/(2*M_PI*sigma*sigma);
sum += kernel[i][j];
}
}

// normalising the Kernel
for (i=0 ; i<height ; i++) {
for (j=0 ; j<width ; j++) {
kernel[i][j] /= sum;
}
}

return kernel;
}

image.png

1. 最中间的值最大，值向周围递减
2. 越大，高斯函数的峰越宽，临接的数值差越大

### 对图片应用高斯Filter

Image applyFilter(Image &image, Matrix &filter){
assert(image.size()==3 && filter.size()!=0);

int height = image[0].size();
int width = image[0][0].size();
int filterHeight = filter.size();
int filterWidth = filter[0].size();
int newImageHeight = height-filterHeight+1;
int newImageWidth = width-filterWidth+1;
int d,i,j,h,w;

Image newImage(3, Matrix(newImageHeight, Array(newImageWidth)));

// iter the image pixel
for (d=0 ; d<3 ; d++) {
for (i=0 ; i<newImageHeight ; i++) {
for (j=0 ; j<newImageWidth ; j++) {
// using filter convolute the image matrix
for (h=i ; h<i+filterHeight ; h++) {
for (w=j ; w<j+filterWidth ; w++) {
newImage[d][i][j] += filter[h-i][w-j]*image[d][h][w];
}
}
}
}
}

return newImage;
}

image.png

#### More:

https://suelan.github.io/2019/07/12/Gaussian-Filter/