一、简介
本文介绍了如何使用python
将.stl
格式的mesh转为.obj
格式的文件。
二、将stl转为obj
1. 使用PyMeshLab进行转换
a. 安装PyMeshLab
pip install pymeshlab
b. 将stl转换为obj
#!/usr/bin/env python3
import pymeshlab
def stl_to_obj(stl_file_path, obj_file_path):
# Create a new MeshSet
ms = pymeshlab.MeshSet()
# Load the STL file
ms.load_new_mesh(stl_file_path)
# Save the mesh as an OBJ file
# ms.save_current_mesh(obj_file_path, save_face_normals=True)
ms.save_current_mesh(obj_file_path)
print(f"Converted {stl_file_path} to {obj_file_path}")
# Example usage
stl_file_path = 'input.stl'
obj_file_path = 'output.obj'
stl_to_obj(stl_file_path, obj_file_path)
2. 使用aspose-3d进行转换
a. 安装 aspose-3d
pip install aspose-3d
b. 将stl转换为obj
import aspose.threed as a3d
stl_file_path = 'input.stl'
obj_file_path = 'output.obj'
scene = a3d.Scene.from_file(stl_file_path)
scene.save(obj_file_path)
3. 使用trimesh进行转换
a. 安装 trimesh
pip install numpy-stl trimesh
b. 将stl转换为obj
#!/usr/bin/env python3
import numpy as np
import trimesh
import trimesh.exchange.export
import trimesh.exchange.obj
from stl import mesh
def stl_to_obj(stl_file_path, obj_file_path):
# Load the STL file
stl_mesh = mesh.Mesh.from_file(stl_file_path)
# Extract vertices and faces
vertices = stl_mesh.vectors.reshape(-1, 3)
faces = np.arange(len(vertices)).reshape(-1, 3)
# Calculate normals if not present
stl_mesh.update_normals()
# Create a Trimesh object from the STL mesh
trimesh_mesh = trimesh.Trimesh(vertices=vertices, faces=faces, face_normals=stl_mesh.normals)
trimesh_mesh.export(obj_file_path, include_normals=True)
print(f"Converted {stl_file_path} to {obj_file_path}")
# Example usage
stl_file_path = 'input.stl'
obj_file_path = 'output.obj'
stl_to_obj(stl_file_path, obj_file_path)