# overflow avoidance on multi-frame accumulation

I asked a question a few weeks ago about calculating image statistics (mean, variance, skewness, etc.) across multiple frames. The answers I received worked nicely, but I have a follow-on question.

I am starting with an array of matrices ( Mat *frameArray ) of type CV_U16C1 or CV_U8C1. When accumulating multiple frames, it is necessary to perform the accumulation and division in floating point math to avoid overflow. My current implementation is as the following:

```
Mat sumImage, tempDouble;
frameArray[0].convertTo(sumImage,CV_64FC1,0); // initialize accumlation to zeros
for(int i=0; i < numFrames; i++) {
frameArray[i].convertTo(tempDouble,CV_64FC1);
sumImage += tempDouble;
}
```

This works, but requires converting each frame to double precision, which seems slow and rather inefficient. In fact the "convertTo" function accounts for more than half of the time required for this loop. Can anyone recommend a more efficient approach? Is there a way to recast the pointer to the matrix array?

Try converting to CV_32SC1 instead of CV_64FC1, it should be more than enough, unless you average more than 2^24 frames, which I doubt... Integer math is sometimes much faster, and conversions are especially fast.