import trimesh
import numpy as np
import argparse
from stl import Mesh
def main(input_file, output_file, num, volume_info):
# 加载STL文件
your_mesh = trimesh.load_mesh(input_file)
# 分割成连通域
connected_components = your_mesh.split()
# 找到最大的num个连通域
largest_components = sorted(connected_components, key=lambda component: component.area, reverse=True)[:num]
# 计算所有连通域的面数总和
total_faces = sum([comp.faces.shape[0] for comp in largest_components])
# 创建一个足够大的mesh.Mesh对象来保存所有连通域
combined_mesh = Mesh(np.zeros(total_faces, dtype=Mesh.dtype))
# 当前在combined_mesh中的面的索引
current_face_index = 0
for largest_component in largest_components:
for i, f in enumerate(largest_component.faces):
for j in range(3):
combined_mesh.vectors[current_face_index + i][j] = largest_component.vertices[f[j], :]
current_face_index += largest_component.faces.shape[0]
# 添加元数据
combined_mesh.metadata = {'volume': volume_info}
# 保存所有连通域到一个新的STL文件
combined_mesh.save(output_file)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('input_file', type=str, help='The input STL file')
parser.add_argument('output_file', type=str, help='The output STL file')
parser.add_argument('num', type=int, help='The number of largest components to keep')
parser.add_argument('volume_info', type=str, help='Volume information to be added to the STL metadata')
args = parser.parse_args()
main(args.input_file, args.output_file, args.num, args.volume_info)
标签:STL,component,args,写入,python,mesh,file,largest
From: https://www.cnblogs.com/cupwym/p/18228331