slow when calculate moment [closed]

asked 2016-11-29 08:32:53 -0600

greenworld gravatar image

updated 2016-11-29 09:18:59 -0600

berak gravatar image

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 +=<uchar>(y, x);
            case 01:
                mm += y*<uchar>(y, x);
            case 10:
                mm += x*<uchar>(y, x);
            case 11:
                mm += x*y*<uchar>(y, x);
            case 02:
                mm += y*y*<uchar>(y, x);
            case 20:
                mm += x*x*<uchar>(y, x);
    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?

edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by sturkmen
close date 2020-10-04 06:37:54.255835



Whu don't you want to use Opencv function?

LBerger gravatar imageLBerger ( 2016-11-29 08:52:36 -0600 )edit

If you want speed, never use at use pointers instead. Pass the cv::Mat by const reference. Also, cache loop end conditions, meaning don't call row.size() HxW times.

Der Luftmensch gravatar imageDer Luftmensch ( 2016-11-29 09:09:15 -0600 )edit

Also, don't post images of code, post the code and then use the formatting options.

Der Luftmensch gravatar imageDer Luftmensch ( 2016-11-29 09:10:40 -0600 )edit

Hi Der, can you give me more detail about "never use at use pointers instead". Thank you!

greenworld gravatar imagegreenworld ( 2016-11-29 09:49:06 -0600 )edit

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.

Tetragramm gravatar imageTetragramm ( 2016-11-29 14:49:27 -0600 )edit

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

StevenPuttemans gravatar imageStevenPuttemans ( 2016-11-30 04:39:11 -0600 )edit

Thank for your support!

greenworld gravatar imagegreenworld ( 2016-11-30 06:36:11 -0600 )edit