Ask Your Question
0

Understand the memory managment while using imread() on allocated Mat

asked 2012-10-11 06:46:19 -0600

Legor gravatar image

updated 2012-10-11 06:52:33 -0600

Hello everyone.

I'm currently using openCV 2.4.2 for C++ development in the fields of image processing. I just noticed a behaviour extracting some edges with the Canny operator which i can't really make sense of. In fact i dont believe it really has to do with the Canny implementation but more with some memory managment which eiterhway is bugged somehow or i'm using it the wrong way (or in an unsupported one).

Please help me to understand what is going on. See the following code snippet which produces this behaviour.

Mat grayImage;
for (int k = 0; k < 20; k++) 
{
   Mat edgeMat;
   grayImage = imread( "myImage.jpg", 0 );

   /// Canny detector
   Canny( grayImage, edgeMat, 80, 200, 3, true );

   // Count the number of edge pixels
    unsigned int count = 0;
    for (int i = 0; i < edgeMat.rows; i++)
    {
        // Use the raw pointer for fastest access
        const unsigned* Mi = edgeMat.ptr<unsigned>(i);
        for (int j = 0; j < edgeMat.cols; j++)
        {
            // If the pixel is not black (it belongs to an edge), count.
            if (Mi[j] != 0)
            {
                count++;
            }
        }

    }

    cout << count << endl;
  }

Now the output is something like (showing the number of edge pixels per iteration):

2651
2651
2398
2651
2398
...

To sum it up. It seems that the Canny produces different edges allthough the same image and parameters are used. But when i release the image Mat first with edgeMat.release() every time the same number of edges is found.

But why is it that way?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
5

answered 2012-10-12 02:15:13 -0600

Vladislav Vinogradov gravatar image

edgeMat has CV_8UC1 type. You should iterate it with unsigned char type:

const unsigned char* Mi = edgeMat.ptr<unsigned char>(i);
edit flag offensive delete link more

Comments

Thank, you this was the problem.

Legor gravatar imageLegor ( 2012-10-16 07:13:53 -0600 )edit

Question Tools

Stats

Asked: 2012-10-11 06:46:19 -0600

Seen: 1,461 times

Last updated: Oct 12 '12