简体   繁体   中英

OpenCV (C++) matrix release not working as expected?

According to OpenCV Intro Doc , code that I wrote below should result in im being frame 2 and imPrev frame 1; however, they are both frame 2. Why and what is a simple and efficient fix?

Mat im, imPrev;
VideoCapture v(fileName);

v >> im;           // im = frame1
imPrev = im;       // im = imPrev = frame1
im.release();      // im = empty, imPrev = frame1
v >> im;           // I wanted      im = frame2, imPrev = frame1
                   // but it became im = imPrev = frame2

(OpenCV 2.4.5)

Note: The last three lines go in a loop so I'd preferably like to avoid unnecessary memory allocation on every iteration (eg. using clone ).

if you do like:

v >> im;

you get an img, that points to static memory inside the webcam driver.

it is not refcounted, so your im.release() has no effect at all.

-------------

but the problem is here:

imPrev = im;   
// this is a shallow copy only, the Mat struct gets copied, the pixels are shared.

replace it with:

imPrev = im.clone(); // imPrev now owns it own pixels

--------------

[edit]

imho, you also don't want 2 >> or read operations per loop, so maybe make it :

Mat cur,prev;
while(1)
{
   capture >> cur;
   if ( ! prev.empty() )
   {
        process(cur,prev);
   }
   prev = cur.clone();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM