二维高斯函数
高斯模板
高斯函数离散化并归一化。得到的是浮点值。下面是一个3X3的例子
C++代码
MyImage MyImage::Gauss(double sigma, int n) const
{ // 高斯模糊
MyImage temp(cv::Mat(rows, cols, CV_8U, cv::Scalar(0)));
double** gauss = new double*[n]; //高斯模板
double sum = 0;
for (int i = 0; i < n; i++)
gauss[i] = new double[n];
for (int i = 0; i < n; i++)
{
int x = i - n / 2;
for (int j = 0; j < n; j++)
{
int y = j - n / 2;
gauss[i][j] = exp(-(pow(x, 2) + pow(y, 2)) / (2 * pow(sigma, 2))); //因为要归一化,所以指数前的系数可以不计算
sum += gauss[i][j];
}
}
for (int i = 0; i < n; i++) // 归一化
for (int j = 0; j < n; j++)
gauss[i][j] /= sum;
for (int i = 0; i < rows; i++)
for (int j = 0; j < cols; j++)
{
for (int m = 0; m < n; m++)
for (int k = 0; k < n; k++)
temp.ptr(i)[j] += gauss[m][k] * ptr(i - n / 2 + m)[j - n / 2 + k];
}
return temp;
}