slow when calculate moment [closed]
Hi everyone, I try to write my own function to calc the moments as below:
double getMoment(Mat roi, uint8_t mode) {
double mm = 0;
for (int x = 0; x < roi.size().width; ++x) {
for (int y = 0; y < roi.size().height; ++y) {
switch (mode)
{
case 00:
mm += roi.at<uchar>(y, x);
break;
case 01:
mm += y*roi.at<uchar>(y, x);
break;
case 10:
mm += x*roi.at<uchar>(y, x);
break;
case 11:
mm += x*y*roi.at<uchar>(y, x);
break;
case 02:
mm += y*y*roi.at<uchar>(y, x);
break;
case 20:
mm += x*x*roi.at<uchar>(y, x);
break;
default:
break;
}
}
}
return mm;
}
My problem is my own function is quite slower than the moments of OpenCV library. So can you help me to improve my code to make it faster?
Whu don't you want to use Opencv function?
If you want speed, never use
at
use pointers instead. Pass thecv::Mat
by const reference. Also, cache loop end conditions, meaning don't callrow.size()
HxW times.Also, don't post images of code, post the code and then use the formatting options.
Hi Der, can you give me more detail about "never use at use pointers instead". Thank you!
First, you're traversing the image wrong. You should be going along rows, not columns.
Then at the start of each row, create a uchar* pRow = roi.ptr<uchar>(y); Then access using pRow[x] instead of the at() function.
But again, the best remark so far by @LBerger, just using the Moments() function, would be a better approach. It is simply optimized when your code is not XD
Thank for your support!