I've got eveything working at last, but now, how to change codec of video

I need to change the codec of mp4’s created with cv2.VideoWriter.

I’ve found the list of codes here:

http://mp4ra.org/#/codecs

and I’m currently using mpv4. The issue is the very low bit rate, and I think the codec is incompatible with a lot of website. Is there any way to choose h.264? I can only see h.263

"avc1"

bitrate has NO RELATION to the specific codec. you can choose a bitrate.

VideoWriter has some ways to tell ffmpeg (opencv uses ffmpeg) what bitrate to use

opencv is for computer vision, not for transcoding video. use ffmpeg directly.

oh, I had a look at the available arguments for the VideoWriter regarding setting bitrate but couldn’t see any. I’ll have to retry.

Regarding using ffmpeg directly. What would that look like in the code? Currently I’m using:

        scaledvideo = cv.VideoWriter(destvideo, format, sourcefps, newresolution)        
        while True:
            ret, frame = sourcevideo.read()
            if ret == True:
                b = sr.upsample(frame)
                scaledvideo.write(b)
            else:
                break

Would it just be a case of pip installing ffmpeg-python and then replacing cv.VideoWriter with ffmpeg’s own videowriter you mean? Maybe something like:

scaledvideo = ffmpeg.output(stream, destvideo)

don’t bother with ffmpeg-python, python-ffmpeg, or ffmpeg packages on PyPI. the most developed/popular one of them appears abandoned, and it’s a lot of hacking around to harness an ffmpeg subprocess, which isn’t how any of this should be done (technically terrible, wasteful). the most recent one is just another amateur attempt to get fame (i.e. the “library” is excrement).

you could look at imageio. it does video too. Imageio Usage Examples — imageio 2.33.1 documentation

or use PyAV. that gives you proper bindings for ffmpeg, i.e. the entire power and flexibility of ffmpeg. available on PyPI. the github repo comes with examples for everything.

by that I meant there is some code in OpenCV that reads an environment variable (that you set in code) to gather up extra arguments for ffmpeg to pass along. AFAIK that’s undocumented or poorly documented.

basically… give imageio a look first.

1 Like

Oh wow. Thanks very much, this knowledge is golden. Thanks for sharing :+1: