基于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;
}
相关推荐
myloveasuka2 小时前
C++进阶:利用作用域解析运算符 :: 突破多态与变量隐藏
开发语言·c++
keep intensify2 小时前
康复训练 5
linux·c++
0 0 02 小时前
CCF-CSP 38-4 月票发行【C++】考点:动态规划DP+矩阵快速幂
c++·算法·动态规划·矩阵快速幂
OxyTheCrack2 小时前
【C++】详细拆解std::mutex的底层原理
linux·开发语言·c++·笔记
八角Z2 小时前
AI短视频创作实战心得:从玩具到生产力工具亲测
人工智能·机器学习·服务发现·音视频
j_xxx404_3 小时前
力扣困难算法精解:串联所有单词的子串与最小覆盖子串
java·开发语言·c++·算法·leetcode·哈希算法
bst@微胖子3 小时前
OpenCV 案例四【人脸识别】
人工智能·opencv·计算机视觉
筱砚.4 小时前
C++——lambda
开发语言·c++·算法
sycmancia5 小时前
C++——动态内存分配、关于虚函数、关于继承中的强制类型转换
开发语言·c++
样例过了就是过了6 小时前
LeetCode热题100 路径总和 III
数据结构·c++·算法·leetcode·链表