Skip to content

Instantly share code, notes, and snippets.

@usagi
Created January 12, 2014 17:19
Show Gist options
  • Select an option

  • Save usagi/8387625 to your computer and use it in GitHub Desktop.

Select an option

Save usagi/8387625 to your computer and use it in GitHub Desktop.
#pragma once
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
namespace
{
struct cv_video_helper_t final
{
using frames_t = std::vector<cv::Mat>;
using frames_fps_t = std::tuple<frames_t, int>;
static frames_fps_t load_to_vector(const std::string& video_filename)
{
auto video = cv::VideoCapture(video_filename);
if(!video.isOpened())
throw std::runtime_error("cannot open video file.");
const int fps = int(video.get(CV_CAP_PROP_FPS));
const size_t frame_count = video.get(CV_CAP_PROP_FRAME_COUNT);
if(frame_count == 0)
throw std::runtime_error("cannot get frame count");
frames_t frames(frame_count);
for(auto& frame : frames)
{
cv::Mat source;
video >> source;
source.copyTo(frame);
}
return make_tuple(std::move(frames), std::move(fps));
}
private:
cv_video_helper_t();
};
}
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "cv_video_helper.hxx"
int main(int n, char** a)
{
if(n < 1)
throw;
// write test
{
const auto frames_fps = cv_video_helper_t::load_to_vector(a[1]);
const auto& frames = std::get<0>(frames_fps);
const auto& fps = std::get<1>(frames_fps);
{
cv::VideoWriter writer("test.avi", CV_FOURCC('X','V','I','D'), fps, cv::Size(frames.at(0).cols, frames.at(0).rows));
for(const auto& frame : frames)
writer << frame;
}
}
// read test
{
const auto frames_fps = cv_video_helper_t::load_to_vector("test.avi");
const auto& frames = std::get<0>(frames_fps);
const auto& fps = std::get<1>(frames_fps);
std::cout << " first frame width : " << frames.at(0).cols << " [px]\n"
<< " height: " << frames.at(0).rows << " [px]\n"
<< " fps : " << fps << " [fps]\n"
<< " frame count : " << frames.size() << " [#]\n"
<< " time : " << frames.size() / fps << " [sec]\n"
;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment