1 Creating a video with OpenCV {#tutorial_video_write}
2 ============================
4 @prev_tutorial{tutorial_video_input_psnr_ssim}
5 @next_tutorial{tutorial_kinect_openni}
10 Whenever you work with video feeds you may eventually want to save your image processing result in a
11 form of a new video file. For simple video outputs you can use the OpenCV built-in @ref cv::VideoWriter
12 class, designed for this.
14 - How to create a video file with OpenCV
15 - What type of video files you can create with OpenCV
16 - How to extract a given color channel from a video
18 As a simple demonstration I'll just extract one of the BGR color channels of an input video file
19 into a new video. You can control the flow of the application from its console line arguments:
21 - The first argument points to the video file to work on
22 - The second argument may be one of the characters: R G B. This will specify which of the channels
24 - The last argument is the character Y (Yes) or N (No). If this is no, the codec used for the
25 input video file will be the same as for the output. Otherwise, a window will pop up and allow
26 you to select yourself the codec to use.
28 For example, a valid command line would look like:
30 video-write.exe video/Megamind.avi R Y
35 You may also find the source code and these video file in the
36 `samples/cpp/tutorial_code/videoio/video-write/` folder of the OpenCV source library or [download it
37 from here ](https://github.com/opencv/opencv/tree/master/samples/cpp/tutorial_code/videoio/video-write/video-write.cpp).
39 @include cpp/tutorial_code/videoio/video-write/video-write.cpp
41 The structure of a video
42 ------------------------
44 For start, you should have an idea of just how a video file looks. Every video file in itself is a
45 container. The type of the container is expressed in the files extension (for example *avi*, *mov*
46 or *mkv*). This contains multiple elements like: video feeds, audio feeds or other tracks (like for
47 example subtitles). How these feeds are stored is determined by the codec used for each one of them.
48 In case of the audio tracks commonly used codecs are *mp3* or *aac*. For the video files the list is
49 somehow longer and includes names such as *XVID*, *DIVX*, *H264* or *LAGS* (*Lagarith Lossless
50 Codec*). The full list of codecs you may use on a system depends on just what one you have
53 ![](images/videoFileStructure.png)
55 As you can see things can get really complicated with videos. However, OpenCV is mainly a computer
56 vision library, not a video stream, codec and write one. Therefore, the developers tried to keep
57 this part as simple as possible. Due to this OpenCV for video containers supports only the *avi*
58 extension, its first version. A direct limitation of this is that you cannot save a video file
59 larger than 2 GB. Furthermore you can only create and expand a single video track inside the
60 container. No audio or other track editing support here. Nevertheless, any video codec present on
61 your system might work. If you encounter some of these limitations you will need to look into more
62 specialized video writing libraries such as *FFMpeg* or codecs as *HuffYUV*, *CorePNG* and *LCL*. As
63 an alternative, create the video track with OpenCV and expand it with sound tracks or convert it to
64 other formats by using video manipulation programs such as *VirtualDub* or *AviSynth*.
67 -----------------------
69 The content written here builds on the assumption you
70 already read the @ref tutorial_video_input_psnr_ssim tutorial and you know how to read video files. To create a
71 video file you just need to create an instance of the @ref cv::VideoWriter class. You can specify
72 its properties either via parameters in the constructor or later on via the @ref cv::VideoWriter::open function.
73 Either way, the parameters are the same: 1. The name of the output that contains the container type
74 in its extension. At the moment only *avi* is supported. We construct this from the input file, add
75 to this the name of the channel to use, and finish it off with the container extension.
77 const string source = argv[1]; // the source file name
78 string::size_type pAt = source.find_last_of('.'); // Find extension point
79 const string NAME = source.substr(0, pAt) + argv[2][0] + ".avi"; // Form the new name with container
81 -# The codec to use for the video track. Now all the video codecs have a unique short name of
82 maximum four characters. Hence, the *XVID*, *DIVX* or *H264* names. This is called a four
83 character code. You may also ask this from an input video by using its *get* function. Because
84 the *get* function is a general function it always returns double values. A double value is
85 stored on 64 bits. Four characters are four bytes, meaning 32 bits. These four characters are
86 coded in the lower 32 bits of the *double*. A simple way to throw away the upper 32 bits would
87 be to just convert this value to *int*:
89 VideoCapture inputVideo(source); // Open input
90 int ex = static_cast<int>(inputVideo.get(CAP_PROP_FOURCC)); // Get Codec Type- Int form
92 OpenCV internally works with this integer type and expect this as its second parameter. Now to
93 convert from the integer form to string we may use two methods: a bitwise operator and a union
94 method. The first one extracting from an int the characters looks like (an "and" operation, some
95 shifting and adding a 0 at the end to close the string):
97 char EXT[] = {ex & 0XFF , (ex & 0XFF00) >> 8,(ex & 0XFF0000) >> 16,(ex & 0XFF000000) >> 24, 0};
99 You can do the same thing with the *union* as:
101 union { int v; char c[5];} uEx ;
102 uEx.v = ex; // From Int to char via union
105 The advantage of this is that the conversion is done automatically after assigning, while for
106 the bitwise operator you need to do the operations whenever you change the codec type. In case
107 you know the codecs four character code beforehand, you can use the *CV_FOURCC* macro to build
110 CV_FOURCC('P','I','M,'1') // this is an MPEG1 codec from the characters to integer
112 If you pass for this argument minus one then a window will pop up at runtime that contains all
113 the codec installed on your system and ask you to select the one to use:
115 ![](images/videoCompressSelect.png)
117 -# The frame per second for the output video. Again, here I keep the input videos frame per second
118 by using the *get* function.
119 -# The size of the frames for the output video. Here too I keep the input videos frame size per
120 second by using the *get* function.
121 -# The final argument is an optional one. By default is true and says that the output will be a
122 colorful one (so for write you will send three channel images). To create a gray scale video
123 pass a false parameter here.
125 Here it is, how I use it in the sample:
127 VideoWriter outputVideo;
128 Size S = Size((int) inputVideo.get(CAP_PROP_FRAME_WIDTH), //Acquire input size
129 (int) inputVideo.get(CAP_PROP_FRAME_HEIGHT));
130 outputVideo.open(NAME , ex, inputVideo.get(CAP_PROP_FPS),S, true);
132 Afterwards, you use the @ref cv::VideoWriter::isOpened() function to find out if the open operation succeeded or
133 not. The video file automatically closes when the *VideoWriter* object is destroyed. After you open
134 the object with success you can send the frames of the video in a sequential order by using the
135 @ref cv::VideoWriter::write function of the class. Alternatively, you can use its overloaded operator \<\< :
137 outputVideo.write(res); //or
140 Extracting a color channel from an BGR image means to set to zero the BGR values of the other
141 channels. You can either do this with image scanning operations or by using the split and merge
142 operations. You first split the channels up into different images, set the other channels to zero
143 images of the same size and type and finally merge them back:
145 split(src, spl); // process - extract only the correct channel
146 for( int i =0; i < 3; ++i)
148 spl[i] = Mat::zeros(S, spl[0].type());
151 Put all this together and you'll get the upper source code, whose runtime result will show something
154 ![](images/resultOutputWideoWrite.png)
156 You may observe a runtime instance of this on the [YouTube
157 here](https://www.youtube.com/watch?v=jpBwHxsl1_0).
159 @youtube{jpBwHxsl1_0}