This commit is contained in:
2026-04-13 16:32:30 +08:00
parent dad17dbadd
commit 1de35f21d7
14 changed files with 1081 additions and 63 deletions

View File

@@ -5,6 +5,70 @@ import sys
import os
def simplify_stl(input_path, output_path, keep_ratio=0.1):
try:
# Try using professional pymeshlab first
import pymeshlab
ms = pymeshlab.MeshSet()
ms.load_new_mesh(input_path)
target_faces = int(ms.current_mesh().face_number() * keep_ratio)
# Optimize using quadric edge collapse to preserve 95% visual effect
try:
ms.apply_filter('meshing_decimation_quadric_edge_collapse',
targetfacenum=target_faces,
preserveboundary=True,
preservenormal=True,
preservetopology=True)
except AttributeError:
ms.meshing_decimation_quadric_edge_collapse(
targetfacenum=target_faces,
preserveboundary=True,
preservenormal=True,
preservetopology=True
)
ms.save_current_mesh(output_path)
return True
except ImportError:
pass
except Exception as e:
print(f"Pymeshlab simplification failed: {e}. Falling back to Open3D...")
try:
# Try using open3d as second fallback
import open3d as o3d
o3d_mesh = o3d.io.read_triangle_mesh(input_path)
if len(o3d_mesh.triangles) > 0:
target_faces = max(1, int(len(o3d_mesh.triangles) * keep_ratio))
smp_mesh = o3d_mesh.simplify_quadric_decimation(target_number_of_triangles=target_faces)
smp_mesh.compute_triangle_normals()
o3d.io.write_triangle_mesh(output_path, smp_mesh)
return True
except ImportError:
pass
except Exception as e:
print(f"Open3D simplification failed: {e}. Falling back to PyFQMR...")
try:
# Try using pyfqmr as third fallback
import pyfqmr
import trimesh
mesh_data = trimesh.load(input_path, file_type='stl')
target_faces = max(1, int(len(mesh_data.faces) * keep_ratio))
simplifier = pyfqmr.Simplify()
simplifier.setMesh(mesh_data.vertices, mesh_data.faces)
simplifier.simplify_mesh(target_count=target_faces, aggressiveness=7, preserve_border=True, verbose=False)
mesh_parts = simplifier.getMesh()
smp_mesh = trimesh.Trimesh(vertices=mesh_parts[0], faces=mesh_parts[1], process=False)
smp_mesh.export(output_path, file_type='stl')
return True
except ImportError:
pass
except Exception as e:
print(f"PyFQMR simplification failed: {e}. Falling back to custom algorithm...")
try:
try:
import trimesh