views:

388

answers:

4

hi everyone,am trying to calculate mean and variance using 3X3 window over image(hXw) in opencv...here is my code...is there any accuracy issues with this??or is there any other efficient method to do it in one pass.?

int pi,a,b;

for(i=1;i<h-1;i++)
{
    for(j=1;j<w-1;j++)
    {   int sq=0,sum=0;
        double mean=0;
        double var=0;
        for(a=-1;a<=1;a++)
        {
            for(b=-1;b<=1;b++)
            {
                pi=data[(i+a)*step+(j+b)];
                sq=pi*pi;
                sum=sum+sq;
                mean=mean+pi;
            }
        }
        mean=mean/9;
        double soa=mean*mean;//square of average
        double aos=sum/9;//mean of squares
        double var=aos-soa;//variance
    }
}
+2  A: 

That is a pretty well-researched topic, see e.g. this Wikipedia article on variance calculations.

One of the issues that sometimes gets mentioned is accumulated numerical errors; you need to decide if that may be an issue. If the values you compute over are similar in range that it may be less of an issue.

Dirk Eddelbuettel
thnx for link....i think its better to go with Naive algorithm.
ajith
A: 

You should be fine even with floats over such a small number of pixels. Typically you need doubles if you're doing this kind of thing over an entire image.

Paul R
+2  A: 

With respect to computational efficiency I would recommend doing this in the Fourier domain instead of the time (image) domain using convolutions. Remember, a convolution is a simple multiplication in the Fourier domain. Just like in time series where the spectral density function is the variance decomposed as a function of frequency, one can extend this into two dimensions for an image. Should be much better than nested for-loops.

I don't have the code on me at the moment. but this technique has been used in algorithms like "fast template matching" for object detection or image registration.

bjwhitcher
ahh...that sounds different view...can u throw some light on that? or post any links leading to there...?
ajith
Okay, here is a previous conversation in stackoverflow:http://stackoverflow.com/questions/676709/fast-way-to-implement-2d-convolution-in-c...I would still argue that the FFT (maybe the FFTW implementation) is a good idea. A reference to fast template matching may be found athttp://www.idiom.com/~zilla/Work/nvisionInterface/nip.pdf...which outlines cross-correlation methods used in image registration. The mean and variance are components of the cross-correlation function, so it's all there for you.
bjwhitcher
A: 

You should better use image integrals for quick local mean and standard deviation calculation! All you need in that case is to correctly calculate the boundaries of the mask window at each position of the image. It will be much more faster. If you will need a sample code, please ask for that.

erjik
@erjik:it would be very helpful.my mail id:[email protected]
ajith