1.安装库

pip install opencv-python pillow numpy

2.示例

import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont

# 配置:文字 + 视频参数
TEXT = "你好,这是自动生成的视频"
W, H = 800, 480  # 视频宽高
FPS = 30         # 帧率
DURATION = 3     # 视频时长(秒)

# 创建视频写入器
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter('text_video.mp4', fourcc, FPS, (W, H))

# 加载字体(无特殊字体用默认)
try:
    font = ImageFont.truetype("simhei.ttf", 60)
except:
    font = ImageFont.load_default(size=60)

# 生成每一帧
for _ in range(int(FPS * DURATION)):
    # 创建黑色背景
    img = Image.new('RGB', (W, H), 'black')
    draw = ImageDraw.Draw(img)
    
    # 文字居中
    text_bbox = draw.textbbox((0,0), TEXT, font=font)
    text_w = text_bbox[2] - text_bbox[0]
    text_h = text_bbox[3] - text_bbox[1]
    x, y = (W-text_w)//2, (H-text_h)//2
    
    # 画白色文字
    draw.text((x, y), TEXT, fill='white', font=font)
    
    # 转OpenCV格式并写入视频
    frame = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)
    out.write(frame)

# 保存视频
out.release()
print("视频已生成:text_video.mp4")