基于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;
}
相关推荐
XiaoCCCcCCccCcccC36 分钟前
多路复用 select -- select 的介绍,select 的优缺点,select 版本的 TCP 回显服务器
服务器·c++
XiaoCCCcCCccCcccC37 分钟前
多路复用 poll -- poll 的介绍,poll 的优缺点,poll 版本的 TCP 回显服务器
服务器·网络·c++
小π军2 小时前
STL利器:upper_bound与lower_bound的使用
c++
Zx623652 小时前
13.泛型编程 STL技术
java·开发语言·c++
The Last.H2 小时前
Educational Codeforces Round 185 (Rated for Div. 2)A-C
c语言·c++·算法
caron42 小时前
C++ 推箱子游戏
开发语言·c++·游戏
百***35483 小时前
前端视频处理开发
前端·音视频
路过君_P3 小时前
C++ 算法题解:迷宫寻路
c++·算法·深度优先
止观止3 小时前
告别“祖传C++”:开启你的现代C++之旅
c++·c++11·c++20·编程思想·现代c++