In OpenCV 3 we use CV_FOURCC to identify codec , for example:
writer.open("image.jpg", CV_FOURCC('M', 'J', 'P', 'G'), fps, size);
In this line of code, we name the storage target file of cv::VideoWriter writer image.jpg, use the codec of MJPG (here MJPG is the abbreviation of motion jpeg), and enter the corresponding number of frames per second and the video lens size.
Unfortunately, in OpenCV 4 (4.5.4-dev) in, CV_FOURCC VideoWriter has been replaced by a function of the fourcc. If we continue to use the macro CV_FOURCC, an error will be reported when compiling:
error: ‘CV_ FOURCC’ was not declared in this scope
Here is a simple usage of FourCC in opencv4:
writer.open("image.jpg", cv::VideoWriter::fourcc('M', 'J', 'P', 'G'), fps, size);
In order to better show fourcc standard usage, and how the video is stored in OpenCV 4, below we give a complete example of how to store video:
1 #include <opencv2/core.hpp>
2 #include <opencv2/videoio.hpp>
3 #include <opencv2/highgui.hpp>
4 #include <iostream>
5 #include <stdio.h>
6 using namespace cv;
7 using namespace std;
8 int main(int, char**)
9 {
10 Mat src;
11 // use default camera as video source
12 VideoCapture cap(0);
13 // check if we succeeded
14 if (!cap.isOpened()) {
15 cerr << "ERROR! Unable to open camera\n";
16 return -1;
17 }
18 // get one frame from camera to know frame size and type
19 cap >> src;
20 // check if we succeeded
21 if (src.empty()) {
22 cerr << "ERROR! blank frame grabbed\n";
23 return -1;
24 }
25 bool isColor = (src.type() == CV_8UC3);
26 //--- INITIALIZE VIDEOWRITER
27 VideoWriter writer;
28 int codec = VideoWriter::fourcc('M', 'J', 'P', 'G'); // select desired codec (must be available at runtime)
29 double fps = 25.0; // framerate of the created video stream
30 string filename = "./live.avi"; // name of the output video file
31 writer.open(filename, codec, fps, src.size(), isColor);
32 // check if we succeeded
33 if (!writer.isOpened()) {
34 cerr << "Could not open the output video file for write\n";
35 return -1;
36 }
37 //--- GRAB AND WRITE LOOP
38 cout << "Writing videofile: " << filename << endl
39 << "Press any key to terminate" << endl;
40 for (;;)
41 {
42 // check if we succeeded
43 if (!cap.read(src)) {
44 cerr << "ERROR! blank frame grabbed\n";
45 break;
46 }
47 // encode the frame into the videofile stream
48 writer.write(src);
49 // show live and wait for a key with timeout long enough to show images
50 imshow("Live", src);
51 if (waitKey(5) >= 0)
52 break;
53 }
54 // the videofile will be closed and released automatically in VideoWriter destructor
55 return 0;
56 }