目录
1--视频读取代码
# include<opencv2/opencv.hpp>
# include<cstdio>
using namespace cv;
using namespace std;
int main(int argc, char *argv[]){
VideoCapture video;
video.open("test.avi"); // 打开视频
if (!video.isOpened()){ // 打开失败
cout << "open video failed !" << endl;
return -1;
}
cout << "open video success !" << endl;
namedWindow("video");
Mat frame;
for (;;){
// 单步处理
/*
if (!video.read(frame)){
break;
}
*/
// if (frame.empty()) break;
// 分步
// 读帧,解码
if (!video.grab()){
break;
}
//转换颜色格式
if (!video.retrieve(frame)){
break;
}
imshow("video", frame);
waitKey(5);
}
getchar();
return 0;
}
2--视频属性查看
①帧率fps:每秒播放的帧数
②视频总帧数
③视频时长:视频总帧数 / 帧率
# include<opencv2/opencv.hpp>
# include<cstdio>
using namespace cv;
using namespace std;
int main(int argc, char *argv[]){
VideoCapture video;
video.open("test.avi");
if (!video.isOpened()){
cout << "open video failed !" << endl;
return -1;
}
cout << "open video success !" << endl;
namedWindow("video");
Mat frame;
int fps = video.get(CAP_PROP_FPS);
int fcount = video.get(CAP_PROP_FRAME_COUNT);
int s = 30;
if (fps != 0){
s = 1000 / fps;
}
// s = s / 2; // 2倍速
cout << "fps is " << fps << endl; // fps
cout << "total frame is " << fcount << endl; // frame_count
cout << "total time is " << float(fcount) / float(fps) << " s" << endl; // time
for (;;){
if (!video.read(frame)){
break;
}
imshow("video", frame);
waitKey(s);
}
getchar();
return 0;
}
3--视频循环播放代码
通过改变当前帧索引的数值,来达到视频循环播放的功能;
# include<opencv2/opencv.hpp>
# include<cstdio>
using namespace cv;
using namespace std;
int main(int argc, char *argv[]){
VideoCapture video;
video.open("test.avi");
if (!video.isOpened()){
cout << "open video failed !" << endl;
return -1;
}
cout << "open video success !" << endl;
namedWindow("video");
Mat frame;
for (;;){
if (!video.read(frame)){
break;
}
int cur = video.get(CAP_PROP_POS_FRAMES); // 当前帧
// 当前帧索引大于50后,重新播放
if (cur > 50){
video.set(CAP_PROP_POS_FRAMES, 0); // 设置当前帧为0, 循环播放
continue;
}
imshow("video", frame);
waitKey(5);
}
getchar();
return 0;
}