VideoCapture:OpenCV的读视频类

VideoCapture可以从文件或设备中读取视频。有两种构造方式:

[cpp]
VideoCapture::VideoCapture(const string& filename);
VideoCapture::VideoCapture(int device);
[/cpp]
第一种是文件名,第二种是设备编号。
VideoCapture::read方法可获取一帧图像
[cpp]
VideoCapture& VideoCapture::operator»(Mat& image);
bool VideoCapture::read(Mat& image);
[/cpp]
注意,read方法中的Mat是引用,实则是VideoCapture内部解析出来的帧图像的引用,而OpenCV中Mat的复制构造函数和赋值操作符共享数据,仅构造矩阵头,所以读取下一帧后,image中的数据就变化了。如果同时获取多帧图像,应用Mat::clone()方法复制image中的数据,这样就不会丢失了。例如
[cpp]
video_capture.read(frame1);
video_capture.read(frame2);
[/cpp]
此时,frame1和frame2均为后面的一帧,不是想要的那样。我们应该这样
[cpp]
video_capture.read(frame);
frame.clone(frame1);
video_capture.read(frame);
frame.clone(frame2);
[/cpp]
这样,frame1和frame2就存储相邻两帧了。