Use H264 codec with cv2.VideoWriter.

MLBoy
2 min readJan 2, 2024

--

mp4v cannot be played in a browser.

When writing a video using cv2.VideoWriter, if you use mp4v as the codec, the written video cannot be played in the browser 🥺

cv2.VideoWriter_fourcc(*'mp4v') # we can't play this on the browser.

It is necessary to use an h264 codec that can be played in a browser .

h264 cannot be used with OpenCV installed with pip.

So, I would like to use H264, but if I set H264 as shown below, OpenCV with pip install cannot use H264, so I can’t write 🥺🥺

cv2.VideoWriter_fourcc(*'avc1') # we can't write

Solution

Therefore, instead of using pip, install OpenCV using the following method.

pip uninstall opencv-python
sudo apt install build-essential cmake git python3-dev python3-numpy \
libavcodec-dev libavformat-dev libswscale-dev \
libgstreamer-plugins-base1.0-dev \
libgstreamer1.0-dev libgtk-3-dev \
libpng-dev libjpeg-dev libopenexr-dev libtiff-dev libwebp-dev \
libopencv-dev x264 libx264-dev libssl-dev ffmpeg
python -m pip install --no-binary opencv-python opencv-python

I was able to export it successfully in h264.
colab environment.

🐣

I’m a freelance engineer.
Work consultation
Please feel free to contact us with a brief development description.
rockyshikoku@gmail.com

I am creating applications using machine learning and AR technology.

I send machine learning / AR related information.

GitHub

Twitter
Medium

--

--

MLBoy
MLBoy

No responses yet