介绍

3D content rarely stays in a single format for its entire lifetime. A model may originate as an OBJ file exported from a modelling application, travel through a 3D printing pipeline as STL, appear in a web application as glTF, and end up in an additive manufacturing tool as 3MF. Each format serves a different audience and a different downstream tool, and conversion between them is something most 3D pipelines need to handle reliably.

Python 非常适合这项工作:Shell 脚本太脆弱,完整的 DCC(数字内容创作)工具集成对批处理来说又过于笨重。你需要的是一个库,能够加载这些格式中的任意一种,提供一致的场景图,并在不依赖 GUI 或显卡驱动的情况下写出任意目标格式。.

Aspose.用于Python的3D自由开源软件 (aspose-3d-foss, MIT license) 弥补了这一空白。本指南展示了最常见的转换路径,并提供完整、可运行的代码示例。.


Aspose.3D FOSS 支持哪些格式??

格式Extension(s)加载保存常见用例
Wavefront OBJ.obj来自建模工具的互换;; .mtl 支持材质文件
STL.stl3D printing, CAD export; binary and ASCII variants
glTF 2.0 / GLB.gltf, .glbWeb 查看器、游戏引擎;GLB 是自包含的二进制变体
COLLADA.dae从动画工具导入;; ColladaSaveOptions 支持导出
3MF.3mf增材制造,提供比 STL 更丰富的打印元数据

格式检测会根据文件扩展名自动完成。特定格式的选项类(ObjLoadOptions, StlSaveOptions, GltfSaveOptions)在需要细粒度控制时可用。.

关于 FBX 的说明:: 该库包含一个用于导入的部分 FBX 标记器。此版本不建议在生产转换工作流中使用 FBX;请改用 OBJ 或 glTF 作为中间格式。.


OBJ 转 STL:为 3D 打印准备模型

OBJ 是建模和雕刻工具最常见的输出格式。STL 是 3D 打印切片软件的通用语言。两者之间的转换只需一次调用即可完成。.

from aspose.threed import Scene
from aspose.threed.formats import StlSaveOptions

scene = Scene.from_file("model.obj")

opts = StlSaveOptions()
scene.save("model.stl", opts)

STL 仅编码三角形面。如果你的 OBJ 文件包含四边形或 n 边形面,导出器会在写入前自动对其进行三角化。如果你想在保存前显式控制三角化,请调用 mesh.triangulate() 对场景中的每个网格调用::

from aspose.threed import Scene
from aspose.threed.entities import Mesh
from aspose.threed.formats import StlSaveOptions

scene = Scene.from_file("model.obj")

def triangulate_all(node):
    for entity in list(node.entities):
        if isinstance(entity, Mesh):
            tri_mesh = entity.triangulate()
            # Attach the triangulated mesh via add_entity
            node.add_entity(tri_mesh)
    for child in node.child_nodes:
        triangulate_all(child)

triangulate_all(scene.root_node)
scene.save("model_triangulated.stl", StlSaveOptions())

OBJ 转 glTF:面向网页和游戏引擎的导出

glTF 2.0 是实时渲染器、WebGL 查看器以及 Babylon.js、Three.js、Unity 等游戏引擎首选的互换格式。GLB(二进制变体)将几何体、纹理和材质打包成单个自包含文件,便于通过 HTTP 进行分发。.

from aspose.threed import Scene
from aspose.threed.formats import GltfSaveOptions

scene = Scene.from_file("model.obj")

##Save as JSON-based glTF (external buffer)
opts_gltf = GltfSaveOptions()
scene.save("model.gltf", opts_gltf)

##Save as self-contained GLB binary: preferred for web delivery
scene.save("model.glb", GltfSaveOptions())

格式会根据文件扩展名推断:: .gltf 生成 JSON 与二进制缓冲区的配对;; .glb 生成单文件二进制。OBJ 材质数据(LambertMaterial, PhongMaterial)会传递到 glTF PBR 材质表示中(如果存在等价的)。.


STL 转 glTF:从扫描仪或 CAD 输出到网页

来自3D扫描仪和CAD系统的STL文件是常见的输入,需要转换为可在网页上查看。STL仅包含三角形几何信息且没有材质数据,因此转换过程相当直接。.

from aspose.threed import Scene
from aspose.threed.formats import GltfSaveOptions

scene = Scene.from_file("scan.stl")
scene.save("scan.glb", GltfSaveOptions())

如果STL是由使用非标准坐标系(Z向上 vs Y向上)的CAD工具生成的,您可以在保存之前检查并纠正根节点的变换::

from aspose.threed import Scene
from aspose.threed.formats import GltfSaveOptions

scene = Scene.from_file("cad_export.stl")

##Rotate 90 degrees around X to convert Z-up to Y-up
root = scene.root_node
root.transform.set_euler_angles(-90.0, 0.0, 0.0)

scene.save("cad_export_yup.glb", GltfSaveOptions())

glTF 转 3MF:为增材制造做准备

3MF is a modern 3D printing format backed by the 3MF Consortium. It supports richer metadata than STL (colour, material assignments, build instructions) and is accepted by slicer software such as PrusaSlicer and Bambu Studio. If you are delivering models from a web viewer into a printing workflow, converting GLB to 3MF is a useful step.

from aspose.threed import Scene
from aspose.threed import FileFormat
from aspose.threed.formats import SaveOptions

scene = Scene.from_file("model.glb")
scene.save("model.3mf")

3MF 格式会自动从 .3mf 扩展名检测。若需显式控制,请传入一个 SaveOptions 实例已配置为 3MF。.


批量转换

在实际使用中,转换任务通常针对文件目录而非单个文件。下面的模式处理一个 OBJ 文件夹,将其中每个文件转换为 GLB,并对每个文件进行错误处理,避免单个错误文件导致整个运行中止。.

import os
from aspose.threed import Scene
from aspose.threed.formats import GltfSaveOptions

input_dir = "./obj_files"
output_dir = "./glb_files"

os.makedirs(output_dir, exist_ok=True)

opts = GltfSaveOptions()
results = {"ok": [], "failed": []}

for filename in os.listdir(input_dir):
    if not filename.lower().endswith(".obj"):
        continue
    src = os.path.join(input_dir, filename)
    stem = os.path.splitext(filename)[0]
    dst = os.path.join(output_dir, stem + ".glb")
    try:
        scene = Scene.from_file(src)
        scene.save(dst, opts)
        results["ok"].append(filename)
        print(f"OK  {filename} -> {stem}.glb")
    except Exception as exc:
        results["failed"].append((filename, str(exc)))
        print(f"ERR {filename}: {exc}")

print(f"\n{len(results['ok'])} converted, {len(results['failed'])} failed.")
if results["failed"]:
    for name, reason in results["failed"]:
        print(f"  {name}: {reason}")

此模式自然地扩展到其他源/目标格式对:更改扩展名过滤器和 SaveOptions 类,以适配上表中任意组合。.


结论

Aspose.3D FOSS for Python 使格式转换变得简单:使用 Scene.from_file,,可选地检查或修改场景图,然后使用适当的 SaveOptions.。该库在内部处理三角化、坐标归一化以及特定格式的细节。.

欲获取完整的类和方法列表,请参阅 API 参考.。若想深入了解场景图模型(节点、网格、变换),请参阅::