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()

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

相关推荐
云烟成雨TD3 天前
NumPy 2.x 完全指南【四十二】线性代数之向量运算
python·机器学习·numpy
做科研的周师兄3 天前
【机器学习入门】9.2:感知机 Python 实践代码模板(苹果香蕉分类任务适配)
人工智能·python·学习·机器学习·分类·数据挖掘·numpy
全栈探索者3 天前
numpy基础
python·数据分析·numpy
代码AI弗森6 天前
Python × NumPy」 vs 「JavaScript × TensorFlow.js」生态全景图
javascript·python·numpy
犽戾武7 天前
1. 简单回顾Numpy神经网络
人工智能·神经网络·numpy
懒惰蜗牛8 天前
Day10:Python实现Excel自动汇总
python·numpy·pandas·pip·1024程序员节·python读写excel
Kratzdisteln13 天前
【Python】绘制椭圆眼睛跟随鼠标交互算法配图详解
python·数学·numpy·pillow·matplotlib·仿射变换
MoRanzhi120313 天前
Pillow 基础图像操作与数据预处理
图像处理·python·深度学习·机器学习·numpy·pillow·数据预处理
Geoking.15 天前
NumPy zeros() 函数详解
python·numpy