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

Vispy SurfacePlot可视化:区域高亮与纹理叠加实现问询

Vispy SurfacePlot 两项功能实现方案

1. X轴中心区域颜色高亮

要实现特定区域高亮,核心是手动修改曲面的颜色数组,给目标区域的顶点分配专属颜色:

  • 先获取曲面的X坐标数据,判断哪些点处于X轴中心附近(比如X值在x_center ± 0.5范围内)
  • 初始化一个RGBA颜色数组,默认用基础色(比如蓝色)
  • 把符合条件的区域的颜色替换为高亮色(比如红色)
  • 将修改后的颜色数组传给SurfacePlot的color参数

2. 图像纹理叠加+移除曲面阴影

SurfacePlot默认的Phong光照会产生阴影,导致纹理颜色失真。要让曲面颜色和图像完全一致,需要禁用光照效果,同时正确加载图像作为纹理:

  • 用vispy.io.imread加载图像,转为纹理可用的格式
  • 创建SurfacePlot时,设置texture参数为加载的图像
  • 通过shading='none'关闭光照,或者将ambient=1.0、diffuse=1.0让光照不影响颜色显示
  • 确保纹理坐标和曲面的UV映射匹配(SurfacePlot默认会自动生成UV坐标,一般无需额外调整)

完整示例代码

import numpy as np
from vispy import app, scene
from vispy.io import imread

# 生成曲面数据
x = np.linspace(-5, 5, 100)
y = np.linspace(-5, 5, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(np.sqrt(X**2 + Y**2))

# 1. 处理X轴中心区域高亮
x_center = 0.0
highlight_range = 0.5  # 中心区域的X范围
# 初始化颜色数组:默认蓝色,RGBA格式
colors = np.full((Z.shape[0], Z.shape[1], 4), [0, 0, 1, 1], dtype=np.float32)
# 标记X中心区域的点
highlight_mask = np.abs(X - x_center) <= highlight_range
# 替换为高亮红色
colors[highlight_mask] = [1, 0, 0, 1]

# 2. 加载图像作为纹理
img = imread("your_image.png")  # 替换为你的图像路径
# 确保图像是RGBA格式(如果是RGB,需要添加alpha通道)
if img.shape[-1] == 3:
    img = np.concatenate([img, np.full((img.shape[0], img.shape[1], 1), 255, dtype=np.uint8)], axis=-1)
img = img.astype(np.float32) / 255.0  # 归一化到0-1

# 创建画布和视图
canvas = scene.SceneCanvas(keys='interactive', size=(800, 600), show=True)
view = canvas.central_widget.add_view()
view.camera = 'turntable'
view.camera.fov = 45

# 创建SurfacePlot,同时实现高亮和纹理叠加
surface = scene.visuals.SurfacePlot(
    x=x, y=y, z=Z,
    color=colors,  # 高亮颜色
    texture=img,   # 叠加纹理
    shading='none',  # 关闭光照,移除阴影
    parent=view.scene
)

# 调整纹理混合模式(可选,确保纹理和高亮颜色正确叠加)
surface.set_gl_state('translucent', blend=True)

if __name__ == '__main__':
    app.run()

关键说明

  • 高亮部分:通过布尔掩码highlight_mask定位X中心区域,直接修改颜色数组,这种方式高效且不需要额外的视觉元素
  • 纹理与阴影移除:shading='none'会完全关闭Vispy的光照计算,让曲面颜色直接使用纹理或自定义颜色,完美匹配图像原色;如果需要保留轻微光照,可设置shading='flat'并调整ambient=1.0、diffuse=1.0
  • 纹理叠加优先级:如果同时设置color和texture,默认会混合两者颜色。如果需要让纹理完全覆盖基础颜色,可去掉color参数,或者在高亮区域单独修改纹理对应的UV坐标(不过直接修改颜色数组更简单)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 09:25:19