1

I'm coding using C++ and opencv on linux. I've found this similar question; although, I can't quite get it to work.

What I want to do is read in a video file and store a certain number of frames in an array. Over that number, I want to delete the first frame and add the most recent frame to the end of the array.

Here's my code so far.

VideoCapture cap("Video.mp4");
int width = 2;
int height = 2;
Rect roi = Rect(100, 100, width, height);

 vector<Mat> matArray;
int numberFrames = 6;
int currentFrameNumber = 0;

for (;;){

    cap >> cameraInput;
    cameraInput(roi).copyTo(finalOutputImage);

    if(currentFrameNumber < numberFrames){
        matArray.push_back(finalOutputImage);
    }else if(currentFrameNumber <= numberFrames){
        for(int i=0;i<matArray.size()-1; i++){
            swap(matArray[i], matArray[i+1]);
        }
        matArray.pop_back();
        matArray.push_back(finalOutputImage);
    }

    currentFrameNumber++;
 }

My understanding of mats says this is probably a problem with pointers; I'm just not sure how to fix it. When I look at the array of mats, every element is the same frame. Thank you.

Community
  • 1
  • 1
  • if you want to use the array to store `numberFrames` last frames, why do you use `}else if(currentFrameNumber <= numberFrames){` ? This if will prevent anything from happening when `currentFrameNumber > numberFrames`, which will happen quite fast. So I'd say you are merely storing frames 1-6 (exluding 0) no matter how long the video is. – Pafka Oct 16 '14 at 19:32
  • Mat is just a smart pointer, and what you get from the capture, points at *static* memory. what you want is: `matArray.push_back(finalOutputImage.clone());` – berak Oct 16 '14 at 20:07
  • @Pafka Thank you for pointing out my typo. It should have been a greater than sign. Still doesn't fix the problem but what berak said does. – tierratheseeress Oct 17 '14 at 20:45

1 Answers1

3

There's no need for all this complication if you were to make use of C++'s highly useful STL.

if( currentFrameNumber >= numberFrames )
    matArray.remove( matArray.begin() );
matArray.push_back( finalOutputImage.clone() );     //check out @berak's comment

should do it.

a-Jays
  • 1,182
  • 9
  • 20
  • Including .clone() fixes the problem with them all showing the same frame. When I build it, I get the error that "remove could not be resolved". Did a bit of research. It's .erase that needs to be used. Thanks for helping clean up my code. – tierratheseeress Oct 17 '14 at 20:51
  • I'm not sure why that is so. Check this out: http://stackoverflow.com/questions/19296958/difference-between-stdremove-and-erase-for-vector – a-Jays Oct 18 '14 at 01:16