Python快速三维建模神器:trimesh
安装和试用
trimesh是 Python 中用于加载、处理、分析和渲染三维网格数据的开源库。它支持常见的三维模型格式,并提供丰富的几何计算、网格操作和可视化功能,常用于三维重建、机器人、计算机视觉、CAD、3D 打印、仿真等场景。
pip install trimesh -i https://pypi.tuna.tsinghua.edu.cn/simple
安装完成后,可以先画一个立方体,如图所示

代码如下
import trimesh
box = trimesh.creation.box(extents=[1, 1, 1])
box.visual.face_colors = [0, 255, 0, 128]
box.show()
box.export('box.stl')
四行代码,依次是创建立方体、设置立方体的颜色、弹出绘图窗口、将三维模型存储为stl格式。
几何对象
trimesh的creation模块支持从零开始生成3D网格模型,提供了一些基本几何体。大部分几何体在创建时都有transform参数,用于指定几何体的位姿,其实质上是一个 4 × 4 4\times4 4×4矩阵,左上角的 3 × 3 3\times3 3×3是旋转矩阵,第四列是 [ d x , d y , d z , 1 ] T [d_x, d_y, d_z, 1]^T [dx,dy,dz,1]T,下表中,支持transform参数的用🔄标记。
| 函数 | 对象 | 关键参数 | 说明 |
|---|---|---|---|
| box | 长方体🔄 | extents, bounds | |
| cylinder | 圆柱体🔄 | radius, height, sections, segments | |
| cone | 圆锥体🔄 | radius, height, sections | |
| icosahedron | 正二十面体 | ||
| uv_sphere | UV球 | polygon, triangle_args, engine, force_vertices | |
| icosphere | 正二十面体球 | subdivisions, radius | |
| torus | 圆环🔄 | major_radius, minor_radius, major_sections, minor_sections | |
| capsule | 胶囊🔄 | height, radius, count | |
| random_soup | 随机三角形碎片 | ||
| annulus | 环形汽缸🔄 | r_min, r_max, height, sections, segment | |
| axis | 坐标系指示器🔄 | origin_size, origin_color, axis_radius, axis_length | |
| camera_marker | 相机标记 |
这些几何体形状如下

绘图代码为
import numpy as np
import trimesh
import trimesh.creation as tc
# camera_marker 需要传入一个 Camera 对象
cam = trimesh.scene.Camera(resolution=(100, 100), fov=(60, 60))
shapeDct = {
"box": tc.box(extents=[1, 1, 1]),
"cylinder": tc.cylinder(radius=0.5, height=1),
"cone": tc.cone(radius=0.5, height=1),
"icosahedron": tc.icosahedron(),
"uv_sphere": tc.uv_sphere(radius=0.5),
"icosphere": tc.icosphere(radius=0.5, subdivisions=2),
"torus": tc.torus(major_radius=0.5, minor_radius=0.2),
"capsule": tc.capsule(radius=0.3, height=1),
"random_soup": tc.random_soup(),
"annulus": tc.annulus(r_min=0.3, r_max=0.5, height=0.5),
"axis": tc.axis(axis_length=0.5),
"camera_marker": tc.camera_marker(cam)[1],
}
scene = trimesh.Scene()
cols = 4 # 每行 4 个
spacing = 1.5 # 对象之间的间距
for i,key in enumerate(shapeDct):
print(key)
geom = shapeDct[key]
row, col = divmod(i, cols)
x, y = col * spacing, -row * spacing # 计算当前对象的平移位置
geom.apply_translation([x, y, 0]) # 应用平移并添加到主场景
scene.add_geometry(geom)
scene.show()
DAMO开发者矩阵,由阿里巴巴达摩院和中国互联网协会联合发起,致力于探讨最前沿的技术趋势与应用成果,搭建高质量的交流与分享平台,推动技术创新与产业应用链接,围绕“人工智能与新型计算”构建开放共享的开发者生态。
更多推荐



所有评论(0)