mrgloom
mrgloom

Reputation: 21672

OpenCV: How to get list of available codecs?

How to get list of codecs available on current system, i.e. as I understand cv2.VideoWriter can fail when codec is not available. What codec is used by default?

Not sure if it's for all cases, but seems opencv fallback to mp4v codec as default with message: OpenCV: FFMPEG: fallback to use tag 0x7634706d/'mp4v'

Also to add new codecs do we need to rebuild opencv or we can just install additional codecs \ update ffmpeg via something like apt get?

Upvotes: 6

Views: 12792

Answers (2)

lubosz
lubosz

Reputation: 877

There is no way to actually enumerate available fourcc codecs in OpenCV.

This is quite unfortunate, since due to licensing issues OpenCV codec packaging differs between distributors. As can be seen here: OpenCV video writer unable to find codec or "avc1"

Using isOpened() on VideoWriter tells you if a encoder could be initialized successfully.

With a given list of fourcc codecs you can do something like this though:

import cv2
from pprint import pprint

def is_fourcc_available(codec):
    try:
        fourcc = cv2.VideoWriter_fourcc(*codec)
        temp_video = cv2.VideoWriter('temp.mkv', fourcc, 30, (640, 480), isColor=True)
        return temp_video.isOpened()
    except:
        return False

def enumerate_fourcc_codecs():
    codecs_to_test = ["DIVX", "XVID", "MJPG", "X264", "WMV1", "WMV2", "FMP4",
                      "mp4v", "avc1", "I420", "IYUV", "mpg1", "H264"]
    available_codecs = []
    for codec in codecs_to_test:
        available_codecs.append((codec, is_fourcc_available(codec)))
    return available_codecs

if __name__ == "__main__":
    codecs = enumerate_fourcc_codecs()
    print("Available FourCC codecs:")
    pprint(codecs)

An extensive list of existing, but probably mostly unsupported, fourccs can be retrieved from the link from the OpenCV docs: https://web.archive.org/web/20220316062600/http://www.fourcc.org/codecs.php

Upvotes: 3

Yunus Temurlenk
Yunus Temurlenk

Reputation: 4367

Here is the list of video codecs by FOURCC. You can get the char format there which you needed.

As the documentation says:

The constructors/functions initialize video writers. On Linux FFMPEG is used to write videos; on Windows FFMPEG or VFW is used; on MacOSX QTKit is used.

OpenCV uses FFMPEG supports(for linux in your case) to writes the videos so as @Mark Setchell mentioned on comment you can get the ffmpeg supported codec formats by the command:

ffmpeg -codecs

Upvotes: 1

Related Questions