如何在 Python 中优化 3D 模型

如何在 Python 中优化 3D 模型

问题

大型 3D 模型文件可能加载和传输缓慢。在 Python 中使用 Aspose.3D 时,您可以采取实用步骤来减小文件大小并删除不必要的场景数据;主要通过导出为紧凑的二进制格式并修剪场景图中未使用的节点。.

先决条件

  • Python 3.7 或更高版本
  • aspose-3d-foss 通过…安装的包 pip install aspose-3d-foss
  • 一个 3D 输入文件(OBJ、STL、FBX、glTF 或 3MF)

优化技术

转换为紧凑的二进制格式

减少文件大小的最有效方法之一是将场景导出为 glTF 二进制(.glb)。GLB 格式将几何体和材质打包到单个二进制文件中,与 OBJ 或 ASCII FBX 等基于文本的格式相比,体积显著更小,加载速度更快。.

from aspose.threed import Scene, FileFormat

scene = Scene.from_file("model.obj")
scene.save("model.glb", FileFormat.GLTF2_BINARY)

检查并统计网格

在处理之前,了解场景中包含多少网格节点是有帮助的。这有助于识别出意外庞大或复杂的场景。.

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

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

mesh_count = 0
for node in scene.root_node.child_nodes:
    if isinstance(node.entity, Mesh):
        mesh_count += 1
        print(f"  Mesh '{node.name}': {len(node.entity.control_points)} vertices, "
              f"{node.entity.polygon_count} polygons")

print(f"Total meshes: {mesh_count}")

移除未使用(已排除)的节点

标记为排除的节点不会被渲染。在导出时识别并跳过这些节点可以减小场景占用。该 excluded attribute 是某对象的属性 Entity,,而不是方法调用。.

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

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

active_nodes = []
for node in scene.root_node.child_nodes:
    entity = node.entity
    if entity is not None and not entity.excluded:
        active_nodes.append(node.name)

print(f"Active (non-excluded) nodes: {active_nodes}")

代码示例

此示例加载场景,报告网格统计信息,并保存为紧凑的 GLB 格式:这是通过 Aspose.3D 可获得的主要实用优化。.

from aspose.threed import Scene, FileFormat
from aspose.threed.entities import Mesh

# Load the input model
scene = Scene.from_file("input.obj")

# Inspect mesh count and vertex totals
total_vertices = 0
for node in scene.root_node.child_nodes:
    if isinstance(node.entity, Mesh):
        mesh = node.entity
        total_vertices += len(mesh.control_points)

print(f"Total vertices before export: {total_vertices}")

# Save to compact binary GLB: smaller and faster to load than OBJ
scene.save("output.glb", FileFormat.GLTF2_BINARY)
print("Saved as GLB (binary glTF)")

关于优化范围的说明

Aspose.3D 不提供网格简化或多边形减少算法。文件大小的缩减主要通过以下方式实现::

  • 导出为二进制格式(GLB 而非 OBJ 或 ASCII FBX)
  • 在您自己的处理逻辑中跳过被排除的或空的节点

关于具体百分比的加速或内存减少的声明取决于您的输入数据,通常无法保证。.

另见

 中文