import trimesh
import numpy as np
from sklearn.cluster import DBSCAN
# 加载OBJ文件
mesh = trimesh.load_mesh(r'C:\Users\a\Desktop\file_60digree\motobike.obj')
# 使用DBSCAN聚类法向量
clustering = DBSCAN(eps=0.001, min_samples=2).fit(mesh.face_normals)
# 计算每个平面的总面积
areas = [np.sum(mesh.area_faces[clustering.labels_ == i]) for i in range(max(clustering.labels_) + 1)]
# 确定最大平面法向量
largest_plane_id = np.argmax(areas)
largest_plane_normal = np.mean(mesh.face_normals[clustering.labels_ == largest_plane_id], axis=0)
# 归一化最大法向量
largest_plane_normal = largest_plane_normal / np.linalg.norm(largest_plane_normal)
# 计算最大平面法向量与y轴之间的角度
rotation_angle_y = np.arccos(np.dot(largest_plane_normal, [0, 1, 0]) / np.linalg.norm(largest_plane_normal))
# 如果最大平面的法线的y分量小于0,将旋转角度加上π
if largest_plane_normal[1] < 0:
rotation_angle_y += np.pi
# 计算旋转轴
rotation_axis = np.cross(largest_plane_normal, [0, 1, 0])
# 应用旋转角度到所有顶点
rotation_matrix_y = trimesh.transformations.rotation_matrix(rotation_angle_y, rotation_axis)
mesh.apply_transform(rotation_matrix_y)
# 将最大平面涂成红色
mesh.visual.face_colors[clustering.labels_ == largest_plane_id] = [255, 0, 0, 255]
# 保存旋转后的OBJ文件
mesh.export(r'C:\Users\a\Desktop\rotated.obj')
obj文件调整最大面至底面
最新推荐文章于 2025-04-28 21:11:34 发布