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

如何在PyVista交互式网格拾取中维持多选中区域的可见高亮

问题描述

使用PyVista开发交互式STL查看器,支持选择网格上的多个区域。当前代码能实现选择功能,但新选中区域时,之前的选中区域会从视觉上消失——选中数据已在后台正确存储(已通过保存文件验证),但可视化仅显示最新选中区域。需要实现所有选中区域在持续选择时,均保持各自颜色的可见高亮。

解决方案

核心问题在于每次选中时,你将所有已选中单元格的标量值都设为1,且使用仅包含两种颜色的色图,同时每次都重新添加网格覆盖原有显示。要实现多颜色高亮,需要给每个选中的单元格分配唯一的标量值,对应色图中的不同颜色,并且更新现有网格的标量数据而非重新添加。

修改后的代码如下:

import pyvista as pv
import numpy as np

mesh = pv.read('tumor.stl')
plotter = pv.Plotter()

colors = [[1,0,0], [0,1,0], [0,0,1], [1,1,0], [1,0,1]]
# 初始化选中单元格的标量数组,0表示未选中
mesh.cell_data["selection_scalars"] = np.zeros(mesh.n_cells, dtype=int)
selected = []

def pick_cell(cell_id):
    global selected
    if cell_id is not None and cell_id not in selected:
        # 给当前选中单元格分配唯一的标量值(从1开始)
        scalar_value = len(selected) + 1
        mesh.cell_data["selection_scalars"][cell_id] = scalar_value
        selected.append(cell_id)
        
        # 更新现有网格的显示,使用自定义色图:未选中为浅灰,选中的用colors列表中的颜色
        cmap = ['lightgray'] + colors
        plotter.update_scalars(mesh.cell_data["selection_scalars"], mesh="main_mesh", cmap=cmap)
        
        print(f"Selected triangle {cell_id}")

def save_selection():
    # 保存选中的三角形索引
    with open('selected_triangles.txt', 'w') as f:
        for cell_id in selected:
            f.write(f"{cell_id}\n")
    print(f"已保存{len(selected)}个三角形到selected_triangles.txt")

# 初始化绘图:添加网格并绑定选择标量
plotter.add_mesh(mesh, scalars="selection_scalars", cmap=['lightgray'] + colors, 
                 show_scalar_bar=True, name="main_mesh")
plotter.add_text("点击三角形进行选择\n按'S'保存", position='lower_left')

# 启用交互功能
plotter.enable_cell_picking(callback=pick_cell, through=False)
plotter.add_key_event("s", save_selection)

# 启动查看器
plotter.show()

# 关闭后的提示
print(f"最终选中了{len(selected)}个三角形")

关键修改点

  • 初始化selection_scalars数组,给每个选中单元格分配唯一的标量值(1、2、3……),而非统一设为1
  • 使用plotter.update_scalars()更新现有网格的标量数据,避免重新添加网格覆盖原有显示
  • 色图cmap包含未选中状态的浅灰色,加上所有选中区域用的颜色,确保每个选中区域对应不同颜色
  • 添加重复选中判断,避免同一单元格被多次选中

内容的提问来源于stack exchange,提问作者Martina Arnau Niñerola

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 02:52:37