Sign in to follow this  
Khaos Dragon

Am I computing my Gaussian Kernel incorrectly?

Recommended Posts

I have just started researching Gaussian blur for some effects I want to work on and currently I am trying to compute a 2D Gaussian kernel of arbitrary size (I will worry about separable 1D kernels later). The following is a test function I have made to compute such a kernel. It only calculates the correct values for the center element (I am comparing my results against the results on the wikipedia entry for gaussian blur which has an example of a 7x7 kernel with standard deviation 0.84089642.) If anyone can tell me what I am doing wrong, it would be greatly appreciated.

void ComputeGaussianKernel( float kernel**, int size, float standardDeviation )
{
	//note: size is assumed to be an odd integer
	
	const float PI = 3.14159f;
	const float e  = 2.71828f;
	
	float center = (float) (size/2);
	float sigmaSquared = standardDeviation * standardDeviation;
	float sigma = standardDeviation;
	

	for( int x = 0; x < size; ++x )
	for( int y = 0; y < size; ++y )
	{
		float X = (float) x;
		float Y = (float) y;
		
		float distFromCenterSquared = ( X - center ) * (X - center ) + ( Y - center ) * ( Y - center );
		
		float baseEexponential = pow( e, -distFromCenterSquared / ( 2.0f * sigmaSquared ) );
		float base2exponential = pow( 2.0f, baseEexponential );
		
		kernel[x][y] = 1.0f / (2.0f*PI* pow( sigma, base2exponential ));
	}
}


Share this post


Link to post
Share on other sites
Did you mess up rows and columns? Usually x is column, y is row, so maybe instead of

kernel[x][y] =

you meant

kernel[y][x] =

?

Share this post


Link to post
Share on other sites
Quote:
Original post by RDragon1
Did you mess up rows and columns? Usually x is column, y is row, so maybe instead of

kernel[x][y] =

you meant

kernel[y][x] =

?


If it was a row column issue, I would still see that my values for non center elements are correct, just that the rows and columns are switched. What I see here are that my non center elements are entirely off.

Share this post


Link to post
Share on other sites
I figured it out, the way the formula is represented is misleading. It leads someone to think that the we are computing 1/(2PIsigma^2^e^(-u^2/(2sigma^2)) when it actually is e^(-u^2/(1sigma^2) / ( 2PIsigma^2 ).

Knowing this, the kernel[x][y] assignment in my test function should be
kernel[x][y] = baseEexponential / (2.0f*PI*sigmaSquared ) which conveniently gets rid of the base2 exponential I was computing.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this