Thursday, December 26, 2024
Google search engine
HomeGuest BlogsGaussian Filter Generation in C++

Gaussian Filter Generation in C++

Gaussian Filtering is widely used in the field of image processing. It is used to reduce the noise of an image. In this article we will generate a 2D Gaussian Kernel. The 2D Gaussian Kernel follows the below given Gaussian Distribution. 
G(x, y)=\frac{1}{2\pi \sigma ^{2}}e^{-\frac{x^{2}+y^{2}}{2\sigma ^{2}}}
Where, y is the distance along vertical axis from the origin, x is the distance along horizontal axis from the origin and ? is the standard deviation.

Implementation in C++ 

C++




// C++ program to generate Gaussian filter
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
  
// Function to create Gaussian filter
void FilterCreation(double GKernel[][5])
{
    // initialising standard deviation to 1.0
    double sigma = 1.0;
    double r, s = 2.0 * sigma * sigma;
  
    // sum is for normalization
    double sum = 0.0;
  
    // generating 5x5 kernel
    for (int x = -2; x <= 2; x++) {
        for (int y = -2; y <= 2; y++) {
            r = sqrt(x * x + y * y);
            GKernel[x + 2][y + 2] = (exp(-(r * r) / s)) / (M_PI * s);
            sum += GKernel[x + 2][y + 2];
        }
    }
  
    // normalising the Kernel
    for (int i = 0; i < 5; ++i)
        for (int j = 0; j < 5; ++j)
            GKernel[i][j] /= sum;
}
  
// Driver program to test above function
int main()
{
    double GKernel[5][5];
    FilterCreation(GKernel);
  
    for (int i = 0; i < 5; ++i) {
        for (int j = 0; j < 5; ++j)
            cout << GKernel[i][j] << "\t";
        cout << endl;
    }
}


Output: 

0.00296902    0.0133062    0.0219382    0.0133062    0.00296902    
0.0133062    0.0596343    0.0983203    0.0596343    0.0133062    
0.0219382    0.0983203    0.162103    0.0983203    0.0219382    
0.0133062    0.0596343    0.0983203    0.0596343    0.0133062    
0.00296902    0.0133062    0.0219382    0.0133062    0.00296902

References: 
https://en.wikipedia.org/wiki/Gaussian_filter

 

Last Updated :
11 Sep, 2023
Like Article
Save Article


Previous

<!–

8 Min Read | Java

–>


Next


<!–

8 Min Read | Java

–>

Share your thoughts in the comments

RELATED ARTICLES

Most Popular

Recent Comments