以Mayavi,Python交互式更新颜色

时间:2015-06-29 15:14:07

标签: python traits mayavi

这是我在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()

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

我注意到points3d的交互性中的一个错误与您在此处描述的内容非常相似。我不知道这个bug的确切原因是什么,但我经常使用以下解决方法。基本想法是避免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