Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save video in opencv with H264 codec

I am using opencv-python==4.5.1.48 and python3.9 docker. I want to save a video in h264 format. Here is my function to save a video:

import cv2

def save_video(frames):
    fps = 30
    video_path = '/home/save_test.mp4'
    fourcc = cv2.VideoWriter_fourcc(*'h264')
    video_writer = cv2.VideoWriter(video_path, fourcc, fps, (112, 112))

    for frame in frames:
        video_writer.write(frame)

    video_writer.release()

When I use .mp4 format to save video, I get the following error:

OpenCV: FFMPEG: tag 0x34363268/'h264' is not supported with codec id 27 and format 'mp4 / MP4 (MPEG-4 Part 14)' OpenCV: FFMPEG: fallback to use tag 0x31637661/'avc1' Could not find encoder for codec id 27: Encoder not found

I search and read some solutions but none of them solve my issue.

Update:

I also install libx264-dev which was recommended in this post and did not work.

like image 348
Mohammadreza Riahi Avatar asked Jan 17 '26 21:01

Mohammadreza Riahi


1 Answers

Below is my solution on ubuntu20.04:

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

refer

like image 193
Tombon Avatar answered Jan 19 '26 19:01

Tombon