Skip to content

Instantly share code, notes, and snippets.

@yjxiong
Last active June 5, 2020 12:07
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yjxiong/b899d7ab30a55564d847178ab0ffd5d5 to your computer and use it in GitHub Desktop.
Save yjxiong/b899d7ab30a55564d847178ab0ffd5d5 to your computer and use it in GitHub Desktop.

To use OpenCV's VideoWriter class to write an H264 encoded video, one would encounter some error like

Could not open codec libx264: unspecified error

Here is the trick. Beforehand, one has to make sure

  • --enable-libx264 is switched on in ffmpeg
  • OpenCV is downloaded in sources.

Then make following changes to modules/highgui/src/cap_ffmpeg_impl.hpp:

    ...
    c->bit_rate = (int)lbit_rate;

    /************** modifications to enable x264 writer ************************/
    c->me_range = 16;
    c->max_qdiff = 4;
    c->qmin = 1;
    c->qmax = 30;
    c->qcompress = 0.9;
    c->qcompress = 0.6;
    /************** end of modificaiton ****************************************/
  

    /* open the codec */
    if ((err=
#if LIBAVCODEC_VERSION_INT >= ((53<<16)+(8<<8)+0)
         avcodec_open2(c, codec, NULL)
#else
         avcodec_open(c, codec)
#endif
         ) < 0) {
        fprintf(stderr, "Could not open codec '%s': %s", codec->name, icvFFMPEGErrStr(err));
        return false;
    }

Compile OpenCV, then you will be able to use the VideoWriter with FOURCC H264.

@techsin
Copy link

techsin commented Jun 5, 2019

can you show how it can be accomplished with https://github.com/justadudewhohacks/opencv4nodejs

@yjxiong
Copy link
Author

yjxiong commented Jun 5, 2019

@techsin

TBH I don't know how to do it.

@techsin
Copy link

techsin commented Jun 5, 2019

thanks i got it working by simply placing file in the main directory of project

@yjxiong
Copy link
Author

yjxiong commented Jun 5, 2019

cool.

@CrossLee1
Copy link

what's your ffmpeg version and opencv version

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment