webm_creator.py
1.52 KB
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
42
43
44
45
46
47
48
49
50
import av
import numpy as np
from PIL import Image
import os
def png_to_webm_with_alpha(input_folder, output_file, fps=12):
# 获取所有PNG文件并按名称排序
png_files = sorted([f for f in os.listdir(input_folder) if f.endswith('.png')])
if not png_files:
raise ValueError("No PNG files found in the input folder")
first_image = Image.open(os.path.join(input_folder, png_files[0]))
width, height = first_image.size
# 创建输出容器和视频流
container = av.open(output_file, mode='w')
stream = container.add_stream('libvpx-vp9', rate=fps)
stream.pix_fmt = 'yuva420p'
stream.width = width
stream.height = height
# 设置编码器参数
stream.options = {
'quality': 'good',
'crf': '35',
'auto-alt-ref': '0',
}
for png_file in png_files:
image_path = os.path.join(input_folder, png_file)
image = Image.open(image_path).convert('RGBA')
frame_data = np.array(image)
# 创建AVFrame并填充数据
frame = av.VideoFrame.from_ndarray(frame_data, format='rgba')
# 编码并写入
for packet in stream.encode(frame):
container.mux(packet)
# 刷新编码器(修复此处:传入 None 表示结束)
for packet in stream.encode(None): # <-- 更安全的刷新方式
container.mux(packet)
container.close()
if __name__ == "__main__":
input_folder = "pngs"
output_file = "output.webm"
png_to_webm_with_alpha(input_folder, output_file, fps=12)