How do I define a floatSlider using python2.7 in maya? - python

very new to scripting with python in maya so excuse my limited knowledge.
I need help figuring out how to define the variable for a floatSlider. I need two float sliders for the assignment I'm doing. I need one that will change the size of the selected or specified objects, and I need another that will use MASH to change the count of that object.
I have script with those sliders and a Distribute button laid out. I'm not sure what I need to include to link the scale of the object to the slider I have.
This is the code I have so far:
from maya import cmds
if cmds.window('mainUI2', exists=True):
cmds.deleteUI
win = cmds.window("mainUI2", title="Bush Generator", widthHeight=(300, 300))
# Layout
cmds.columnLayout(adjustableColumn=True)
cmds.text(label='Bush Generator')
cmds.button(label='Distribute', command='DistributeMesh()')
cmds.text(label=' ')
# need help defining Leaf_size
Leaf_size = cmds.floatSlider(min=0, max=100, value=0, step=1)
# I tried another type of slider
LeafScale = cmds.intSliderGrp(min=0, max=100, f=True)
cmds.text(label='Leaf Size')
# need defining Leaf_amount and linking to mash count
Leaf_amount = cmds.floatSlider(min=0, max=100, value=0, step=1)
cmds.text(label='Leaf Amount')
# Bush tool
def DistributeMesh():
cmds.loadPlugin("MASH", quiet=True)
import MASH.api as mapi
count = 3000
source_mesh = "pCube2"
scatter_mesh = "pSphere1"
source_shape = cmds.listRelatives(scatter_mesh, children=True)[0]
cmds.select(source_mesh)
mash_network = mapi.Network()
mash_network.createNetwork(name="Test", geometry="Instancer")
# set to use meshes to scatter
cmds.setAttr(mash_network.distribute + ".arrangement", 4)
cmds.setAttr(mash_network.distribute + ".pointCount", count)
# connect mesh
cmds.connectAttr(
source_shape + ".worldMesh[0]",
mash_network.distribute + ".inputMesh",
force=True)
cmds.showWindow(win)

Scale is a float value so you can use cmds.floatSliderGrp to set the source mesh's scale. First you have to define a separate function that will be triggered when you change the value of floatSliderGrp, then in floatSliderGrp set its changeCommand parameter to that function:
from maya import cmds
# Define a function that will be called when the slider changes values.
def on_size_slider_changed(value):
source_mesh = "pCube2"
if cmds.objExists(source_mesh): # Check if it exists.
cmds.setAttr("{}.scale".format(source_mesh), value, value, value) # Set its scale.
if cmds.window('mainUI2', exists=True):
cmds.deleteUI
win = cmds.window("mainUI2", title="Bush Generator", widthHeight=(300, 300))
# Layout
cmds.columnLayout(adjustableColumn=True)
cmds.text(label='Bush Generator')
cmds.button(label='Distribute', command='DistributeMesh()')
# Use `changeCommand` to define what function it should call.
leaf_size_slider = cmds.floatSliderGrp(label="Size", field=True, min=0, max=100, value=1, changeCommand=on_size_slider_changed)
# Bush tool
def DistributeMesh():
cmds.loadPlugin("MASH", quiet=True)
import MASH.api as mapi
count = 3000
source_mesh = "pCube2"
scatter_mesh = "pSphere1"
source_shape = cmds.listRelatives(scatter_mesh, children=True)[0]
cmds.select(source_mesh)
mash_network = mapi.Network()
mash_network.createNetwork(name="Test", geometry="Instancer")
# set to use meshes to scatter
cmds.setAttr(mash_network.distribute + ".arrangement", 4)
cmds.setAttr(mash_network.distribute + ".pointCount", count)
# connect mesh
cmds.connectAttr(
source_shape + ".worldMesh[0]",
mash_network.distribute + ".inputMesh",
force=True)
cmds.showWindow(win)
Dragging the slider will now set the scale of the cube. Though to be honest the structure of the code here is very messy and a bit too hard-coded (think about how it would work with the current selection instead of explicitly using the object's names)

Related

How do I pass the object clicked on in a bokeh network graph

I have implemented a bokeh network graph with a datasource as follows:
# Create a Bokeh graph from the NetworkX input using nx.spring_layout
graph = from_networkx(G, nx.spring_layout, center=(0,0), scale=1.8)
plot.renderers.append(graph)
# Add some new columns to the node renderer data source
#graph.node_renderer.data_source.data['index'] = list(range(len(G)))
degrees = scale_degree_size([v[1] for v in G.degree()], 5, 20)
graph.node_renderer.data_source.data['degree'] = degrees
graph.node_renderer.data_source.data["color"] = [colors[G.nodes[x].get("isA")] if G.nodes[x].get("isA") else colors["default"]for x in nx.nodes(G)]
graph.node_renderer.data_source.data["type"] = [G.nodes[x].get("isA").split('/')[-1] if G.nodes[x].get("isA") else "Untyped" for x in nx.nodes(G)]
graph.node_renderer.data_source.data["aka"] = [G.nodes[x].get("aka").split('/')[-1] if G.nodes[x].get("aka") else "???" for x in nx.nodes(G)]
graph.node_renderer.glyph = Circle(size=15, fill_color="red") #Spectral4[0])
graph.node_renderer.selection_glyph = Circle(size=15, fill_color=Spectral4[2])
graph.node_renderer.hover_glyph = Circle(size=15, fill_color=Spectral4[1])
graph.edge_renderer.glyph = MultiLine(line_color="#CCCCCC", line_alpha=0.8, line_width=3) # , end=OpenHead(line_color="firebrick", line_width=4)
graph.edge_renderer.selection_glyph = MultiLine(line_color=Spectral4[2], line_width=5)
graph.edge_renderer.hover_glyph = MultiLine(line_color=Spectral4[1], line_width=5)
graph.selection_policy = NodesAndLinkedEdges()
graph.node_renderer.glyph.update(size='degree') #, fill_color="colors")
graph.node_renderer.glyph.update(fill_color='color')
This works without any problem. I now need to add the functionality of bringing up an info box when clicking on a node in the ui. So I have tried to add this function to Tap.
# setup button click
def callback(???):
return CustomJS(args=dict(degrees=graph.node_renderer.data_source.data), code='alert(`${???}`)')
plot.js_on_event('tap', callback(???))
show(plot)
My question is, how do I pass the information of what node was clicked into the CustomJs? I have look at cb_obj, but it only has the mouse position and I need info on the node clicked.
add Tap
plot.on_event(Tap, function)
and update your source with indices
def function():
print(source.selected.indices)
i dont have your data so cant help more.

scrollbar does not work in recent chaco releases

This program was running fine in chaco 3.2, but with chaco 4, scrollbar does not show at all.
I would like either to find the problem or find a workaround.
PanTool may be a workaround, but this will conflict with some linecursors used with mouse.
#!/usr/bin/env python
# Major library imports
from numpy import linspace
from scipy.special import jn
# Enthought library imports
from enthought.enable.api import Component, ComponentEditor
from enthought.traits.api import HasTraits, Instance
from enthought.traits.ui.api import Item, Group, View
# Chaco imports
from enthought.chaco.api import ArrayPlotData, VPlotContainer, \
Plot, OverlayPlotContainer, add_default_axes, add_default_grids
from enthought.chaco.plotscrollbar import PlotScrollBar
from enthought.chaco.tools.api import PanTool, ZoomTool
#===============================================================================
# # Create the Chaco plot.
#===============================================================================
def _create_plot_component():
# Create some x-y data series to plot
x = linspace(-2.0, 10.0, 100)
pd = ArrayPlotData(index = x)
for i in range(5):
pd.set_data("y" + str(i), jn(i,x))
# Create some line plots of some of the data
plot1 = Plot(pd)
plot1.plot(("index", "y0", "y1", "y2"), name="j_n, n<3", color="red")[0]
p = plot1.plot(("index", "y3"), name="j_3", color="blue")[0]
# Add the scrollbar
plot1.padding_top = 0
p.index_range.high_setting = 1
# Create a container and add our plots
container = OverlayPlotContainer(padding = 5,fill_padding = True,
bgcolor = "lightgray", use_backbuffer=True)
hscrollbar = PlotScrollBar(component=p, mapper=p.index_mapper,axis="index", resizable="",use_backbuffer = False,
height=15,position=(0,0))
hscrollbar.force_data_update()
plot1.overlays.append(hscrollbar)
hgrid,vgrid = add_default_grids(plot1)
add_default_axes(plot1)
container.add(plot1)
container.invalidate_and_redraw()
return container
#===============================================================================
# Attributes to use for the plot view.
size=(900,500)
title="Scrollbar example"
#===============================================================================
# # Demo class that is used by the demo.py application.
#===============================================================================
class Demo(HasTraits):
plot = Instance(Component)
traits_view = View(
Group(
Item('plot', editor=ComponentEditor(size=size),
show_label=False),
orientation = "vertical"),
resizable=True, title=title
)
def _plot_default(self):
return _create_plot_component()
demo = Demo()
if __name__ == "__main__":
demo.configure_traits()
#--EOF---
We investigated and found some problems in the code of enable api (https://github.com/enthought/enable), that had disallowed the scrollbar to display in wx backend.
The following patch solves the problem.
There are other issues, like height setting that does not work, we will continue to investigate.
diff --git a/enable/wx/scrollbar.py b/enable/wx/scrollbar.py
index 02d0da0..003cc90 100644
--- a/enable/wx/scrollbar.py
+++ b/enable/wx/scrollbar.py
## -136,7 +136,7 ##
# We have to do this flip_y business because wx and enable use opposite
# coordinate systems, and enable defines the component's position as its
# lower left corner, while wx defines it as the upper left corner.
- window = getattr(gc, "window", None)
+ window = getattr(self, "window", None)
if window is None:
return
wx_ypos = window._flip_y(wx_ypos)

updating a Slider min - max range in runtime in matplotlib [duplicate]

I am trying to write a small bit of code that interactively deletes selected slices in an image series using matplotlib. I have created a button 'delete' which stores a number of indices to be deleted when the button 'update' is selected. However, I am currently unable to reset the range of my slider widget, i.e. removing the number of deleted slices from valmax. What is the pythonic solution to this problem?
Here is my code:
import dicom
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
frame = 0
#store indices of slices to be deleted
delete_list = []
def main():
data = np.random.rand(16,256,256)
nframes = data.shape[0]
raw_dicom_stack = []
for x in range (nframes):
raw_dicom_stack.append(data[x,:,:])
#yframe = 0
# Visualize it
viewer = VolumeViewer(raw_dicom_stack, nframes)
viewer.show()
class VolumeViewer(object):
def __init__(self, raw_dicom_stack, nframes):
global delete_list
self.raw_dicom_stack = raw_dicom_stack
self.nframes = nframes
self.delete_list = delete_list
# Setup the axes.
self.fig, self.ax = plt.subplots()
self.slider_ax = self.fig.add_axes([0.2, 0.03, 0.65, 0.03])
self.delete_ax = self.fig.add_axes([0.85,0.84,0.1,0.04])
self.update_ax = self.fig.add_axes([0.85,0.78,0.1,0.04])
self.register_ax = self.fig.add_axes([0.85,0.72,0.1,0.04])
self.add_ax = self.fig.add_axes([0.85,0.66,0.1,0.04])
# Make the slider
self.slider = Slider(self.slider_ax, 'Frame', 1, self.nframes,
valinit=1, valfmt='%1d/{}'.format(self.nframes))
self.slider.on_changed(self.update)
#Make the buttons
self.del_button = Button(self.delete_ax, 'Delete')
self.del_button.on_clicked(self.delete)
self.upd_button = Button(self.update_ax, 'Update')
self.upd_button.on_clicked(self.img_update)
self.reg_button = Button(self.register_ax, 'Register')
self.add_button = Button(self.add_ax, "Add")
# Plot the first slice of the image
self.im = self.ax.imshow(np.array(raw_dicom_stack[0]))
def update(self, value):
global frame
frame = int(np.round(value - 1))
# Update the image data
dat = np.array(self.raw_dicom_stack[frame])
self.im.set_data(dat)
# Reset the image scaling bounds (this may not be necessary for you)
self.im.set_clim([dat.min(), dat.max()])
# Redraw the plot
self.fig.canvas.draw()
def delete(self,event):
global frame
global delete_list
delete_list.append(frame)
print 'Frame %s has been added to list of slices to be deleted' %str(frame+1)
print 'Please click update to delete these slices and show updated image series \n'
#Remove duplicates from delete list
def img_update(self,event):
#function deletes image stacks and updates viewer
global delete_list
#Remove duplicates from list and sort into numerical order
delete_list = list(set(delete_list))
delete_list.sort()
#Make sure delete_list is not empty
if not delete_list:
print "Delete list is empty, no slices to delete"
#Loop through delete list in reverse numerical order and remove slices from series
else:
for i in reversed(delete_list):
self.raw_dicom_stack.pop(i)
print 'Slice %i removed from dicom series \n' %(i+1)
#Can now remove contents from delete_list
del delete_list[:]
#Update slider range
self.nframes = len(self.raw_dicom_stack)
def show(self):
plt.show()
if __name__ == '__main__':
main()
In order to update a slider range you may set the min and max value of it directly,
slider.valmin = 3
slider.valmax = 7
In order to reflect this change in the slider axes you need to set the limits of the axes,
slider.ax.set_xlim(slider.valmin,slider.valmax)
A complete example, where typing in any digit changes the valmin of the slider to that value.
import matplotlib.pyplot as plt
import matplotlib.widgets
fig, (ax,sliderax) = plt.subplots(nrows=2,gridspec_kw=dict(height_ratios=[1,.05]))
ax.plot(range(11))
ax.set_xlim(5,None)
ax.set_title("Type number to set minimum slider value")
def update_range(val):
ax.set_xlim(val,None)
def update_slider(evt):
print(evt.key)
try:
val = int(evt.key)
slider.valmin = val
slider.ax.set_xlim(slider.valmin,None)
if val > slider.val:
slider.val=val
update_range(val)
fig.canvas.draw_idle()
except:
pass
slider=matplotlib.widgets.Slider(sliderax,"xlim",0,10,5)
slider.on_changed(update_range)
fig.canvas.mpl_connect('key_press_event', update_slider)
plt.show()
It looks like the slider does not have a way to update the range (api). I would suggest setting the range of the slider to be [0,1] and doing
frame = int(self.nframes * value)
On a somewhat related note, I would have made frame an instance variable a data attribute instead of a global variable (tutorial).

Creating a mouse over text box in tkinter

I'm trying to implement system where when the user points to an object, a text box appears with certain information which I haven't implemented yet, then disappears when they move their mouse away. I'm trying to do that by binding the < Enter > and < Leave > commands, but nothing happens when I run the following code, except that in the terminal it says that destroy requires two arguments, so I know it is calling the functions.
from tkinter import *
xhig, yhig = 425,325
bkgnclr = '#070707'
currentmouseoverevent = ''
c = Canvas(master, width=xhig*2, height=yhig*2, bg=bkgnclr, cursor = 'crosshair',)
def mouseovertext(event):
mouseover = "Jack"
currentmouseoverevent = event
c.create_rectangle(bbox=(event.x,event.y, (event.x + 5), (event.y +len(mouseover)*5)),outline="white", fill=bkgnclr, width= len(mouseover))
c.create_text(position=(event.x,event.y),text=mouseover, fill="white", currentmouseoverevent=event)
def closemouseover(x):
c.destroy(currentmouseoverevent)
c.bind("<Enter>", mouseovertext)
c.bind("<Leave>", closemouseover)
What arguments does destroy take, and why is the rectangle not being created?
A bounding box (bbox) in tkinter is a 4-tuple which stores the bounds of the rectangle. You are only passing in the mouse location, which is a 2-tuple.
Also, you are never actually assigning to the variable "currentmouseoverevent" before using it in the code you show, so your closemouseover function will fail.
The corrected code is as follows.
It turns out I was calling bbox wrong. Instead of passing the coords as a tuple, I should have passed them as the first four agrguments of create_rectangle. c.destroy is only for objects like canvas, entry or textbox, instead I used c.delete for deleting items, and used the event number returned by c.create_rectangle and c.create_text.
from tkinter import *
xhig, yhig = 425,325
bkgnclr = '#070707'
currentmouseoverevent = ['','']
c = Canvas(master, width=xhig*2, height=yhig*2, bg=bkgnclr, cursor = 'crosshair',)
def mouseovertext(event):
mouseover = "Jack"
if currentmouseoverevent[0] != '':
closemouseover()
currentmouseoverevent[0]=''
return
currentmouseoverevent[0] = c.create_rectangle(event.x,event.y, (event.x + 5), (event.y +len(mouseover)*5),outline="white", fill=bkgnclr, width= len(mouseover))
currentmouseoverevent[1] = c.create_text(event.x,event.y,text=mouseover, fill="white", currentmouseoverevent=event,anchor=NW)
def closemouseover(x):
c.delete(currentmouseoverevent[0])
c.delete(currentmouseoverevent[1])
c.bind("<Button-3", mouseovertext)

3d image visualisation with numpy/vtk

I'm trying to display further images (ct-scan) using numpy/vtk as describe in this sample code (http://www.vtk.org/Wiki/VTK/Examples/Python/vtkWithNumpy) but I don't get it and don't know why.
If someone could help me it would be kind.
Here's my code :
import vtk
import numpy as np
import os
import cv, cv2
import matplotlib.pyplot as plt
import PIL
import Image
DEBUG =True
directory="splitted_mri/"
w = 226
h = 186
d = 27
stack = np.zeros((w,d,h))
k=-1 #add the next picture in a differente level of depth/z-positions
for file in os.listdir(directory):
k+=1
img = directory + file
im = Image.open(img)
temp = np.asarray(im, dtype=int)
stack[:,k,:]= temp
print stack.shape
#~ plt.imshow(test)
#~ plt.show()
print type(stack[10,10,15])
res = np.amax(stack)
res1 = np.amin(stack)
print res, type(res)
print res1, type(res1)
#~ for (x,y,z), value in np.ndenumerate(stack):
#~ stack[x,y,z]=np.require(stack[x,y,z],dtype=np.int16)
#~ print type(stack[x,y,z])
stack = np.require(stack,dtype=np.uint16)
print stack.dtype
if DEBUG : print stack.shape
dataImporter = vtk.vtkImageImport()
data_string = stack.tostring()
dataImporter.CopyImportVoidPointer(data_string, len(data_string))
dataImporter.SetDataScalarTypeToUnsignedChar()
dataImporter.SetNumberOfScalarComponents(1)
dataImporter.SetDataExtent(0, w-1, 0, 1, 0, h-1)
dataImporter.SetWholeExtent(0, w-1, 0, 1, 0, h-1)
essai = raw_input()
alphaChannelFunc = vtk.vtkPiecewiseFunction()
colorFunc = vtk.vtkColorTransferFunction()
for i in range (0,255):
alphaChannelFunc.AddPoint(i, 0.9)
colorFunc.AddRGBPoint(i,i,i,i)
volumeProperty = vtk.vtkVolumeProperty()
volumeProperty.SetColor(colorFunc)
#volumeProperty.ShadeOn()
volumeProperty.SetScalarOpacity(alphaChannelFunc)
# This class describes how the volume is rendered (through ray tracing).
compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
# We can finally create our volume. We also have to specify the data for it, as well as how the data will be rendered.
volumeMapper = vtk.vtkVolumeRayCastMapper()
volumeMapper.SetVolumeRayCastFunction(compositeFunction)
volumeMapper.SetInputConnection(dataImporter.GetOutputPort())
# The class vtkVolume is used to pair the preaviusly declared volume as well as the properties to be used when rendering that volume.
volume = vtk.vtkVolume()
volume.SetMapper(volumeMapper)
volume.SetProperty(volumeProperty)
# With almost everything else ready, its time to initialize the renderer and window, as well as creating a method for exiting the application
renderer = vtk.vtkRenderer()
renderWin = vtk.vtkRenderWindow()
renderWin.AddRenderer(renderer)
renderInteractor = vtk.vtkRenderWindowInteractor()
renderInteractor.SetRenderWindow(renderWin)
# We add the volume to the renderer ...
renderer.AddVolume(volume)
# ... set background color to white ...
renderer.SetBackground(1, 1, 1)
# ... and set window size.
renderWin.SetSize(400, 400)
# A simple function to be called when the user decides to quit the application.
def exitCheck(obj, event):
if obj.GetEventPending() != 0:
obj.SetAbortRender(1)
# Tell the application to use the function as an exit check.
renderWin.AddObserver("AbortCheckEvent", exitCheck)
#to quit, press q
renderInteractor.Initialize()
# Because nothing will be rendered without any input, we order the first render manually before control is handed over to the main-loop.
renderWin.Render()
renderInteractor.Start()
I finally find out what was wrong
here's my new code
import vtk
import numpy as np
import os
import matplotlib.pyplot as plt
import PIL
import Image
DEBUG =False
directory="splitted_mri/"
l = []
k=0 #add the next picture in a differente level of depth/z-positions
for file in os.listdir(directory):
img = directory + file
if DEBUG : print img
l.append(img)
# the os.listdir function do not give the files in the right order
#so we need to sort them
l=sorted(l)
temp = Image.open(l[0])
h, w = temp.size
d = len(l)*5 #with our sample each images will be displayed 5times to get a better view
if DEBUG : print 'width, height, depth : ',w,h,d
stack = np.zeros((w,d,h),dtype=np.uint8)
for i in l:
im = Image.open(i)
temp = np.asarray(im, dtype=int)
for i in range(5):
stack[:,k+i,:]= temp
k+=5
#~ stack[:,k,:]= temp
#~ k+=1
if DEBUG :
res = np.amax(stack)
print 'max value',res
res1 = np.amin(stack)
print 'min value',res1
#convert the stack in the right dtype
stack = np.require(stack,dtype=np.uint8)
if DEBUG :#check if the image have not been modified
test = stack [:,0,:]
plt.imshow(test,cmap='gray')
plt.show()
if DEBUG : print 'stack shape & dtype' ,stack.shape,',',stack.dtype
dataImporter = vtk.vtkImageImport()
data_string = stack.tostring()
dataImporter.CopyImportVoidPointer(data_string, len(data_string))
dataImporter.SetDataScalarTypeToUnsignedChar()
dataImporter.SetNumberOfScalarComponents(1)
#vtk uses an array in the order : height, depth, width which is
#different of numpy (w,h,d)
w, d, h = stack.shape
dataImporter.SetDataExtent(0, h-1, 0, d-1, 0, w-1)
dataImporter.SetWholeExtent(0, h-1, 0, d-1, 0, w-1)
alphaChannelFunc = vtk.vtkPiecewiseFunction()
colorFunc = vtk.vtkColorTransferFunction()
for i in range(256):
alphaChannelFunc.AddPoint(i, 0.2)
colorFunc.AddRGBPoint(i,i/255.0,i/255.0,i/255.0)
# for our test sample, we set the black opacity to 0 (transparent) so as
#to see the sample
alphaChannelFunc.AddPoint(0, 0.0)
colorFunc.AddRGBPoint(0,0,0,0)
volumeProperty = vtk.vtkVolumeProperty()
volumeProperty.SetColor(colorFunc)
#volumeProperty.ShadeOn()
volumeProperty.SetScalarOpacity(alphaChannelFunc)
# This class describes how the volume is rendered (through ray tracing).
compositeFunction = vtk.vtkVolumeRayCastCompositeFunction()
# We can finally create our volume. We also have to specify the data for
# it, as well as how the data will be rendered.
volumeMapper = vtk.vtkVolumeRayCastMapper()
# function to reduce the spacing between each image
volumeMapper.SetMaximumImageSampleDistance(0.01)
volumeMapper.SetVolumeRayCastFunction(compositeFunction)
volumeMapper.SetInputConnection(dataImporter.GetOutputPort())
# The class vtkVolume is used to pair the preaviusly declared volume as
#well as the properties to be used when rendering that volume.
volume = vtk.vtkVolume()
volume.SetMapper(volumeMapper)
volume.SetProperty(volumeProperty)
# With almost everything else ready, its time to initialize the renderer and window,
# as well as creating a method for exiting the application
renderer = vtk.vtkRenderer()
renderWin = vtk.vtkRenderWindow()
renderWin.AddRenderer(renderer)
renderInteractor = vtk.vtkRenderWindowInteractor()
renderInteractor.SetRenderWindow(renderWin)
# We add the volume to the renderer ...
renderer.AddVolume(volume)
# ... set background color to white ...
renderer.SetBackground(1, 1, 1)
# ... and set window size.
renderWin.SetSize(550, 550)
renderWin.SetMultiSamples(4)
# A simple function to be called when the user decides to quit the application.
def exitCheck(obj, event):
if obj.GetEventPending() != 0:
obj.SetAbortRender(1)
# Tell the application to use the function as an exit check.
renderWin.AddObserver("AbortCheckEvent", exitCheck)
#to auit, press q
renderInteractor.Initialize()
# Because nothing will be rendered without any input, we order the first
# render manually before control is handed over to the main-loop.
renderWin.Render()
renderInteractor.Start()
If you are ok with a solution not using VTK, you could use Matplotlib imshow and interactive navigation with keys.
This tutorial shows how:
https://www.datacamp.com/community/tutorials/matplotlib-3d-volumetric-data
https://github.com/jni/mpl-volume-viewer
and here an implementation for viewing RTdose files:
https://github.com/pydicom/contrib-pydicom/pull/19
See also:
https://github.com/napari/napari

Categories

Resources