Skip to content

Instantly share code, notes, and snippets.

@itsrifat
Last active July 13, 2023 18:48
Show Gist options
  • Save itsrifat/66b253db2736b23f247c to your computer and use it in GitHub Desktop.
Save itsrifat/66b253db2736b23f247c to your computer and use it in GitHub Desktop.
simple c++ functions to extract frames of a video file into a vector of Mat and saving the vector as jpg images using OpenCV 2.4.9
/*
This functions opens a video file and extracts the frames and put them into a vector of Mat(its the class for representing an img)
*/
void extract_frames(const string &videoFilePath,vector<Mat>& frames){
try{
//open the video file
VideoCapture cap(videoFilePath); // open the video file
if(!cap.isOpened()) // check if we succeeded
CV_Error(CV_StsError, "Can not open Video file");
//cap.get(CV_CAP_PROP_FRAME_COUNT) contains the number of frames in the video;
for(int frameNum = 0; frameNum < cap.get(CV_CAP_PROP_FRAME_COUNT);frameNum++)
{
Mat frame;
cap >> frame; // get the next frame from video
frames.push_back(frame);
}
}
catch( cv::Exception& e ){
cerr << e.msg << endl;
exit(1);
}
}
/*
It saves a vector of frames into jpg images into the outputDir as 1.jpg,2.jpg etc where 1,2 etc represents the frame number
*/
void save_frames(vector<Mat>& frames, const string& outputDir){
vector<int> compression_params;
compression_params.push_back(CV_IMWRITE_JPEG_QUALITY);
compression_params.push_back(100);
for(std::vector<Mat>::iterator frame = frames.begin(),frameNumber=0; frame != frame.end(); ++frame){
string filePath = outputDir + to_string(static_cast<long long>(frameNumber))+ ".jpg";
imwrite(filePath,*frame,compression_params);
}
}
@itsrifat
Copy link
Author

itsrifat commented Nov 7, 2014

to call the function:

//to extract
vector<Mat> frames;
extract_frames("C:\\myvideo.mp4",frames);
//to save
save_frames(frames, "c\\myvideo_frames\\")

@IvanPizhenko
Copy link

what do I need to #include to get this working?

@futurestark
Copy link

OpenCV library header files to see imwrite method and others, like #include "opencv2/core.hpp"
#include "opencv2/video.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/videoio.hpp"
#include "opencv2/highgui.hpp" and STL containers like vector #include

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment