高斯滤波(Gaussian filter)

高斯滤波是一种线性平滑滤波,低通滤波器,可以去除高斯噪声。具体操作是:利用二维高斯分布函数,生成高斯模板,然后用模板去扫描图像中的每一个像素,用模板确定的领域内像素的加权平均值作为新图像中模板中心位置的像素值。

  • 常用的二维高斯分布函数
    G(x,y)=ex22σ21y22σ22 G ( x , y ) = e − x 2 2 ∗ σ 1 2 − y 2 2 ∗ σ 2 2

c++ 代码实现

#include 

using namespace std;
using namespace cv;

//边界未处理,所以滤波后新图像有黑框
void gausssianFilter(Mat srcimg, Mat dstimg, double sigma1, double sigma2=-1)
{
    if (sigma1 <= 0 )
    {
        return;
    }
    if (sigma2 < 0)
    {
        sigma2 = sigma1;
    }
    int radius1 = (int)(3 * sigma1 + 0.5f);
    int radius2 = (int)(3 * sigma2 + 0.5f);
    Mat kernel(2 * radius1 + 1, 2 * radius2 + 1, CV_32F);
    float fsum = 0;
    for (int y = -radius1; y <= radius1; y++)//计算高斯卷积模板
    {
        for (int x = -radius2; x <= radius2; x++)
        {
            kernel.at<float>(y+radius1, x+radius2) = (float)exp(-x*x / (sigma2*sigma2) - y*y / (sigma1*sigma1));
            fsum += kernel.at<float>(y+radius2, x+radius1);
        }
    }

    for (int y = -radius1; y <= radius1; y++)
    {
        for (int x = -radius2; x <= radius2; x++)
        {
            kernel.at<float>(y+radius1, x+radius2) = kernel.at<float>(y+radius1, x+radius2) / fsum;
        }
    }

    //用高斯模板与原图像做卷积
    if (!dstimg.data)
    {
        dstimg.d
    }
    uchar *data =  srcimg.data;
    uchar *newData = dstimg.data;
    float *pixel = new float[srcimg.channels()];
    for (int row = radius1; row < srcimg.rows - radius1; row++)
    {
        int row_step = srcimg.cols * srcimg.channels();
        for (int col = radius2; col < srcimg.cols - radius2; col++)
        {
            // 每个通道值置零
            for (int channel = 0; channel < srcimg.channels();channel++)
            {
                pixel[channel] = 0;
            }
            for (int i = -radius1; i <= radius1; i++)
            {
                for (int j = -radius2; j <= radius2; j++)
                {
                    //计算每个通道的值
                    int index = (row + i)*row_step + (col + j)*srcimg.channels();
                    for (int channel = 0; channel < srcimg.channels(); channel++)
                    {
                        pixel[channel] += data[index + channel] * kernel.at<float>(i + radius1, j + radius2);
                    }

                }
            }
            int index = row*row_step + col*srcimg.channels();
            for (int channel = 0; channel < srcimg.channels(); channel++)
            {
                newData[index + channel] = saturate_cast(pixel[channel]);
            }

        }
    }
    delete[] pixel;
    return;
}


//test
int main()
{
    Mat srcimg = imread("rmb.bmp");
    Mat gaussianImg /*= Mat::zeros(srcimg.rows, srcimg.cols, srcimg.type())*/;
    gausssianFilter(srcimg, gaussianImg, 0.5, 0.6);

    imshow("source image", srcimg);
    imshow("gaussian image", gaussianImg);

    waitKey(0);
    return 0;
}



高斯滤波

你可能感兴趣的:(图像处理,高斯滤波)