How to Record Videos Using OpenCV

In this post I am going to share a very simple but crucial parts of my QRecorder program which is recording images into videos. At the time of writing this article, Qt doesn’t allow recording of video files and OpenCV with its multi-platform support seems to be the best solution.

I’m assuming that you know how to add required OpenCV libraries and includes to your Qt project, but if you don’t, you can search this website for keywords like libraries and includes and it will show up 🙂

OK,  so let’s start. You can use VideoWriter class in OpenCV to write and save videos from any sources. Define it like this:

cv::VideoWriter video;


Next, you have to open this video file (for writing) to start recording frames into it. Note that the first parameter is the output video file name. Second one is FourCC, third is the video Frame Rate Per Second and last parameter is the video size.

video.open("c:/videos/output.avi", CV_FOURCC('M', 'J', 'P', 'G'), 15, cv::Size(320, 240));

You can check if OpenCV was able to successfully open a video file using the function below:

video.isOpened()

Now you can start recording any images into this video file. Please note that this function uses cv::Mat images but if you want to record QImage or other Qt image formats you should first check out this article to see how you can convert them to cv::Mat first:

video.write(frame);

Note that frame variable is a cv::Mat.

Lastly you have to release (means close) the Video Writer like this:

video.release();


5 Replies to “How to Record Videos Using OpenCV”

  1. Hi dear interesting post, but i dont understand this, the “video.open(“c:/videos/output.avi”,” create the file if dont exist? because i dont have a video in my directory i just want to create a new one, but i everytime get “video.isOpened()=false”
    . Best regards

  2. Hi dear interesting post, but i dont understand this, the create the file if dont exist? because i dont have a video in my directory i just want to create a new one, but i everytime get . Best regards

    1. This functions should all work out-of-the-box and quite easily. Check if you have MJPG codec. The only thing I would advice you to change is CV_FOURCC(‘M’, ‘J’, ‘P’, ‘G’). You can use any existing codec on your Mac.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.