赞
踩
看这篇文章的道友想必对高斯滤波已经很熟悉,在此就不进行赘述了,也可以看看参考资料的文章回顾一下。
二维方式是根据kernel的大小以及sigma大小生成一个 size*size的卷积核,然后再做卷积。计算量是imgWidth * imgHeight * size * size,但如果用两个一维来替代,则计算量是imgWidth * imgHeight * size * 2,计算量大大减少。
此处的数据类型ImagePro可以根据自己的需求进行定义。
double *GetGaussianKernel_1D(int arr_size, double sigma) { double *array = new double[arr_size]; int center_i = arr_size / 2; double sum = 0.0f; double sigma2 = (2.0f*sigma*sigma); for (int i = 0; i < arr_size; i++) { array[i] = exp(-(1.0f)* (((i - center_i)*(i - center_i)) / sigma2)); sum += array[i]; } //归一化求权值 for (int i = 0; i < arr_size; i++) { array[i] /= sum; cout << array[i] << " "; } cout << endl; return array; } void GaussBlur_x(ImagePro* src, ImagePro* dst, int w, int h, int kernelSize, double *gaussianArray) { int center = kernelSize / 2; int ind = 0; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { double sum = 0.0; for (int k = -center; k <= center; k++) { if (j + k < 0 || j + k >= w) continue; ind = i*w + j + k; sum += src[ind] * gaussianArray[k + center]; } // 放入中间结果 ind = ind = i*w + j; dst[ind] = MAX(MIN(sum, 255), 0); } } } void GaussBlur_y(ImagePro* src, ImagePro* dst, int w, int h, int kernelSize, double *gaussianArray) { int center = kernelSize / 2; int ind = 0; for (int i = 0; i < h; i++) { for (int j = 0; j < w; j++) { double sum = 0.0; for (int k = -center; k <= center; k++) { if (i + k < 0 || i + k >= h) continue; ind = (i+k)*w + j; sum += src[ind] * gaussianArray[k + center]; } // 放入中间结果 ind = ind = i*w + j; dst[ind] = MAX(MIN(sum, 255), 0); } } } Mat FastGaussian(cv::Mat _src, int kernelSize, double sigma) { int srcW = _src.cols; int srcH = _src.rows; int radius = kernelSize / 2; //padding Margin margin; margin.down = radius; margin.up = radius; margin.left = radius; margin.right = radius; int w = _src.cols + margin.left + margin.right; int h = _src.rows + margin.up + margin.down; Mat pad(h, w, _src.type(), Scalar(0)); ImagePadding((ImagePro*)_src.data, _src.cols, _src.rows, (ImagePro*)pad.data, margin); _src = pad.clone(); double *gaussianArray = GetGaussianKernel_1D(kernelSize, sigma); int center = kernelSize / 2; cv::Mat temp = _src.clone(); cv::Mat dst = _src.clone(); int channels = _src.channels(); // X方向 GaussBlur_x((ImagePro*)_src.data, (ImagePro*)temp.data, _src.cols, _src.rows, kernelSize, gaussianArray); // Y方向 GaussBlur_y((ImagePro*)temp.data, (ImagePro*)dst.data, _src.cols, _src.rows, kernelSize, gaussianArray); delete[] gaussianArray; return dst(Rect(radius, radius, srcW, srcH)); }
[1] Opencv之分离高斯滤波
[2] 图像处理之高斯滤波:原理、代码实现和优化加速
[3] 高斯滤波(GaussianFilter)原理及C++实现
[4] 快速高斯滤波、高斯模糊、高斯平滑
[5] 快速高斯滤波(用两个一维代替二维)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。