如何从python中不断出现的图像中不断更新视频?

2024-06-17 15:48:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在从事一个机器人技术项目,在该项目中,机器人连续创建.pgm格式的图像(而不是相机图像),我将其转换为.jpeg并保存到一个目录中。然而,当我想在视频中连续转换这些图像时,随着越来越多的图像被添加,这个目录会不断更新。我已经可以从一个实例中保存的图像创建视频,但我想要的是在图像不断保存的同时,将视频作为单个文件(流式传输到URL)不断更新。这是我的代码,但它不能同时用于图像和视频。有人能帮忙吗

from PIL import Image import os, glob import cv2 import numpy as np from os.path import isfile, join # remove .yaml files directory = "/home/user/catkin_ws/src/ros_map/map_pgms" files_in_directory = os.listdir(directory) filtered_files = [file for file in files_in_directory if file.endswith(".yaml")] for file in filtered_files: path_to_file = os.path.join(directory, file) os.remove(path_to_file) def batch_image(in_dir, out_dir): if not os.path.exists(out_dir): print(out_dir, 'is not existed.') os.mkdir(out_dir) if not os.path.exists(in_dir): print(in_dir, 'is not existed.') return -1 count = 0 for files in glob.glob(in_dir + '/*'): filepath, filename = os.path.split(files) out_file = filename[0:9] + '.jpg' # print(filepath,',',filename, ',', out_file) im = Image.open(files) new_path = os.path.join(out_dir, out_file) print(count, ',', new_path) count = count + 1 im.save(os.path.join(out_dir, out_file)) if __name__ == '__main__': batch_image('/home/user/catkin_ws/src/ros_map/map_pgms', './batch') # convert the .jpgs to video img_array = [] for filename in glob.glob('./batch/*.jpg'): img = cv2.imread(filename) height, width, layers = img.shape size = (width, height) img_array.append(img) out = cv2.VideoWriter('project.avi', cv2.VideoWriter_fourcc(*'DIVX'), 15, size) for i in range(len(img_array)): out.write(img_array[i]) out.release()