trimesh库初步接触

背景

最近做了一个很有意思的需求,有这样一个游戏场景,有一个隧道模型(glb),模型是根据我们做的坐标系来建造的,还有一批隧道内的设施模型,比如隧道内的一些设施,都要加载到同一个坐标系地图内,但是这批设备位置不太对,举个例子,本该在隧道壁上的物体跑到了隧道上方,这个时候就需要调整,一个两个或许可以但是数量多了,就需要通过脚本批量处理

代码

python 复制代码
import trimesh
import numpy as np

# 加载隧道模型,file_path是模型路径
mesh = trimesh.load(file_path, force="mesh")
# 包装点np.array,这里的点是本该在隧道内的物体的点
point_xyz_np = np.array((point_xyz[0], point_xyz[1], point_xyz[2]))
# 射线方向,例如:向z轴正方向
ray_direction = np.array([0, 0, 1])  
# 求从隧道内物体发出的射线和模型的交点
locations, _, _ = mesh.ray.intersects_location([point_xyz_np], [ray_direction])

我用的trimesh的版本是4.0.2

可视化

说实话,光这样说,很抽象,我们能不能看到呢,就是让隧道和隧道内的物体点位可视化,有的兄弟,有的,可以用pyvista 库来做到,但是我要说一下,这个库加载模型很慢,不如用blender

python 复制代码
import pyvista as pv

def add_vertical_ray(plotter, start_point, ray_length=5.0, ray_color='blue', ray_width=3):
    """
    在点的Z轴正方向添加射线
    
    参数:
    - plotter: PyVista绘图器
    - start_point: 起始点坐标 [x, y, z]
    - ray_length: 射线长度
    - ray_color: 射线颜色
    - ray_width: 射线宽度
    """
    
    # 计算射线终点
    end_point = start_point + [0, 0, ray_length]
    
    # 创建线段
    line = pv.Line(start_point, end_point)
    
    # 添加线段到场景
    plotter.add_mesh(line, color=ray_color, line_width=ray_width, label='Vertical Ray')
    
    return line

# 物体点位
point_xyz_np = np.array((point_xyz[0], point_xyz[1], point_xyz[2]))

if point_xyz_np.ndim == 1:
    # 单个点,需要reshape为(1, 3)
    point_xyz_np = point_xyz_np.reshape(1, 3)

# 检查点坐标的维度
if point_xyz_np.shape[1] != 3:
    raise ValueError(f"点坐标应该是3维的,但得到的是 {point_xyz_np.shape[1]} 维")

plotter = pv.Plotter()
# file_path是隧道glb
mesh = pv.read(file_path)

point_colors='red'
    point_size=10
    plotter.add_mesh(mesh, color='lightgray', show_edges=True)
    point_cloud = pv.PolyData(point_xyz_np)
    plotter.add_mesh(point_cloud, color=point_colors, point_size=point_size, 
                    render_points_as_spheres=True)

# 添加点
for i, point in enumerate(point_xyz_np):
    plotter.add_point_labels([point], [f'Point {i}'], font_size=16, 
       text_color='black', shape_color=point_colors)

add_vertical_ray(plotter,[point_xyz[0], point_xyz[1], point_xyz[2]])
plotter.add_axes()
plotter.show_grid()
plotter.set_background('white')
    
print("显示可视化界面...")
plotter.show()

我写的原代码包含部分敏感内容,不能放出来,这里只记录思路哦

相关推荐
brave and determined1 天前
CANN教程:NPU原生NumPy接口asnumpy详解引言
numpy
啊阿狸不会拉杆1 天前
《机器学习导论》第 5 章-多元方法
人工智能·python·算法·机器学习·numpy·matplotlib·多元方法
铁手飞鹰2 天前
[深度学习]常用的库与操作
人工智能·pytorch·python·深度学习·numpy·scikit-learn·matplotlib
啊阿狸不会拉杆2 天前
《机器学习导论》第3章 -贝叶斯决策理论
人工智能·python·算法·机器学习·numpy·深度优先·贝叶斯决策理论
林深现海3 天前
【刘二大人】PyTorch深度学习实践笔记 —— 第四集:反向传播(凝练版)
pytorch·python·numpy
断眉的派大星3 天前
NumPy库完全解析(从基础到进阶,附实战示例)
numpy
啊阿狸不会拉杆3 天前
《机器学习导论》第 1 章 - 引言
人工智能·python·算法·机器学习·ai·numpy·matplotlib
Dfreedom.3 天前
详解四大格式(PIL/OpenCV/NumPy/PyTorch)的转换原理与场景选择
图像处理·人工智能·pytorch·opencv·numpy·pillow
不懒不懒3 天前
【机器学习:下采样 VS 过采样——逻辑回归在信用卡欺诈检测中的实践】
python·numpy·scikit-learn·matplotlib·pip·futurewarning
小白开始进步4 天前
JAKA Zu12 机械臂运动学算法深度解析(含可视化方案)
python·算法·numpy