You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python的Trimesh保存带球形孔洞3D模型的截面?

将Trimesh截面保存为numpy数组或图像的方法

一、渲染为图像并保存(含numpy数组)

通过Trimesh的场景渲染功能,把2D截面直接转为像素图像或numpy数组:

import trimesh
import numpy as np
from PIL import Image

# 你的原有截面获取代码
slice = tm_build.section(plane_origin=tm_build.centroid, plane_normal=[0,1,0])
slice_2D, to_3D = slice.to_planar()

# 创建场景并添加2D截面
scene = trimesh.Scene()
scene.add_geometry(slice_2D)

# 渲染得到RGBA格式的numpy数组(shape为(高度, 宽度, 4))
img_array = scene.render(resolution=[1024, 1024], background=[255,255,255,255])

# 保存为PNG图像
img = Image.fromarray(img_array)
img.save("section_output.png")

# 直接保存numpy数组
np.save("section_array.npy", img_array)

二、提取截面轮廓坐标为numpy数组

如果需要的是截面的矢量坐标而非像素图像,可以提取路径的顶点数据:

import numpy as np

# 遍历截面的所有路径实体,提取顶点
section_vertices = []
for entity in slice_2D.entities:
    # 处理直线段
    if isinstance(entity, trimesh.path.entities.Line):
        section_vertices.append(slice_2D.vertices[entity.points])
    # 处理圆弧(可通过num_points调整拟合精度)
    elif isinstance(entity, trimesh.path.entities.Arc):
        arc_points = entity.discrete(slice_2D.vertices, num_points=100)
        section_vertices.append(arc_points)

# 转换为统一的numpy数组
section_coords = np.vstack(section_vertices)
np.save("section_coords.npy", section_coords)

注意事项

  • 渲染时可通过调整resolution参数控制图像清晰度,数值越大细节越丰富
  • 背景色可通过background修改,设置[0,0,0,0]可得到透明背景图像
  • 若截面包含其他类型路径(如贝塞尔曲线),需对应添加trimesh.path.entities.Curve的处理逻辑

内容的提问来源于stack exchange,提问作者sonido

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 22:01:26