基于C++和OpenCv对视频进行抽帧

下列代码演示了从某.MP4视频文件内以一秒一帧进行抽取,并对抽出的图片以秒数命名的全过程。

cpp 复制代码
#include <opencv2/opencv.hpp>
#include <iostream>
#include <string>
#include <direct.h>

using namespace cv;
using namespace std;

void extractFrames(const string& videoPath, const string& outputFolder) {
	// 打开视频文件
	VideoCapture cap(videoPath);
	if (!cap.isOpened()) {
		cerr << "Error: Unable to open video file." << endl;
		return;
	}

	// 获取视频帧率
	double fps = cap.get(CAP_PROP_FPS);

	// 确保输出文件夹存在
	if (outputFolder.empty()) {
		cerr << "Error: Output folder not specified." << endl;
		return;
	}
	if (_mkdir(outputFolder.c_str()) != 0) {
		cerr << "Error: Unable to create output folder." << endl;
		return;
	}

	// 初始化计数器
	int frameCount = 0;

	// 循环读取视频帧
	Mat frame;
	while (cap.read(frame)) {
		// 每秒提取一帧
		if (frameCount % static_cast<int>(fps) == 0) {
			// 将当前帧保存为图像文件
			imwrite(outputFolder + "/" + to_string(frameCount / static_cast<int>(fps)) + ".jpg", frame);
		}
		frameCount++;
	}

	// 释放视频对象
	cap.release();

	cout << "视频提取完成!" << endl;
}

int main() {
	// 输入视频文件路径和输出文件夹路径
	string videoFile = "输入路径";
	string outputFolder = "输出路径";

	// 调用函数提取视频帧
	extractFrames(videoFile, outputFolder);

	return 0;
}
相关推荐
AI搅拌机20 小时前
LTX2.3 IC-LORA动作迁移,通过depth、POSE、Canny精准控制生成的视频!
人工智能·音视频
君义_noip21 小时前
CSP-S 2025 入门级 第一轮(初赛) 完善程序(1)
c++·算法·信息学奥赛·初赛·csp 第一轮
蒋胜山21 小时前
PowerPoint插入音频报错
windows·经验分享·音视频
byte轻骑兵1 天前
【LE Audio】CAP精讲[5]: 导演上线!Initiator音频协同全流程合规指南
人工智能·音视频·低功耗·le audio
蜡笔小马1 天前
07.C++设计模式-组合模式
c++·设计模式·组合模式
liulilittle1 天前
TCP UCP v1.0:BBR 的非破坏性约束层
网络·c++·网络协议·tcp/ip·算法·c·通信
每天回答3个问题1 天前
leetcodeHot100 | 104.二叉树的最大深度
c++·面试·
坚果派·白晓明1 天前
【鸿蒙PC三方库移植适配框架解读系列】第五篇:完整流程图与角色职责
c语言·c++·华为·harmonyos·鸿蒙
xiao_li_ya1 天前
C++学习日记1(`*`的理解、const关键词)
开发语言·c++
知识领航员1 天前
2026年精选4款音频处理软件:Adobe Audition领衔,蘑兔AI音乐紧随其后
adobe·音视频