I’ve always knew that OpenCV can be used to do some video editing, however when I’ve actually tried to use it to open a video file, a few weeks ago, I was amazed at the quantity of misleading or incomplete tutorials you find on the web. I wrote this tutorial to save some time for others like me that need to do some quick and dirty video editing with C++ and OpenCV.
Simplest thing that you could try is to read frames from your computer’s webcam. OpenCV uses the same function, VideoCapture, for opening a video file or a camera attached to your computer, the only difference is that for a camera you will feed the function a number, while for an actual video file you will use the video path.
If your computer has a camera attached to it, you can access it with the next piece of code (use the escape key to close the program):
Now, if you want to save the feed from your camera to a video file, you need use the VideoWriter function, that has the next signature:
from which the second parameter, fourcc - 4-character code of codec used to compress the frames, is the most problematic. Basically, you need to know what video codec is provided by your operating system or what codec you have installed. On OS X, for example, I was able to use the MP4V codec to encode videos. The catch was that you need to write the codec four character code in lower cases if you want to actually save the video. Same codec can be used on Windows.
We can modify the above example in order to save the camera feed in a file, see lines 17, 18, 21 and 35 for the important differences between the original and the modified code:
For reading a local video file we’ll use the same syntax, e.g.:
Now, that we can read and write video files, let’s try something more ambitious - modifying an existing video. For the purpose of this tutorial we’ll use an open video like Big Buck Bunny, also we are going to ignore the audio.
When we read a video with OpenCV, we have access to each frame and we can apply any of the typical image processing operations provided by the library to this frame, after that we can save the modified video. Let’s try an experiment: split each frame in three, equal area, vertical rectangles, we leave the left rectangle untouched, we convert to gray the middle rectangle and we apply a Canny edge detector to the right rectangle. Finally, if we copy the modified middle and right rectangles back to the original image, this is what we get:
Please note that the original video used to generate the video included above is (c) copyright 2008, Blender Foundation www.bigbuckbunny.org.
Here is the code I’ve used to obtain the above video:
If you want to learn more about OpenCV I would recommend reading OpenCV Essentials by O. D. Suarez: