基于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;
}
相关推荐
2401_841495646 小时前
【操作系统】进程同步与互斥实验报告
c++·算法·操作系统·进程·并发·同步·互斥
fqbqrr6 小时前
2607C++,soui与安卓
c++·soui
墨染天姬7 小时前
[V2X]音频数据流图
音视频
fqbqrr10 小时前
2607C++,使用微软detours勾挂工具
c++
蓝悦无人机13 小时前
C++基础 — 函数总结
开发语言·c++
我不是懒洋洋14 小时前
从零实现一个分布式监控:Prometheus的核心设计
c++
An_s14 小时前
c++对接pdfium(一)win系统篇
开发语言·c++
众少成多积小致巨15 小时前
C++ 规范参考(上)
c++
byte轻骑兵17 小时前
【AVDTP】规范精讲[6]: 打通全流程,蓝牙音频连接背后的12步信令博弈
人工智能·音视频·avrcp·蓝牙耳机·蓝牙车机
qq36219670517 小时前
# 视频转文字准确率如何提升?影响识别质量的 6 个关键因素与优化技巧
音视频