栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

文章目录
  • 源码
  • 编译
  • 运行

源码

#include
#include
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;
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/980236.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号