#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;
}
}