opencv-python converts image sequence to video

After the tracking result is saved as a picture, sometimes you want to convert the picture sequence into a video for demonstration, or even make a animated picture and insert it into the blog, so here is the script you use for subsequent access:
my cv2 version is 4.1 .0

img2video.py

import os
import cv2

# image path
im_dir = '/home/lsm/PycharmProjects/py-MDNet/results/Biker/figs'
# output video path
video_dir = '/home/lsm/PycharmProjects/py-MDNet/demo'
if not os.path.exists(video_dir):
    os.makedirs(video_dir)
# set saved fps
fps = 20
# get frames list
frames = sorted(os.listdir(im_dir))
# w,h of image
img = cv2.imread(os.path.join(im_dir, frames[0]))
img_size = (img.shape[1], img.shape[0])
# get seq name
seq_name = os.path.dirname(im_dir).split('/')[-1]
# splice video_dir
video_dir = os.path.join(video_dir, seq_name + '.avi')
fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
# also can write like:fourcc = cv2.VideoWriter_fourcc(*'MJPG')
# if want to write .mp4 file, use 'MP4V'
videowriter = cv2.VideoWriter(video_dir, fourcc, fps, img_size)

for frame in frames:
    f_path = os.path.join(im_dir, frame)
    image = cv2.imread(f_path)
    videowriter.write(image)
    print(frame + " has been written!")

videowriter.release()
  • First specify the image sequence path: such as mine /home/lsm/PycharmProjects/py-MDNet/results/Biker/figs, as shown in the following figure:
    Insert picture description here
  • Then specify the output path
  • Then you can set the number of frames of the video FPS, and the resolution of the video (the default is the resolution of the picture), the name of the video can be modified by yourself (the above is saved as the name of the sequence Biker )
  • Then read in a frame of pictures to write the video, and then you can generate an .avi video file:
    Insert picture description here
    you can use the online online conversion tool to generate a gif file in the future.

Put an example of the official website :
Official website example

Guess you like

Origin blog.csdn.net/laizi_laizi/article/details/107653757