2024-08-02 17:06:32 +08:00
|
|
|
import cv2
|
|
|
|
import os
|
|
|
|
from tqdm import tqdm
|
|
|
|
|
2024-08-02 21:10:28 +08:00
|
|
|
def create_video_from_images(image_folder, output_video_path, frame_rate=25):
|
|
|
|
# define valid extension
|
2024-08-02 17:06:32 +08:00
|
|
|
valid_extensions = [".jpg", ".jpeg", ".JPG", ".JPEG"]
|
|
|
|
|
2024-08-02 21:10:28 +08:00
|
|
|
# get all image files in the folder
|
2024-08-02 17:06:32 +08:00
|
|
|
image_files = [f for f in os.listdir(image_folder)
|
|
|
|
if os.path.splitext(f)[1] in valid_extensions]
|
2024-08-02 21:10:28 +08:00
|
|
|
image_files.sort() # sort the files in alphabetical order
|
2024-08-02 17:06:32 +08:00
|
|
|
print(image_files)
|
|
|
|
if not image_files:
|
|
|
|
raise ValueError("No valid image files found in the specified folder.")
|
|
|
|
|
2024-08-02 21:10:28 +08:00
|
|
|
# load the first image to get the dimensions of the video
|
2024-08-02 17:06:32 +08:00
|
|
|
first_image_path = os.path.join(image_folder, image_files[0])
|
|
|
|
first_image = cv2.imread(first_image_path)
|
|
|
|
height, width, _ = first_image.shape
|
|
|
|
|
2024-08-02 21:10:28 +08:00
|
|
|
# create a video writer
|
|
|
|
fourcc = cv2.VideoWriter_fourcc(*'mp4v') # codec for saving the video
|
2024-08-02 17:06:32 +08:00
|
|
|
video_writer = cv2.VideoWriter(output_video_path, fourcc, frame_rate, (width, height))
|
|
|
|
|
2024-08-02 21:10:28 +08:00
|
|
|
# write each image to the video
|
2024-08-02 17:06:32 +08:00
|
|
|
for image_file in tqdm(image_files):
|
|
|
|
image_path = os.path.join(image_folder, image_file)
|
|
|
|
image = cv2.imread(image_path)
|
|
|
|
video_writer.write(image)
|
|
|
|
|
2024-08-02 21:10:28 +08:00
|
|
|
# source release
|
2024-08-02 17:06:32 +08:00
|
|
|
video_writer.release()
|
|
|
|
print(f"Video saved at {output_video_path}")
|
|
|
|
|