Coding-图片转视频

将图片转成视频

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import cv2
import os
import glob
from PIL import Image
import re
def natural_sort_key(s):
return [int(text) if text.isdigit() else text.lower() for text in re.split('([0-9]+)', s)]
def images_to_video(image_folder, output_video_path, fps=30):
"""
Converts a folder of images into a video.

Parameters:
image_folder (str): Path to the folder containing the images.
output_video_path (str): Path to the output video file.
fps (int, optional): Frames per second for the output video. Default is 30.
"""
# Get the list of all images in the folder sorted by name
image_list = sorted(glob.glob(os.path.join(image_folder, '*.png')),key=natural_sort_key)

# Read the first image to get dimensions
img = cv2.imread(image_list[0])
height, width, layers = img.shape

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # You can use 'XVID' or other codecs depending on your needs
video = cv2.VideoWriter(output_video_path, fourcc, fps, (width, height))

# Write each image to the video
for image_path in image_list:
img = cv2.imread(image_path)
video.write(img)

# Release everything if job is finished
video.release()

print("Video created successfully at: ", output_video_path)

# Example usage
image_folder = 'grid'
output_video_path = 'test_save.mp4'
images_to_video(image_folder, output_video_path, fps=30)