平时会用到的小工具,读取文件夹内所有的png图像文件,并合成视频和gif动图。
直接上代码:
import numpy as np
import cv2
import os
import imageio
src_path = r'D:\fooling_around\stylegan2-pytorch-master\sample'
sav_path = r'D:\fooling_around\stylegan2-pytorch-master'
image_files = [file for file in os.listdir(src_path) if file.endswith('.png')]
frame_width = 500
frame_height = 500
frame_rate = 20
video = cv2.VideoWriter(os.path.join(sav_path, 'output.mp4'), cv2.VideoWriter_fourcc(*'mp4v'), frame_rate, (frame_width, frame_height))
images = []
for image_file in image_files:
image_path = os.path.join(src_path, image_file)
image = cv2.imread(image_path)
image = cv2.resize(image, (frame_width, frame_height))
video.write(image) # 保存为视频
images.append(image) # 保存为gif动图
cv2.imshow('Video', image)
cv2.waitKey(1)
cv2.destroyAllWindows()
video.release()
output_path = os.path.join(sav_path, 'output.gif')
imageio.mimsave(output_path, images, fps=frame_rate)