Bộ lọc Gaussian dùng rộng rãi trong xử lý ảnh để giảm nhiễu. Kernel 2D Gaussian được tính từ hàm phân phối Gaussian:
$$G(x,y)= \frac{1}{2\pi\sigma^{2}}e^{-\frac{x^{2}+y^{2}}{2\sigma^{2}}}$$
Triển khai C++
#include <cmath>
#include <iomanip>
#include <iostream>
#define PI 3.1415
using namespace std;
void calc_filter(double kernel[][5]) {
double sigma = 1.0;
double q = 2.0 * sigma * sigma;
double sum = 0.0;
for (int x = -2; x <= 2; x++) {
for (int y = -2; y <= 2; y++) {
double p = sqrt(x*x + y*y);
kernel[x+2][y+2] = exp(-(p*p)/q) / (PI * q);
sum += kernel[x+2][y+2];
}
}
// Chuẩn hóa để tổng = 1
for (int i = 0; i < 5; i++)
for (int j = 0; j < 5; j++)
kernel[i][j] /= sum;
}
int main() {
double kernel[5][5];
calc_filter(kernel);
for (int i = 0; i < 5; ++i) {
for (int j = 0; j < 5; ++j)
cout << fixed << setprecision(6) << kernel[i][j] << " ";
cout << endl;
}
return 0;
}
Kết quả (Kernel 5x5, σ=1)
0.002969 0.013306 0.021938 0.013306 0.002969 0.013306 0.059634 0.098320 0.059634 0.013306 0.021938 0.098320 0.162103 0.098320 0.021938 0.013306 0.059634 0.098320 0.059634 0.013306 0.002969 0.013306 0.021938 0.013306 0.002969
Lưu ý: Kernel đối xứng, tổng các phần tử = 1. Kích thước kernel thường chọn 6σ+1.