Python saves h264 format video (linux and windows)

1. Problem analysis

  1. When performing target detection, target tracking or other tasks on video, sometimes it is necessary to save a series of output image results as a video. In order to facilitate the front-end page display, the encoding format of the video is also required to be h264 format .
  2. The common method is to use opencv, but opencv cannot be directly saved as a video in h264 format.

To this end, here are several methods that can be successfully saved as h264 encoded video.

Two, the method of using opencv under windows

  1. Download the dll dynamic library file of openh264, and put it in the same path as your program, so that you can successfully save the video in h264 encoding format.
    Download address: https://github.com/cisco/openh264/releases
  • Download page:
    insert image description here
  1. the code
# coding=utf-8
import cv2
import os

save_name = 'output.mp4'
fourcc = cv2.VideoWriter_fourcc(*'h264')
fps = 25
width = 1920
height = 1080
out = cv2.VideoWriter(save_name, fourcc, fps, (width, height))

img_dir = 'your_img_dir'
files = [os.path.join(img_dir, f) for f in os.listdir(img_dir)]
for file in files:
    img = cv2.imread(file)
    out.write(img)
out.release()


3. The method of using opencv under Linux

You need to recompile opencv yourself, which is more troublesome, just give up. (Life is short, hhh)

4. Common method for Windows and Linux (recommended)

Using the imageio library, the imageio version used for the test is 2.19.3. Note that ffmpeg must be installed first.
(The python library of imageio-ffmpeg may also be required, the version used for testing is 0.4.5)

Go directly to the code:

# coding=utf-8
import os
from tqdm import tqdm
import imageio.v2 as iio

output_file = 'output.mp4'

img_dir = r'your_img_dir'
files = [os.path.join(img_dir, f) for f in os.listdir(img_dir)]


out = iio.get_writer(output_file, format='ffmpeg', mode='I', fps=25, codec='libx264', pixelformat='yuv420p')
for file in tqdm(files):
    frame = iio.imread(file)  # RGB format array
    out.append_data(frame)
out.close()

Finish.

Guess you like

Origin blog.csdn.net/weixin_43508499/article/details/125495758