Use Python to combine multiple pictures into video

Today, I want to do a demonstration animation of quantum tunneling. I read a lot of articles from the big guys on CSDN, but I have been busy for nearly half a day to do this. Remember the pits you have stepped on, and this code is also worth recording, because you may encounter similar tasks in the future.
Code first`

import numpy as np
import cv2
#读取一张图片
size = (432,288)
print(size)
#完成写入对象的创建,第一个参数是合成之后的视频的名称,第二个参数是可以使用的编码器,第三个参数是帧率即每秒钟展示多少张图片,第四个参数是图片大小信息
videowrite = cv2.VideoWriter(r'F:\test.mp4',-1,20,size)#20是帧数,size是图片尺寸
img_array=[]
for filename in [r'F:\Picture\{0}.png'.format(i) for i in range(600)]:
    img = cv2.imread(filename)
    if img is None:
        print(filename + " is error!")
        continue
    img_array.append(img)
for i in range(600):
    videowrite.write(img_array[i])
print('end!')

The core idea of ​​the algorithm, everyone's code may be very different, but the idea is the same.
1. Use cv2.imread() to read the picture file
2. Use cv2.VideoWriter() to generate an object
3. Call the write method of this object to write the required picture into it, thus generating a video.
Several big holes :
1.

size = (432,288)#这边是图片的尺寸,图片的尺寸得是一样的,不一样的话有个博主编了一个resize函数可以去参考一下

2. The imread function cannot read the path with Chinese characters, it must be English characters
. 3. videowrite = cv2.VideoWriter(r'F:\test.mp4',-1,20,size)The path here seems to be in English too. I tried the path with Chinese but it didn’t work.

I named the picture 0~599.png
according to the above The code file generated the following video file
Insert picture description here

Guess you like

Origin blog.csdn.net/m0_46296922/article/details/109902075