基于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;
}
相关推荐
炸膛坦客4 小时前
单片机/C/C++八股:(二十)指针常量和常量指针
c语言·开发语言·c++
炸膛坦客5 小时前
单片机/C/C++八股:(十九)栈和堆的区别?
c语言·开发语言·c++
2401_831824966 小时前
代码性能剖析工具
开发语言·c++·算法
是wzoi的一名用户啊~6 小时前
【C++小游戏】2048
开发语言·c++
Sunshine for you7 小时前
C++中的职责链模式实战
开发语言·c++·算法
qq_416018727 小时前
C++中的状态模式
开发语言·c++·算法
2401_884563247 小时前
模板代码生成工具
开发语言·c++·算法
2401_831920748 小时前
C++代码国际化支持
开发语言·c++·算法
m0_672703318 小时前
上机练习第51天
数据结构·c++·算法
2401_851272998 小时前
自定义内存检测工具
开发语言·c++·算法