opencv图片转换为avi格式视频

46 篇文章 0 订阅


#include <opencv.hpp>
#include <iostream>
#include <Windows.h>

std::string AddPathSeparator(const std::string &path)
{
	std::string ret = path;
	if (!ret.empty() && ret[ret.length()-1]!='\\') {
		ret += "\\";
	}
	return ret;
}

void FindInAll(const std::string& srcDir, std::vector<std::string> &ret, const std::string& filter="") 
{
	std::string dir = AddPathSeparator(srcDir);
	dir += "*.*";
   
	WIN32_FIND_DATAA wfd;
	HANDLE hFind = FindFirstFileA(dir.c_str(), &wfd);
	if (hFind == INVALID_HANDLE_VALUE) {
		return;
	}

	do {
		if (wfd.cFileName[0] == '.') {
			continue; // 过滤当前目录和上级目录
		}
		
		std::string childDir = AddPathSeparator(srcDir) + wfd.cFileName;
		if (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
			FindInAll(childDir, ret, filter);
		} else {
			if (filter.empty() || childDir.substr(childDir.length()-filter.length())==filter) {
				ret.push_back(childDir);
			}
		}
	} while (FindNextFileA(hFind, &wfd));
	FindClose(hFind);
}

bool image2video(const std::string &bmpDir, const std::string &aviPath)
{
	if (bmpDir.empty() || aviPath.empty()) {
		return false;
	}

	cv::VideoWriter aviWriter;
	std::vector<std::string> images;
	FindInAll(bmpDir, images, "jpg");
	for (std::vector<std::string>::iterator iter=images.begin(),
		end=images.end(); iter!=end; ++iter) {
			cv::Mat frame = cv::imread(*iter);
			int frameRate = 1;
			if (!aviWriter.isOpened()) {
				cv::Size frameSize;
				frameSize.width = frame.cols;
				frameSize.height = frame.rows;
				if (!aviWriter.open(aviPath, CV_FOURCC('M', 'J', 'P', 'G'),
					frameRate, frameSize, true)) {
						std::cout << "VideoWriter open failed!" << std::endl;
						return false;
				}
			}
			aviWriter.write(frame);
			cv::waitKey(frameRate);
	}
	return true;
}

int main(int argc, char *argv[])
{
	if (image2video("G:\\test", "G:\\test\\test.avi")) {
		std::cout << "success" << std::endl;
	} else {
		std::cout << "failed" << std::endl;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值