Skip to main content
 首页 » 编程设计

python之在 Mayavi、Python 中交互式更新颜色

2025年05月04日8unruledboy

这是我在 StackOverflow 上的第一篇文章。 我正在编写一个 Mayavi Python 程序。谁能告诉我如何以交互方式更新/修改点的颜色?例如,在 points3d() 中,当我交互式修改点的位置时实时更改点的颜色。 我试图在 @on_trait_change 下做一些事情,但它不起作用。颜色无法更改。 以下是我的代码:

import mayavi 
import mayavi.mlab 
from numpy import arange, pi, cos, sin 
 
from traits.api import HasTraits, Range, Instance, \ 
        on_trait_change 
from traitsui.api import View, Item, HGroup 
 
from mayavi.core.api import PipelineBase 
from mayavi.core.ui.api import MayaviScene, SceneEditor, \ 
                MlabSceneModel 
 
def luc_func(x, y, z): 
    return x + y + z; 
 
class Visualization(HasTraits): 
    x1 = Range(1, 30, 5) 
    z1 = Range(1, 30, 5) 
    scene      = Instance(MlabSceneModel, ()) 
    def __init__(self): 
        # Do not forget to call the parent's __init__ 
        HasTraits.__init__(self) 
        z = [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1] 
        y = [1,1,1,1,1,2,2,2,2,2,3,3,3,3,3,4,4,4,4,4,5,5,5,5,5] 
        x = [1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5,1,2,3,4,5] 
        self.plot = self.scene.mlab.points3d(x, y, z, luc_func, scale_mode = 'none') 
        #self.plot2 = self.scene.mlab.points3d(z, x, y, color = (0, 0, 1)) 
 
    @on_trait_change('x1,z1') 
    def update_plot(self): 
        x = [1,2,3,4,self.x1,1,2,3,4,self.x1,1,2,3,4,self.x1,1,2,3,4,self.x1,1,2,3,4,self.x1] 
        z = [1,1,1,1,self.z1,1,1,1,1,self.z1,1,1,1,1,self.z1,1,1,1,1,self.z1,1,1,1,1,self.z1] 
        luc_func = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,self.z1] 
        self.plot.mlab_source.reset(x = x, z = z, luc_func = luc_func) 
        #self.plot2.mlab_source.set(y = y, z = z) 
 
 
    # the layout of the dialog created 
    view = View(Item('scene', editor=SceneEditor(scene_class=MayaviScene), 
                    height=250, width=300, show_label=False), 
                HGroup( 
                        '_', 'x1', "z1", 
                    ), 
                ) 
visualization = Visualization() 
visualization.configure_traits() 

感谢您的帮助!

请您参考如下方法:

我注意到 points3d 的交互性中有一个错误,与您在此处描述的非常相似。我不知道这个错误的确切来源是什么,但我经常使用以下解决方法。基本思想是避免 mlab.points3d 而是直接调用 mlab.pipeline.glyph,如下所示:

def virtual_points3d(coords, figure=None, scale_factor=None, color=None,  
    name=None): 
 
    c = np.array(coords) 
    source = mlab.pipeline.scalar_scatter( c[:,0], c[:,1], c[:,2], 
        figure=figure) 
 
    return mlab.pipeline.glyph( source, scale_mode='none',  
        scale_factor=scale_factor, 
        mode='sphere', figure=figure, color=color, name=name) 

稍后您可以通过直接引用 vtk 对象而不是未正确连接的 mayavi 特征来更改颜色:

glyph = virtual_points3d(coords) 
glyph.mlab_source.dataset.point_data.scalars = new_values