Exemplo n.º 1
0
    def test_object_cache(self):
        """Test if object cache works."""
        cs = tvtk.ConeSource()
        hash1 = hash(cs)
        o = cs.output
        if hasattr(o, 'producer_port'):
            src = o.producer_port.producer
        else:
            src = o.source
        self.assertEqual(src, cs)
        self.assertEqual(hash1, hash(src))
        del cs, src
        gc.collect()
        cs = tvtk.ConeSource()  # Force cs to be gc'd!
        if hasattr(o, 'producer_port'):
            src = o.producer_port.producer
        else:
            src = o.source
        self.assertEqual(hash1 != hash(src), True)

        # Test for a bug with collections and the object cache.
        r = tvtk.Renderer()

        def _get_props(obj):
            if hasattr(obj, 'view_props'):
                return obj.view_props
            else:
                return obj.props

        p = _get_props(r)
        l1 = len(tvtk_base._object_cache)
        p1 = _get_props(r)
        del p1
        l2 = len(tvtk_base._object_cache)
        self.assertEqual(l1, l2)
Exemplo n.º 2
0
 def setUp(self):
     self.cs = cs = tvtk.ConeSource()
     self.ef = ef = tvtk.ElevationFilter(input_connection=cs.output_port)
     self.m = m = tvtk.PolyDataMapper(input_connection=ef.output_port)
     self.a = tvtk.Actor(mapper=m)
     self.ren = tvtk.Renderer()
     self.ren.add_actor(self.a)
     self.renwin = tvtk.RenderWindow()
     self.renwin.add_renderer(self.ren)
Exemplo n.º 3
0
    def _create_control(self, parent):
        """ Create the toolkit-specific control that represents the widget. """

        if self.off_screen_rendering:
            if hasattr(tvtk, 'EGLRenderWindow'):
                renwin = tvtk.EGLRenderWindow()
            elif hasattr(tvtk, 'OSOpenGLRenderWindow'):
                renwin = tvtk.OSOpenGLRenderWindow()
            else:
                renwin = tvtk.RenderWindow()
                # If we are doing offscreen rendering we set the window size to
                # (1,1) so the window does not appear at all
                renwin.size = (1, 1)

            self._renwin = renwin
            self._interactor = tvtk.GenericRenderWindowInteractor(
                render_window=renwin
            )
        else:
            renwin = self._renwin = tvtk.RenderWindow()
            self._interactor = tvtk.RenderWindowInteractor(
                render_window=renwin
            )

        renwin.trait_set(point_smoothing=self.point_smoothing,
                         line_smoothing=self.line_smoothing,
                         polygon_smoothing=self.polygon_smoothing)
        # Create a renderer and add it to the renderwindow
        self._renderer = tvtk.Renderer()
        renwin.add_renderer(self._renderer)
        # Save a reference to our camera so it is not GC'd -- needed for
        # the sync_traits to work.
        self._camera = self.camera

        # Sync various traits.
        self._renderer.background = self.background
        self.sync_trait('background', self._renderer)
        self._renderer.on_trait_change(self.render, 'background')
        self._camera.parallel_projection = self.parallel_projection
        self.sync_trait('parallel_projection', self._camera)
        renwin.off_screen_rendering = self.off_screen_rendering
        self.sync_trait('off_screen_rendering', self._renwin)
        self.render_window.on_trait_change(self.render, 'off_screen_rendering')
        self.render_window.on_trait_change(self.render, 'stereo_render')
        self.render_window.on_trait_change(self.render, 'stereo_type')
        self.camera.on_trait_change(self.render, 'parallel_projection')

        self._interactor.initialize()
        self._interactor.render()
        self.light_manager = light_manager.LightManager(self)
        if self.off_screen_rendering:
            # We want the default size to be the normal (300, 300).
            # Setting the size now should not resize the window if
            # offscreen is working properly in VTK.
            renwin.size = (300, 300)

        return self._interactor
Exemplo n.º 4
0
 def __init__(self, height, width):
     self.img_actor_wrap = ImageActorWrapper(height, width)
     self.renderer = tvtk.Renderer()
     self.renderer.add_actor(self.img_actor_wrap.getactor())
     self.renderer.interactive = False
     img_data = self.img_actor_wrap.img_data
     prepare_image_renderer(self.renderer,
                            extent=img_data.extent,
                            origin=img_data.origin,
                            spacing=img_data.spacing)
Exemplo n.º 5
0
def get_render_window():
    ren = tvtk.Renderer(background=(0.0, 0.0, 0.0), automatic_light_creation=0)
    rw = tvtk.RenderWindow(size=(width, height))
    rw.off_screen_rendering = 0
    rw.add_renderer(ren)
    rw.multi_samples = 0
    ac = ren.active_camera
    ac.view_angle = 44.61
    #ren.reset_camera()
    return rw
Exemplo n.º 6
0
 def _create_tvtk_window(self, size=(500,500)):
     # create a renderer
     self.renderer = tvtk.Renderer()
     # create a render window and hand it the renderer
     self.render_window = tvtk.RenderWindow(size=size)
     self.render_window.add_renderer(self.renderer)
     # create interactor and hand it the render window
     # This handles mouse interaction with window.
     self.interactor = tvtk.RenderWindowInteractor(render_window=self.render_window)
     self.gui = None
 def test2(self):
     '''展开交互图像窗口的常用流程'''
     s = tvtk.CubeSource(x_length=1.0, y_length=2.0, z_length=3.0)
     m = tvtk.PolyDataMapper(input_connection=s.output_port)
     a = tvtk.Actor(mapper=m)
     r = tvtk.Renderer(background=(0.5, 0.5, 0.5))
     r.add_actor(a)
     w = tvtk.RenderWindow(size=(500, 500))
     w.add_renderer(r)
     i = tvtk.RenderWindowInteractor(render_window=w)
     i.initialize()
     i.start()
Exemplo n.º 8
0
    def __init__(self, size=(300, 300), obj=None, update=True):
        tvtk.RenderWindowInteractor.__init__(self, obj, update)

        # create a renderer
        self.renderer = tvtk.Renderer()

        # create a render window and hand it the renderer
        self.render_window = tvtk.RenderWindow()
        self.render_window.add_renderer(self.renderer)
        self.render_window.size = size

        self.initialize()
Exemplo n.º 9
0
def test01():
    s = tvtk.ConeSource(height=6.0, radius=2.0)
    m = tvtk.PolyDataMapper(input_connection=s.output_port)

    a = tvtk.Actor(mapper=m)
    r = tvtk.Renderer(background=(1, 0, 0))
    r.add_actor(a)

    w = tvtk.RenderWindow(size=(300, 300))
    w.add_renderer(r)
    i = tvtk.RenderWindowInteractor(render_window=w)

    i.initialize()
    i.start()
Exemplo n.º 10
0
    def test_object_cache(self):
        """Test if object cache works."""
        cs = tvtk.ConeSource()
        hash1 = hash(cs)
        o = cs.output
        if hasattr(o, 'producer_port'):
            src = o.producer_port.producer
        else:
            src = cs.executive.algorithm
        self.assertEqual(src, cs)
        self.assertEqual(hash1, hash(src))
        del cs, src
        gc.collect()
        # The test sometimes fails as VTK seems to generate objects with the
        # same memory address and hash, we try to force it to allocate more
        # objects so as to not end up reusing the same address and hash.
        junk = [tvtk.ConeSource() for i in range(50)]

        # Now get another ConeSource and ensure the hash is different.
        cs = tvtk.ConeSource()
        o = cs.output
        if hasattr(o, 'producer_port'):
            src = o.producer_port.producer
        else:
            src = cs.executive.algorithm

        ##############################################################
        # This assertion is related to a bug fixed in VTK 6 onwards
        # For VTK 5.x this test is inconsistent, hence skipeed for 5.x
        # See http://review.source.kitware.com/#/c/15095/
        ##############################################################
        if vtk_major_version > 5:
            self.assertEqual(hash1 != hash(src), True)
        self.assertEqual(hash(cs), hash(src))

        # Test for a bug with collections and the object cache.
        r = tvtk.Renderer()

        def _get_props(obj):
            if hasattr(obj, 'view_props'):
                return obj.view_props
            else:
                return obj.props

        p = _get_props(r)
        l1 = len(tvtk_base._object_cache)
        p1 = _get_props(r)
        del p1
        l2 = len(tvtk_base._object_cache)
        self.assertEqual(l1, l2)
Exemplo n.º 11
0
def get_render_window(options):
    ren = tvtk.Renderer(background=(0.0, 0.0, 0.0))
    rw = tvtk.RenderWindow(size=(width, height))
    rw.off_screen_rendering = 0
    rw.add_renderer(ren)
    rw.multi_samples = 0
    ac = ren.active_camera
    ac.view_angle = 44.61

    ac.position = [options.shift, -options.distance, options.height]
    ac.view_up = [0, 0, 1]
    ac.focal_point = [options.shift, 0, options.height]
    ac.pitch(options.tilt)

    return rw
Exemplo n.º 12
0
def test01():
    # 1. 创建数据源,设置参数,并且将参数映射给数据m
    s = tvtk.CubeSource(x_length=1.0, y_length=2.0, z_length=3.0)
    m = tvtk.PolyDataMapper(input_connection=s.output_port)
    # 2. 创建背景和行为(可以转动),并且将行为送给 背景
    a = tvtk.Actor(mapper=m)
    r = tvtk.Renderer(background=(0, 0, 0))
    r.add_actor(a)
    # 3. 创建左面窗口的大小,并且将渲染器放入窗口
    w = tvtk.RenderWindow(size=(300, 300))
    w.add_renderer(r)

    # 4. 创建交互界面,将窗口放入
    i = tvtk.RenderWindowInteractor(render_window=w)

    i.initialize()
    i.start()
Exemplo n.º 13
0
    def render_bitmap(self,
                      width,
                      height,
                      filename=None,
                      azimuth=15.0,
                      elevation=30.0,
                      roll=0.0,
                      zoom=1.0,
                      pan_h=0.0,
                      pan_v=0.0):
        renderer = tvtk.Renderer()
        for actor in self.scene.actor_list:
            renderer.add_actor(actor)
        renderer.background = (1, 1, 0.8)

        renderer.reset_camera()
        camera = renderer.active_camera
        camera.roll(roll)
        camera.elevation(elevation)
        camera.azimuth(azimuth)
        camera.dolly(zoom)
        camera.yaw(pan_h)
        camera.pitch(pan_v)

        renderWindow = tvtk.RenderWindow()
        renderWindow.off_screen_rendering = True
        renderWindow.add_renderer(renderer)
        renderWindow.size = (width, height)
        renderWindow.render()

        windowToImageFilter = tvtk.WindowToImageFilter()
        windowToImageFilter.input = renderWindow
        windowToImageFilter.update()

        writer = tvtk.PNGWriter()
        if filename is not None:
            writer.file_name = filename
            writer.write_to_memory = False
        else:
            writer.write_to_memory = True
        writer.input_connection = windowToImageFilter.output_port
        writer.write()
        #data = numpy.asarray(writer.result).tostring()
        return writer.result
Exemplo n.º 14
0
    def test_object_cache(self):
        """Test if object cache works."""
        cs = tvtk.ConeSource()
        hash1 = hash(cs)
        o = cs.output
        if hasattr(o, 'producer_port'):
            src = o.producer_port.producer
        else:
            src = cs.executive.algorithm
        self.assertEqual(src, cs)
        self.assertEqual(hash1, hash(src))
        del cs, src
        gc.collect()
        # The test sometimes fails as VTK seems to generate objects with the
        # same memory address and hash, we try to force it to allocate more
        # objects so as to not end up reusing the same address and hash.
        junk = [vtk.vtkConeSource() for i in range(5)]

        # Now get another ConeSource and ensure the hash is different.
        cs = tvtk.ConeSource()
        o = cs.output
        if hasattr(o, 'producer_port'):
            src = o.producer_port.producer
        else:
            src = cs.executive.algorithm

        self.assertEqual(hash1 != hash(src), True)
        self.assertEqual(hash(cs), hash(src))

        # Test for a bug with collections and the object cache.
        r = tvtk.Renderer()

        def _get_props(obj):
            if hasattr(obj, 'view_props'):
                return obj.view_props
            else:
                return obj.props

        p = _get_props(r)
        l1 = len(tvtk_base._object_cache)
        p1 = _get_props(r)
        del p1
        l2 = len(tvtk_base._object_cache)
        self.assertEqual(l1, l2)
Exemplo n.º 15
0
def ShowACube(x, y, z, backgroundcolor=(0, 0, 0)):
    #立方体源
    s = tvtk.CubeSource(x_length=x, y_length=y, z_length=z)
    #转换源为图形数据
    m = tvtk.PolyDataMapper(input_connection=s.output_port)
    #创建Actor,并将图形数据接入
    a = tvtk.Actor(mapper=m)
    #创建渲染,并将Actor接入
    r = tvtk.Renderer(background=backgroundcolor)
    r.add_actor(a)
    #创建窗口,并将渲染接入
    w = tvtk.RenderWindow(size=(900, 900))
    w.add_renderer(r)
    #创建交互,并将窗口接入
    i = tvtk.RenderWindowInteractor(render_window=w)

    #开始运行
    i.initialize()
    i.start()
Exemplo n.º 16
0
def test_source():

    # 创建一个长方体数据源,并且同时设置其长宽高
    s = tvtk.CubeSource(x_length=1.0, y_length=2.0, z_length=3.0)
    # 使用PolyDataMapper将数据转换为图形数据
    m = tvtk.PolyDataMapper(input_connection=s.output_port)
    # 创建一个Actor
    a = tvtk.Actor(mapper=m)
    # 创建一个Renderer,将Actor添加进去
    r = tvtk.Renderer(background=(0, 0, 0))
    r.add_actor(a)
    # 创建一个RenderWindow(窗口),将Renderer添加进去
    w = tvtk.RenderWindow(size=(300, 300))
    w.add_renderer(r)
    # 创建一个RenderWindowInteractor(窗口的交互工具)
    i = tvtk.RenderWindowInteractor(render_window=w)
    # 开启交互
    i.initialize()
    i.start()
Exemplo n.º 17
0
        def _create_control(self, parent):
            """ Create the toolkit-specific control that represents the widget. """

            # Create the VTK widget.
            self._vtk_control = window = FlatInteractor(self,
                                                        parent,
                                                        stereo=self.stereo)

            # Switch the default interaction style to the trackball one.
            window.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

            # Grab the renderwindow.
            renwin = self._renwin = tvtk.to_tvtk(window.GetRenderWindow())
            renwin.set(point_smoothing=self.point_smoothing,
                       line_smoothing=self.line_smoothing,
                       polygon_smoothing=self.polygon_smoothing)
            # Create a renderer and add it to the renderwindow
            self._renderer = tvtk.Renderer()
            renwin.add_renderer(self._renderer)
            # Save a reference to our camera so it is not GC'd -- needed for
            # the sync_traits to work.
            self._camera = self.camera

            # Sync various traits.
            self._renderer.background = self.background
            self.sync_trait('background', self._renderer)
            self.renderer.on_trait_change(self.render, 'background')
            renwin.off_screen_rendering = self.off_screen_rendering
            self._camera.parallel_projection = self.parallel_projection
            self.sync_trait('parallel_projection', self._camera)
            self.sync_trait('off_screen_rendering', self._renwin)
            self.render_window.on_trait_change(self.render,
                                               'off_screen_rendering')
            self.render_window.on_trait_change(self.render, 'stereo_render')
            self.render_window.on_trait_change(self.render, 'stereo_type')
            self.camera.on_trait_change(self.render, 'parallel_projection')

            self._interactor = tvtk.to_tvtk(window._Iren)

            return window
Exemplo n.º 18
0
m = tvtk.PolyDataMapper()

# Note that VTK's GetOutput method is special because it has two call
# signatures: GetOutput() and GetOutput(int N) (which gets the N'th
# output).  In tvtk it is represented as both a property and as a
# method.  Using the output property will work fine if all you want is
# the default output.  OTOH if you want the N'th output use
# get_output(N).
m.input = cs.output  # or m.input = cs.get_output()

# Create the actor and set its mapper.
a = tvtk.Actor()
a.mapper = m

# Create a Renderer, add the actor and set its background color.
ren = tvtk.Renderer()
ren.add_actor(a)
ren.background = (0.1, 0.2, 0.4)

# Create a RenderWindow, add the renderer and set its size.
rw = tvtk.RenderWindow()
rw.add_renderer(ren)
rw.size = (300, 300)

# Create the RenderWindowInteractor
rwi = tvtk.RenderWindowInteractor()
rwi.render_window = rw

# Setup a box widget.
bw = tvtk.BoxWidget()
bw.interactor = rwi
Exemplo n.º 19
0
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 20 17:50:15 2017

@author: Administrator
"""

from tvtk.api import tvtk
 
# 创建一个长方体数据源,并且同时设置其长宽高
s = tvtk.CubeSource(x_length=1.0, y_length=2.0, z_length=3.0)
# 使用PolyDataMapper将数据转换为图形数据
m = tvtk.PolyDataMapper(input_connection=s.output_port)
# 创建一个Actor
a = tvtk.Actor(mapper=m)
# 创建一个Renderer,将Actor添加进去
r = tvtk.Renderer(background=(0, 0, 0))
r.add_actor(a)
# 创建一个RenderWindow(窗口),将Renderer添加进去
w = tvtk.RenderWindow(size=(300,300))
w.add_renderer(r)
# 创建一个RenderWindowInteractor(窗口的交互工具)
i = tvtk.RenderWindowInteractor(render_window=w)
# 开启交互
i.initialize()
i.start()
Exemplo n.º 20
0
from tvtk.api import tvtk
import cv2


# 创建一个长方体数据源,并且同时设置其长宽高
s = tvtk.CubeSource(x_length=1.0, y_length=2.0, z_length=3.0)
# 使用PolyDataMapper将数据转换为图形数据
m = tvtk.PolyDataMapper(input_connection=s.output_port)
# 创建一个Actor
a = tvtk.Actor(mapper=m)
# 创建一个Renderer,将Actor添加进去
r = tvtk.Renderer(background=(255 / 255, 0, 0))
r.add_actor(a)
# 创建一个RenderWindow(窗口),将Renderer添加进去
w = tvtk.RenderWindow(size=(300, 300))
w.add_renderer(r)
# 创建一个RenderWindowInteractor(窗口的交互工具)
i = tvtk.RenderWindowInteractor(render_window=w)
# 开启交互
i.initialize()
i.start()
Exemplo n.º 21
0
        raise ValueError("ary must be 3 dimensional.")

    return img


sz = (256, 256, 3)
array_3d = zeros(sz, uint8)
img = image_from_array(array_3d)

t = tvtk.Texture(interpolate=1)
configure_input_data(t, img)
a.texture = t

# Renderwindow stuff and add actor.
rw = tvtk.RenderWindow(size=(600, 600))
ren = tvtk.Renderer(background=(0.1, 0.2, 0.4))
rw.add_renderer(ren)
rwi = tvtk.RenderWindowInteractor(render_window=rw)
ren.add_actor(a)
rwi.initialize()

# create a little wave to slide across the image.
wave = 1 / sqrt(2 * pi) * exp(-arange(-2, 2, .05)**2 / 2) * 255
# have to use += here because = doesn't respect broadcasting correctly.
array_3d[:len(wave)] += wave.astype(uint8)[:, None, None]

import time
t1 = time.time()
N = 256
for i in range(N):
    array_3d[1:] = array_3d[:-1]
Exemplo n.º 22
0
# Convert this to a PolyData object.
geom_filter = tvtk.ImageDataGeometryFilter(input=sp)

# Now warp this using the scalar value to generate a carpet plot.
warp = tvtk.WarpScalar(input=geom_filter.output)

# Smooth the resulting data so it looks good.
normals = tvtk.PolyDataNormals(input=warp.output)

# The rest of the VTK pipeline.
m = tvtk.PolyDataMapper(input=normals.output,
                        scalar_range=(min(z), max(z)))
a = tvtk.Actor(mapper=m)

ren = tvtk.Renderer(background=(0.5, 0.5, 0.5))
ren.add_actor(a)

# Get a nice view.
cam = ren.active_camera
cam.azimuth(-60)
cam.roll(90)

# Create a RenderWindow, add the renderer and set its size.
rw = tvtk.RenderWindow(size=(600, 600))
rw.add_renderer(ren)

# Create the RenderWindowInteractor
rwi = tvtk.RenderWindowInteractor(render_window=rw)

rwi.initialize()
Exemplo n.º 23
0
    def initialize(self, X, Y, initial_data=None, vmin=None, vmax=None):
        """
		Create objects to plot on
		"""
        if initial_data == None:
            initial_data = zeros(shape(X))
            if vmin == None:
                self.vmin = -1.0
            if vmax == None:
                self.vmax = 1.0
        else:
            if vmin == None:
                self.vmin = np.min(np.min(initial_data))
            if vmax == None:
                self.vmax = np.max(np.max(initial_data))
        x_min = np.min(np.min(X))
        y_min = np.min(np.min(Y))
        x_max = np.max(np.max(X))
        y_max = np.max(np.max(Y))
        x_middle = (x_min + x_max) / 2
        y_middle = (y_min + y_max) / 2
        z_middle = np.mean(np.mean(initial_data))
        L = x_max - x_min
        diffs = np.shape(X)
        x_diff = diffs[0]
        y_diff = diffs[1]
        z_diff = 1.0  #self.vmax-self.vmin

        self.tvtk = tvtk
        self.sp = tvtk.StructuredPoints(origin=(x_middle, y_middle, z_middle),
                                        dimensions=(x_diff, y_diff, 1),
                                        spacing=(2 * L / (x_diff - 1),
                                                 2 * L / (y_diff - 1), 100.0))

        self.z = np.transpose(initial_data).flatten()

        self.sp.point_data.scalars = self.z
        self.geom_filter = tvtk.ImageDataGeometryFilter(input=self.sp)
        self.warp = tvtk.WarpScalar(input=self.geom_filter.output)
        self.normals = tvtk.PolyDataNormals(input=self.warp.output)

        # The rest of the VTK pipeline.
        self.m = tvtk.PolyDataMapper(input=self.normals.output,
                                     scalar_range=(self.vmin, self.vmax))
        p = tvtk.Property(opacity=0.5, color=(1, 1, 1), representation="s")
        self.a = tvtk.Actor(mapper=self.m, property=p)

        self.ren = tvtk.Renderer(background=(0.0, 0.0, 0.0))

        self.ren.add_actor(self.a)

        # Get a nice view.
        self.cam = self.ren.active_camera
        self.cam.azimuth(-50)
        self.cam.roll(90)

        # Create a RenderWindow, add the renderer and set its size.
        self.rw = tvtk.RenderWindow(size=(800, 800))
        self.rw.add_renderer(self.ren)

        # Create the RenderWindowInteractor
        self.rwi = tvtk.RenderWindowInteractor(render_window=self.rw)

        self.rwi.initialize()
        self.ren.reset_camera()
        self.rwi.render()
Exemplo n.º 24
0
    def _create_control(self, parent):
        """ Create the toolkit-specific control that represents the widget. """

        # Create the VTK widget.
        self._vtk_control = window = wxVTKRenderWindowInteractor(parent, -1,
                                                                 stereo=self.stereo)

        # Override these handlers.
        wx.EVT_CHAR(window, None) # Remove the default handler.
        wx.EVT_CHAR(window, self.OnKeyDown)
        wx.EVT_KEY_UP(window, None) # Remove the default handler.
        wx.EVT_KEY_UP(window, self.OnKeyUp)
        wx.EVT_PAINT(window, None) # Remove the default handler.
        wx.EVT_PAINT(window, self.OnPaint)
        wx.EVT_SIZE(window, None) # Remove the default handler.
        wx.EVT_SIZE(window, self.OnSize)
        # Override the button down and up handlers as well to note the
        # interaction.  This is to toggle the busy status nicely.
        for evt in (wx.EVT_LEFT_DOWN, wx.EVT_RIGHT_DOWN,
                    wx.EVT_MIDDLE_DOWN):
            evt(window, None)
            evt(window, self.OnButtonDown)
        for evt in (wx.EVT_LEFT_UP, wx.EVT_RIGHT_UP,
                    wx.EVT_MIDDLE_UP):
            evt(window, None)
            evt(window, self.OnButtonUp)

        # Enable the widget.
        window.Enable(1)
        # Switch the default interaction style to the trackball one.
        window.GetInteractorStyle().SetCurrentStyleToTrackballCamera()

        # Grab the renderwindow.
        renwin = self._renwin = tvtk.to_tvtk(window.GetRenderWindow())
        renwin.set(point_smoothing=self.point_smoothing,
                   line_smoothing=self.line_smoothing,
                   polygon_smoothing=self.polygon_smoothing)
        # Create a renderer and add it to the renderwindow
        self._renderer = tvtk.Renderer()
        renwin.add_renderer(self._renderer)
        # Save a reference to our camera so it is not GC'd -- needed for
        # the sync_traits to work.
        self._camera = self.camera

        # Sync various traits.
        self._renderer.background = self.background
        self.sync_trait('background', self._renderer)
        self.renderer.on_trait_change(self.render, 'background')
        self._camera.parallel_projection = self.parallel_projection
        self.sync_trait('parallel_projection', self._camera)
        renwin.off_screen_rendering = self.off_screen_rendering
        self.sync_trait('off_screen_rendering', self._renwin)
        self.render_window.on_trait_change(self.render, 'off_screen_rendering')
        self.render_window.on_trait_change(self.render, 'stereo_render')
        self.render_window.on_trait_change(self.render, 'stereo_type')
        self.camera.on_trait_change(self.render, 'parallel_projection')

        def _show_parent_hack(window, parent):
            """A hack to get the VTK scene properly setup for use."""
            # Force the parent to show itself.
            parent.Show(1)
            # on some platforms, this SetSize() is necessary to cause
            # an OnPaint() when the event loop begins; else we get an
            # empty window until we force a redraw.
            window.SetSize(parent.GetSize())
            # This is necessary on slow machines in order to force the
            # wx events to be handled.
            wx.GetApp().Yield(True)
            window.Render()

        if wx.Platform == '__WXMSW__':
            _show_parent_hack(window, parent)
        else:
            if (wx.VERSION[0] == 2) and (wx.VERSION[1] < 5):
                _show_parent_hack(window, parent)
            window.Update()

        # Because of the way the VTK widget is setup, and because we
        # set the size above, the window sizing is usually completely
        # messed up when the application window is shown.  To work
        # around this a dynamic IDLE event handler is added and
        # immediately removed once it executes.  This event handler
        # simply forces a resize to occur.  The _idle_count allows us
        # to execute the idle function a few times (this seems to work
        # better).
        def _do_idle(event, window=window):
            w = wx.GetTopLevelParent(window)
            # Force a resize
            sz = w.GetSize()
            w.SetSize((sz[0]-1, sz[1]-1))
            w.SetSize(sz)
            window._idle_count -= 1
            if window._idle_count < 1:
                wx.EVT_IDLE(window, None)
                del window._idle_count

        window._idle_count = 2
        wx.EVT_IDLE(window, _do_idle)

        self._interactor = tvtk.to_tvtk(window._Iren)
        return window
Exemplo n.º 25
0
def writepolydata(polyd, vtkfile, writer=tvtk.PolyDataWriter()):
    writer.input = polyd
    writer.file_name = vtkfile
    writer.write()

def readpolydata(vtkfile):
    reader = tvtk.PolyDataReader()
    reader.file_name = vtkfile
    reader.update()
    polydata = reader.output
    return polydata

# refactor renderer into a class variable to allow multiple displays
# See Visualizer class
renderer = tvtk.Renderer()

def visvtk(vtkfile, clip_bounds=None, color_by_normals=False,
           renderer=renderer):
    """
    visualizes the vtkfile with cells colored by normals. Also, right click
    saves "screnshot.png" in the current directory.
    """
    polydata = readpolydata(vtkfile)

    if clip_bounds is not None:
        box = tvtk.Box()
        #box.set_bounds(-5, 5, -5, 2.5, -5, 5)
        box.set_bounds(*clip_bounds)
        clipper = tvtk.ClipPolyData(input=polydata)
        clipper.inside_out = True
# -*- coding: utf-8 -*-
from tvtk.api import tvtk

# 创建一个圆锥数据源,并且同时设置其高度,底面半径和底面圆的分辨率(用36边形近似)
cs = tvtk.ConeSource(height=3.0, radius=1.0, resolution=36)
# 使用PolyDataMapper将数据转换为图形数据
m = tvtk.PolyDataMapper(input_connection=cs.output_port)
# 创建一个Actor
a = tvtk.Actor(mapper=m)
# 创建一个Renderer,将Actor添加进去
ren = tvtk.Renderer(background=(1, 1, 1))
ren.add_actor(a)
# 创建一个RenderWindow(窗口),将Renderer添加进去
rw = tvtk.RenderWindow(size=(300, 300))
rw.add_renderer(ren)
# 创建一个RenderWindowInteractor(窗口的交互工具)
rwi = tvtk.RenderWindowInteractor(render_window=rw)
# 开启交互
rwi.initialize()
rwi.start()
Exemplo n.º 27
0
    def ipython_view(self, width, height, view={}):
        import ipywidgets as widgets
        from IPython.display import Image, display, clear_output

        renderer = tvtk.Renderer()
        for actor in self.scene.actor_list:
            renderer.add_actor(actor)
        renderer.background = (1, 1, 0.8)
        #
        renderer.reset_camera()
        camera = renderer.active_camera
        if "position" in view:
            camera.position = view['position']
        if "focal_point" in view:
            camera.focal_point = view['focal_point']
        if "view_up" in view:
            camera.view_up = view['view_up']
#
        renderWindow = tvtk.RenderWindow()
        renderWindow.off_screen_rendering = True
        renderWindow.add_renderer(renderer)
        renderWindow.size = (width, height)
        renderWindow.render()

        windowToImageFilter = tvtk.WindowToImageFilter()
        windowToImageFilter.input = renderWindow
        windowToImageFilter.update()
        #
        filename = "/dev/shm/temp_vtk_put.png"
        writer = tvtk.PNGWriter()
        writer.file_name = filename
        writer.write_to_memory = False
        writer.input_connection = windowToImageFilter.output_port
        writer.write()

        view_out = {}

        def show():
            clear_output(wait=True)
            renderer.reset_camera_clipping_range()
            renderer.modified()
            renderWindow.render()
            windowToImageFilter.input = renderWindow
            windowToImageFilter.modified()
            windowToImageFilter.update()
            writer.write()
            view_out.update({
                "position": tuple(camera.position),
                "view_up": tuple(camera.view_up),
                "focal_point": tuple(camera.focal_point)
            })
            return display(Image(filename), grp)

        def r_up(arg):
            camera.orthogonalize_view_up()
            camera.elevation(10)
            return show()

        def r_down(arg):
            camera.orthogonalize_view_up()
            camera.elevation(-10)
            return show()

        def r_left(arg):
            camera.orthogonalize_view_up()
            camera.azimuth(10)
            return show()

        def r_right(arg):
            camera.orthogonalize_view_up()
            camera.azimuth(-10)
            return show()

        def pan_left(arg):
            camera.orthogonalize_view_up()
            camera.yaw(-2)
            return show()

        def pan_right(arg):
            camera.orthogonalize_view_up()
            camera.yaw(2)
            return show()

        def pan_up(arg):
            camera.orthogonalize_view_up()
            camera.pitch(-2)
            return show()

        def pan_down(arg):
            camera.orthogonalize_view_up()
            camera.pitch(2)
            return show()

        def roll_left(arg):
            camera.roll(10)
            return show()

        def roll_right(arg):
            camera.roll(-10)
            return show()

        def zoom_in(arg):
            camera.dolly(1.2)
            return show()

        def zoom_out(arg):
            camera.dolly(0.8)
            return show()

        b1 = widgets.Button(description='\u2191')
        b1.on_click(r_up)
        b2 = widgets.Button(description='\u2193')
        b2.on_click(r_down)
        b3 = widgets.Button(description='\u2190')
        b3.on_click(r_left)
        b4 = widgets.Button(description='\u2192')
        b4.on_click(r_right)
        b5 = widgets.Button(description='\u21ba')
        b5.on_click(roll_left)
        b6 = widgets.Button(description='\u21bb')
        b6.on_click(roll_right)

        b7 = widgets.Button(description='+')
        b7.on_click(zoom_in)
        b8 = widgets.Button(description='-')
        b8.on_click(zoom_out)
        b9 = widgets.Button(description='\u2190')
        b9.on_click(pan_left)
        b10 = widgets.Button(description='\u2192')
        b10.on_click(pan_right)
        b11 = widgets.Button(description='\u2191')
        b11.on_click(pan_up)
        b12 = widgets.Button(description='\u2193')
        b12.on_click(pan_down)

        grp1 = widgets.HBox(border_style="solid",
                            border_width=1,
                            border_radius=5,
                            padding=2,
                            margin=1)
        grp1.children = [b1, b2, b3, b4, b5, b6]

        grp2 = widgets.HBox(border_style="solid",
                            border_width=1,
                            border_radius=5,
                            padding=2,
                            margin=1)
        grp2.children = [b7, b8, b9, b10, b11, b12]

        grp = widgets.HBox(children=[grp1, grp2])

        show()
        return view_out