如何用Python提取*.obj文件中的三维模型特征
论文涉及三维模型特征提取,之前一直在研究 Python 的一些库,希望从中找到方法,但是由于本人经验和能力有限一直没有突破,在这里求助各位如果有这方面的经验或者建议请给我些许指点,万分感谢。
如何用Python提取*.obj文件中的三维模型特征
1 回复
要提取OBJ文件的三维模型特征,得先解析文件格式。OBJ文件是文本格式,包含顶点坐标、纹理坐标、法线向量和面索引。
我用trimesh库来处理,这个库专门处理三维网格数据,比手动解析方便多了:
import trimesh
import numpy as np
def extract_obj_features(obj_file_path):
# 加载OBJ文件
mesh = trimesh.load(obj_file_path)
features = {}
# 1. 顶点特征
vertices = mesh.vertices # 顶点坐标 (n, 3)
features['vertex_count'] = len(vertices)
features['vertex_mean'] = np.mean(vertices, axis=0)
features['vertex_std'] = np.std(vertices, axis=0)
features['bounding_box'] = mesh.bounds # 包围盒
# 2. 面特征
faces = mesh.faces # 面索引 (m, 3)
features['face_count'] = len(faces)
# 3. 几何特征
features['volume'] = mesh.volume
features['surface_area'] = mesh.area
features['center_mass'] = mesh.center_mass
# 4. 拓扑特征
features['euler_characteristic'] = mesh.euler_number
features['is_watertight'] = mesh.is_watertight
features['is_convex'] = mesh.is_convex
# 5. 形状描述符
# 主成分分析获取方向
from sklearn.decomposition import PCA
pca = PCA(n_components=3)
pca.fit(vertices)
features['pca_components'] = pca.components_
features['pca_explained_variance'] = pca.explained_variance_ratio_
# 6. 曲率特征(简化版)
# 计算顶点法线
vertex_normals = mesh.vertex_normals
features['vertex_normals_mean'] = np.mean(vertex_normals, axis=0)
return features
# 使用示例
if __name__ == "__main__":
features = extract_obj_features("model.obj")
# 打印特征
for key, value in features.items():
if isinstance(value, np.ndarray):
print(f"{key}: shape={value.shape}")
else:
print(f"{key}: {value}")
如果你没有trimesh,先安装:pip install trimesh
这个函数提取了六类特征:
- 顶点统计:顶点数量、均值、标准差和包围盒
- 面信息:三角形面的数量
- 几何属性:体积、表面积和质心
- 拓扑特征:欧拉示性数、是否封闭、是否凸体
- 形状方向:通过PCA获取模型的主方向
- 曲率相关:顶点法线统计
对于更高级的特征,比如局部曲率、形状直径函数或光描述符,需要更复杂的算法。不过上面这些基础特征对于大多数分类、检索任务已经够用了。
简单说就是:用trimesh库解析OBJ,然后计算各种几何和拓扑属性作为特征。

