Reputation: 410
This is my code to get frame from video. I want to show 2 frame in video with looping and condition.
int main( int argc, char** argv )
{
string fileName = "E:\\Tugas Akhir\\Video Master\\city_1.avi";
Mat image1;
Mat image2;
Mat frame;
cv::Mat result;
VideoCapture cap(fileName);
if(!cap.isOpened())
return -1;
Mat edges;
for(int loop=0;;loop++)
{
//std::cout<<loop<<endl;
cap >> frame; // get a new frame from camera
if(loop>0 && (loop%20)==0){
//std::cout<<"frame 2"<<endl;
image2=frame;
**imshow("image2",image2);**
break;
}else if(loop==0){
image1=frame;
**imshow("image1",image1);**
//std::cout<<"frame 1"<<endl;
}
//loop++;
if(waitKey(30) >= 0) break;
}
waitKey(0);
return 0;
}
And here's the result, 2 windows with 2 different image
but when i change imshow("image1",image1) method position ...
if(loop>0 && (loop%20)==0){
//std::cout<<"frame 2"<<endl;
image2=frame;
**imshow("image1",image1);**
**imshow("image2",image2);**
break;
}else if(loop==0){
image1=frame;
//std::cout<<"frame 1"<<endl;
}
image1 windows show same picture with image2,
i don't know why it show strange result, please tell me how to fix it, thank you
Upvotes: 1
Views: 2217
Reputation: 1212
What you're facing is essentially the lack of support for copy-on-write in OpenCV Mat's overloaded =
operator. It basically means that image1
and frame
will share their data.
A convenient way of seeing this is, when you write image1 = frame
, called "shallow copying", you're creating a reference image1
to the Mat frame
. So after 20 iterations when you display image1
, you're actually displaying frame
itself.
This wouldn't be the case if you'd written something like image1 = frame.clone()
, because in that case you're actually making a separate copy of frame
.
Also check this out.
Upvotes: 1
Reputation: 39786
an assignment like this:
image1 = frame;
does only a shallow copy. the Mat struct gets copied, the pixels are shared
so, in your 2nd example you're overwriting image1 with the current frame. if you want to 'cache' Mats, use:
image1 = frame.clone(); // deep copy
Upvotes: 3