Opencv获取指定时间内的视频片段以及帧

本文介绍了一段C++代码,用于利用OpenCV库从视频中裁剪指定时间段,并以两倍速度播放。通过设置视频的开始时间和有效帧数,可以灵活调整裁剪范围。此外,代码还展示了如何获取视频的帧率、帧数、宽度和高度等信息,并将裁剪后的视频保存为新的avi文件。
摘要由CSDN通过智能技术生成

文章目录

源码

/*************************************************************************
    > 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`

运行

  1. 将videoClip程序和视频文件radar.mp4放在同一个目录中
  2. 运行videoClip程序
./videoClip

若是需要修改视频的开始时间,就修改下方的2*1000

// 设置视频从第2秒开始读
video.set(CV_CAP_PROP_POS_MSEC,2*1000);

若是需要修改结束时间就修改下方的28的值为(终止时间-开始时间)

// 设置视频的有效帧数,28是秒,fps是帧率,即计算需要从原视频裁减的帧数是28*fps
	int frameNum = 28 * fps;
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

听雨听风眠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值