生成黑白相间并且随机彩色块的视频

生成黑白相间并且随机彩色块的视频

from PIL import Image, ImageDraw
import numpy as np
from moviepy.editor import ImageSequenceClip

# 视频参数
width = 720
height = 540
fps = 60
duration_black = 2  # 全黑帧持续时间(s)
duration_white = 1  # 白色块帧持续时间(s)
block_size = 16

# 创建全黑帧
black_frame = Image.new('RGB', (width, height), 'black')

# 创建包含白色块和随机彩色块的帧
white_block_frame = black_frame.copy()
draw = ImageDraw.Draw(white_block_frame)
# 在中心添加白色块
center_x = width // 2
center_y = height // 2
draw.rectangle([center_x - block_size//2, center_y - block_size//2, 
                center_x + block_size//2, center_y + block_size//2], fill='white')

# 添加随机彩色块
num_color_blocks = 10  # 彩色块数量
for _ in range(num_color_blocks):
    random_x = np.random.randint(0, width - block_size)
    random_y = np.random.randint(0, height - block_size)
    color = tuple(np.random.randint(0, 256, size=(3,)))
    draw.rectangle([random_x, random_y, random_x + block_size, random_y + block_size], fill=color)

# 生成视频帧序列
frames = []

num_frames_black = int(duration_black * fps)
num_frames_white = int(duration_white * fps)

for _ in range(10):  # 循环生成多个序列
    # 添加全黑帧
    for _ in range(num_frames_black):
        frames.append(black_frame.copy())
    # 添加包含白色块和彩色块的帧
    for _ in range(num_frames_white):
        frames.append(white_block_frame.copy())

# 将帧序列转换为视频
clip = ImageSequenceClip([np.array(frame) for frame in frames], fps=fps)
clip.write_videofile("output_wb.mp4", codec="libx264")

print("视频生成完毕")
posted @ 2024-11-11 17:03  xswnb  阅读(2)  评论(0编辑  收藏  举报