agrobot_base/Python/mesh_simplify/ply_to_obj_simplify.py

45 lines
1.5 KiB
Python
Raw Permalink Normal View History

2024-08-13 16:28:41 +00:00
import open3d as o3d
import os
def load_ply(file_path):
"""Carrega um arquivo PLY usando open3d."""
mesh = o3d.io.read_triangle_mesh(file_path)
return mesh
def simplify_mesh(mesh, reduction_factor=0.5):
"""Reduz o número de triângulos da malha."""
target_number_of_triangles = int(len(mesh.triangles) * reduction_factor)
simplified_mesh = mesh.simplify_quadric_decimation(target_number_of_triangles)
return simplified_mesh
def save_obj_with_mtl(mesh, obj_path, mtl_path):
"""Salva a malha em formato OBJ com MTL."""
# Salvar o arquivo OBJ
o3d.io.write_triangle_mesh(obj_path, mesh)
# Gerar o arquivo MTL
with open(mtl_path, 'w') as mtl_file:
mtl_file.write("newmtl material_0\n")
mtl_file.write("Ka 1.000 1.000 1.000\n")
mtl_file.write("Kd 0.800 0.800 0.800\n")
mtl_file.write("Ks 0.000 0.000 0.000\n")
mtl_file.write("d 1.0\n")
mtl_file.write("illum 2\n")
def convert_ply_to_obj(ply_path, obj_path, reduction_factor=0.5):
"""Converte PLY para OBJ com redução de triângulos e gera arquivo MTL."""
mesh = load_ply(ply_path)
simplified_mesh = simplify_mesh(mesh, reduction_factor)
# Definir o caminho do arquivo MTL
mtl_path = os.path.splitext(obj_path)[0] + ".mtl"
# Salvar o OBJ e o MTL
save_obj_with_mtl(simplified_mesh, obj_path, mtl_path)
# Caminhos dos arquivos
ply_file = 'montagem_pulverizador.ply'
obj_file = 'montagem_pulverizador_0.03.obj'
# Converter e simplificar
convert_ply_to_obj(ply_file, obj_file, reduction_factor=0.03)