python将png图片转换为gif、mp4

gif

pillow

1
2
3
4
5
6
7
8
9
from PIL import Image
import glob

pngs = glob.glob('temp_png/*.png')
# print(pngs)

frames = [Image.open(png) for png in pngs]

frames[0].save('z.gif', format='GIF', append_images=frames[1:], save_all=True, duration=100, loop=0)

mp4

opencv-python

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import glob
import cv2

pngs = glob.glob('temp_png/*.png')
# print(pngs)

frames = [cv2.imread(png) for png in pngs]

h, w, l = frames[0].shape
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video = cv2.VideoWriter(f'{pl}.mp4', fourcc, 15, (w, h))
for f in frames:
video.write(f)

cv2.destroyAllWindows()
video.release()