开发者

mean and variance of image in single pass

开发者 https://www.devze.com 2022-12-26 13:12 出处:网络
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??oris there any other efficientmethod to do it in one pas

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;
      开发者_如何学C  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
    }
}


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消