源码
/*************************************************************************
> File Name: ddd.cpp
> Author:
> Mail: 1@163.com
> Created Time: 2022年06月17日 星期五 15时38分43秒
************************************************************************/
#include<iostream>
#include<opencv2/opencv.hpp>
using namespace cv;
using namespace std;
int main(int argc, char** argv)
{
VideoCapture video;
// 打开视频
video.open("radar.mp4");
// 判断是否成功打开
if (!video.isOpened())
{
cout << "open video failed!" << endl;
getchar();
return -1;
}
cout << "open video success!" << endl;
Mat frame;
namedWindow("video");
// 获取视频参数
double fps = video.get(CAP_PROP_FPS);//帧率
int fcount = video.get(CAP_PROP_FRAME_COUNT);//全部帧数
int width = video.get(CAP_PROP_FRAME_WIDTH);//获取宽度
int height = video.get(CAP_PROP_FRAME_HEIGHT);//获取高度
cout << "total height is:" << height << endl;
cout << "total width is:" << width << endl;
cout << "total frame is:" << fcount << endl;//全部帧数
cout << "total sec is:" << fcount/fps << endl;//总时间
// 初始化需保存的视频格式
VideoWriter w1;
int encode_type = VideoWriter::fourcc('M', 'J', 'P', 'G');
bool isColor = true;
string filename = "test_save.avi";
w1.open(filename, encode_type, fps, cv::Size(width, height), isColor);
if (!w1.isOpened()) {
cout << "视频打开失败" << endl;
}
// 设置视频从第2秒开始读
video.set(CV_CAP_PROP_POS_MSEC,2*1000);
// 设置视频的有效帧数,28是秒,fps是帧率,即计算需要从原视频裁减的帧数是28*fps
int frameNum = 28 * fps;
int frameIndex = 0;
int s = 30;
if (fps != 0)
{
int s = 1000 / fps;
}
cout << "fps :" << fps << endl;
s = s / 2;//两倍速度
for (;;)
{
// 当达到有效帧数时退出
frameIndex ++;
if(frameIndex > frameNum){
return 0;
}
// 读视频数据
video.read(frame);
// 判断是否有数据
if (frame.empty())break;
// 写入新的视频文件
w1.write(frame);
// 可视化
imshow("video", frame);
waitKey(s);
}
waitKey(0);
return 0;
}
编译
g++ videoClip.cpp -o videoClip `pkg-config --cflags --libs opencv`
运行
- 将videoClip程序和视频文件radar.mp4放在同一个目录中
- 运行videoClip程序
./videoClip
若是需要修改视频的开始时间,就修改下方的2*1000
// 设置视频从第2秒开始读
video.set(CV_CAP_PROP_POS_MSEC,2*1000);
若是需要修改结束时间就修改下方的28的值为(终止时间-开始时间)
// 设置视频的有效帧数,28是秒,fps是帧率,即计算需要从原视频裁减的帧数是28*fps
int frameNum = 28 * fps;