Python基于OpenCV制作视频:如何一行代码批量读取10张图片
批量读取图片生成视频的优化方案
你可以借助glob模块批量匹配指定格式的图片文件,再通过列表推导式一行生成files_and_duration列表,避免手动逐个输入文件名。
修改后的完整代码
import cv2 import glob frame_per_second = 1 # 一行代码批量获取排序后的图片文件,并生成时长均为1的列表 files_and_duration = [(file, 1) for file in sorted(glob.glob("*.png"), key=lambda x: int(x.split('.')[0]))] w, h = None, None for file, duration in files_and_duration: frame = cv2.imread(file) if w is None: h, w, _ = frame.shape fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') writer = cv2.VideoWriter('output1.mp4', fourcc, frame_per_second, (w, h)) for repeat in range(duration * frame_per_second): writer.write(frame) writer.release()
关键说明
glob.glob("*.png")会匹配当前目录下所有.png格式的文件sorted(..., key=lambda x: int(x.split('.')[0]))确保文件名按数字顺序排列(避免出现10.png排在1.png前面的情况)- 列表推导式直接将每个文件名和固定时长1组成元组,生成目标列表
内容的提问来源于stack exchange,提问作者user19862793
相关产品推荐
相关产品推荐

