How to get 4-character codec code for VideoCapture object in OpenCV?

Viewed 941

How do you retrieve the four-character codec code from a VideoCapture object in OpenCV 4? When I try to inspect it I get a float:

import cv2

movie_name = 'fubar.mp4'
movie = cv2.VideoCapture(movie_path)
codec_code =  movie.get(cv2.CAP_PROP_FOURCC)
print(codec_code)

This prints out something like 828601953.0. There are lots of threads about how to create a codec code, but I haven't found any on how to extract and read one out from an arbitrary VideoCapture object in Python.

I know the name of the file is informative (mp4) but that doesn't really specify the exact four-character encoding that I'm after (say, if I want to resave as a new movie after some processing, or just display the code to the user as metadata).

Related Thread
There is a thread on how to do this in C++ if anyone can translate to Python that would be the answer I suppose:
Qt or OpenCV: print out the codec of a video file

2 Answers

Try this:

hex(int(828601953.0))

prints:

'0x31637661'

Now do man ascii to get an ASCII table and look up the hex:

31 = 1
63 = c
76 = v
61 = a

So your FOURCC is avc1.

Not sure if there's a better way in Python, but this seems ok:

h = int(828601953.0)
chr(h&0xff) + chr((h>>8)&0xff) + chr((h>>16)&0xff) + chr((h>>24)&0xff) 

prints:

'avc1'
def get_fourcc(cap: cv2.VideoCapture):
    fourcc = int(cap.get(cv2.CAP_PROP_FOURCC))
    fourcc = bytes([
        v & 255 for v in (fourcc, fourcc >> 8, fourcc >> 16, fourcc >> 24)
    ]).decode()
    return fourcc

The answer is based on the LorenaGdL's answer on OpenCV Forum.

Related