How to Record Videos Using OpenCV

Posted on Posted in OpenCV Tutorials, Qt Tutorials, Tutorials

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.“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:


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:


Note that frame variable is a cv::Mat.

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


2 thoughts on “How to Record Videos Using OpenCV

    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 *