Python脚本批量将usdz文件转为glb文件
用于将 USDZ格式的3D模型文件批量转换为GLB格式 的Python脚本,使用Blender作为转换工具
主要功能
单个文件转换 (
convert_usdz_to_glb
函数):清空Blender场景。
导入指定的USDZ文件。
将导入的模型导出为GLB格式,不进行任何优化或缩放(保持原始数据)。
批量处理 (
batch_convert
函数):递归扫描输入目录中的所有
.usdz
文件。为每个USDZ文件生成对应的GLB文件路径(保持目录结构)。
调用单个文件转换函数,并统计成功/失败数量。
import bpy
import os
from pathlib import Pathdef convert_usdz_to_glb(input_path, output_path):"""单纯转换USDZ到GLB,不做任何优化和缩放"""try:# 清空场景bpy.ops.wm.read_factory_settings(use_empty=True)# 导入USDZbpy.ops.wm.usd_import(filepath=input_path,import_cameras=False,import_curves=False,import_lights=False)# 导出GLB(保持原始设置)bpy.ops.export_scene.gltf(filepath=output_path,export_format='GLB',export_yup=True,export_apply=False # 不应用变换)return Trueexcept Exception as e:print(f"转换失败 {input_path}: {str(e)}")return Falsedef batch_convert(input_dir, output_dir):"""批量转换(递归处理子目录)"""input_dir = Path(input_dir)output_dir = Path(output_dir)# 统计变量total_files = 0success_count = 0print(f"\n开始转换: {input_dir} -> {output_dir}")print("=" * 50)# 递归遍历所有子目录for usdz_file in input_dir.rglob("*.usdz"):# 计算相对路径以保持目录结构relative_path = usdz_file.relative_to(input_dir)glb_path = output_dir / relative_path.with_suffix('.glb')# 确保输出目录存在glb_path.parent.mkdir(parents=True, exist_ok=True)total_files += 1print(f"[{total_files}] 转换: {relative_path}", end=" => ")if convert_usdz_to_glb(str(usdz_file), str(glb_path)):print("✓")success_count += 1else:print("✕")# 打印报告print("\n" + "=" * 50)print(f"转换完成!")print(f"扫描到USDZ文件: {total_files}个")print(f"成功转换: {success_count}个")print(f"失败: {total_files - success_count}个")print("=" * 50)if __name__ == "__main__":# 配置路径(根据实际情况修改)input_folder = "/Users/changchun/Downloads/usdz"output_folder = "/Users/changchun/Downloads/usdz_to_glb"# 验证路径if not Path(input_folder).exists():print(f"错误:输入目录不存在 - {input_folder}")exit(1)# 执行转换batch_convert(input_folder, output_folder)