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

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

相关推荐
jerryinwuhan9 小时前
python数据挖掘基础
python·数据挖掘·numpy
SugarFreeOixi1 天前
MATLAB绘图风格记录NP类型
python·matlab·numpy
小陈工2 天前
FastAPI性能优化实战:从每秒100请求到1000的踩坑记录
python·性能优化·django·flask·numpy·pandas·fastapi
REDcker2 天前
CentOS 与主流 Linux 发行版历史与版本综述
linux·centos·numpy
百年੭ ᐕ)੭*⁾⁾3 天前
DataFrame存入mysql以及读取操作
数据库·mysql·numpy·pandas·ipython
TheLegendMe5 天前
NumPy 矩阵操作 + 图像处理
图像处理·矩阵·numpy
李昊哲小课6 天前
NumPy轴方向统计在多维数据分析中的应用
python·数据分析·numpy
李昊哲小课6 天前
NumPy 完整学习笔记
笔记·python·学习·数据分析·numpy
好家伙VCC6 天前
**NumPy中的高效数值计算:从基础到进阶的实战指南**在现代数据科学与机器学习领域
java·python·机器学习·numpy
MediaTea7 天前
NumPy:ndarray 数组属性
numpy