import cv2
import os
from natsort import natsorted  # 自然排序，确保图片按数字顺序排列


def images_to_video(image_folder, output_video_path, fps=30):
    # 获取图片文件列表，支持常见图片格式
    valid_exts = ('.png', '.jpg', '.jpeg', '.bmp', '.tiff')
    images = [img for img in os.listdir(image_folder) if img.lower().endswith(valid_exts)]

    # 按自然排序对图片进行排序
    images = natsorted(images)

    if not images:
        print("文件夹中没有找到图片")
        return

    # 读取第一张图片，获取宽高信息
    first_image_path = os.path.join(image_folder, images[0])
    frame = cv2.imread(first_image_path)
    if frame is None:
        print(f"无法读取图片 {first_image_path}")
        return
    height, width, channels = frame.shape

    # 定义视频编码，得到视频写入对象
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')  # mp4格式编码
    video_writer = cv2.VideoWriter(output_video_path, fourcc, fps, (width, height))

    for image_name in images:
        image_path = os.path.join(image_folder, image_name)
        frame = cv2.imread(image_path)
        if frame is None:
            print(f"忽略无法读取的图片 {image_path}")
            continue
        # 确保所有图片大小一致，如果你不确定，可以resize
        if (frame.shape[1], frame.shape[0]) != (width, height):
            frame = cv2.resize(frame, (width, height))
        video_writer.write(frame)

    video_writer.release()
    print(f"视频生成完毕: {output_video_path}")


if __name__ == "__main__":
    image_folder = "/home/sig/qianluo/3DGS_VLN_Benchmark/Capture/Videos/Capture1_frames"
    output_video_path = "/home/sig/qianluo/3DGS_VLN_Benchmark/Capture/Videos/output_video1.mp4"
    images_to_video(image_folder, output_video_path, fps=6)