[docs]defslicer(data,affine=None,value_range=None,opacity=1.,lookup_colormap=None,interpolation='linear',picking_tol=0.025):"""Cut 3D scalar or rgb volumes into 2D images. Parameters ---------- data : array, shape (X, Y, Z) or (X, Y, Z, 3) A grayscale or rgb 4D volume as a numpy array. affine : array, shape (4, 4) Grid to space (usually RAS 1mm) transformation matrix. Default is None. If None then the identity matrix is used. value_range : None or tuple (2,) If None then the values will be interpolated from (data.min(), data.max()) to (0, 255). Otherwise from (value_range[0], value_range[1]) to (0, 255). opacity : float, optional Opacity of 0 means completely transparent and 1 completely visible. lookup_colormap : vtkLookupTable If None (default) then a grayscale map is created. interpolation : string If 'linear' (default) then linear interpolation is used on the final texture mapping. If 'nearest' then nearest neighbor interpolation is used on the final texture mapping. picking_tol : float The tolerance for the vtkCellPicker, specified as a fraction of rendering window size. Returns ------- image_actor : ImageActor An object that is capable of displaying different parts of the volume as slices. The key method of this object is ``display_extent`` where one can input grid coordinates and display the slice in space (or grid) coordinates as calculated by the affine parameter. """ifdata.ndim!=3:ifdata.ndim==4:ifdata.shape[3]!=3:raiseValueError('Only RGB 3D arrays are currently supported.')else:nb_components=3else:raiseValueError('Only 3D arrays are currently supported.')else:nb_components=1ifvalue_rangeisNone:vol=np.interp(data,xp=[data.min(),data.max()],fp=[0,255])else:vol=np.interp(data,xp=[value_range[0],value_range[1]],fp=[0,255])vol=vol.astype('uint8')im=vtk.vtkImageData()I,J,K=vol.shape[:3]im.SetDimensions(I,J,K)voxsz=(1.,1.,1.)# im.SetOrigin(0,0,0)im.SetSpacing(voxsz[2],voxsz[0],voxsz[1])im.AllocateScalars(vtk.VTK_UNSIGNED_CHAR,nb_components)# copy data# what I do below is the same as what is commented here but much faster# for index in ndindex(vol.shape):# i, j, k = index# im.SetScalarComponentFromFloat(i, j, k, 0, vol[i, j, k])vol=np.swapaxes(vol,0,2)vol=np.ascontiguousarray(vol)ifnb_components==1:vol=vol.ravel()else:vol=np.reshape(vol,[np.prod(vol.shape[:3]),vol.shape[3]])uchar_array=numpy_support.numpy_to_vtk(vol,deep=0)im.GetPointData().SetScalars(uchar_array)ifaffineisNone:affine=np.eye(4)# Set the transform (identity if none given)transform=vtk.vtkTransform()transform_matrix=vtk.vtkMatrix4x4()transform_matrix.DeepCopy((affine[0][0],affine[0][1],affine[0][2],affine[0][3],affine[1][0],affine[1][1],affine[1][2],affine[1][3],affine[2][0],affine[2][1],affine[2][2],affine[2][3],affine[3][0],affine[3][1],affine[3][2],affine[3][3]))transform.SetMatrix(transform_matrix)transform.Inverse()# Set the reslicingimage_resliced=vtk.vtkImageReslice()set_input(image_resliced,im)image_resliced.SetResliceTransform(transform)image_resliced.AutoCropOutputOn()# Adding this will allow to support anisotropic voxels# and also gives the opportunity to slice per voxel coordinatesRZS=affine[:3,:3]zooms=np.sqrt(np.sum(RZS*RZS,axis=0))image_resliced.SetOutputSpacing(*zooms)image_resliced.SetInterpolationModeToLinear()image_resliced.Update()ex1,ex2,ey1,ey2,ez1,ez2=image_resliced.GetOutput().GetExtent()classImageActor(vtk.vtkImageActor):def__init__(self):self.picker=vtk.vtkCellPicker()definput_connection(self,output):self.GetMapper().SetInputConnection(output.GetOutputPort())self.output=outputself.shape=(ex2+1,ey2+1,ez2+1)defdisplay_extent(self,x1,x2,y1,y2,z1,z2):self.SetDisplayExtent(x1,x2,y1,y2,z1,z2)self.Update()defdisplay(self,x=None,y=None,z=None):ifxisNoneandyisNoneandzisNone:self.display_extent(ex1,ex2,ey1,ey2,ez2//2,ez2//2)ifxisnotNone:self.display_extent(x,x,ey1,ey2,ez1,ez2)ifyisnotNone:self.display_extent(ex1,ex2,y,y,ez1,ez2)ifzisnotNone:self.display_extent(ex1,ex2,ey1,ey2,z,z)defopacity(self,value):self.GetProperty().SetOpacity(value)deftolerance(self,value):self.picker.SetTolerance(value)defcopy(self):im_actor=ImageActor()im_actor.input_connection(self.output)im_actor.SetDisplayExtent(*self.GetDisplayExtent())im_actor.opacity(self.GetOpacity())im_actor.tolerance(self.picker.GetTolerance())ifinterpolation=='nearest':im_actor.SetInterpolate(False)else:im_actor.SetInterpolate(True)im_actor.GetMapper().BorderOn()returnim_actorimage_actor=ImageActor()ifnb_components==1:lut=lookup_colormapiflookup_colormapisNone:# Create a black/white lookup table.lut=colormap_lookup_table((0,255),(0,0),(0,0),(0,1))plane_colors=vtk.vtkImageMapToColors()plane_colors.SetLookupTable(lut)plane_colors.SetInputConnection(image_resliced.GetOutputPort())plane_colors.Update()image_actor.input_connection(plane_colors)else:image_actor.input_connection(image_resliced)image_actor.display()image_actor.opacity(opacity)image_actor.tolerance(picking_tol)ifinterpolation=='nearest':image_actor.SetInterpolate(False)else:image_actor.SetInterpolate(True)image_actor.GetMapper().BorderOn()returnimage_actor

[docs]defcontour_from_roi(data,affine=None,color=np.array([1,0,0]),opacity=1):"""Generate surface actor from a binary ROI. The color and opacity of the surface can be customized. Parameters ---------- data : array, shape (X, Y, Z) An ROI file that will be binarized and displayed. affine : array, shape (4, 4) Grid to space (usually RAS 1mm) transformation matrix. Default is None. If None then the identity matrix is used. color : (1, 3) ndarray RGB values in [0,1]. opacity : float Opacity of surface between 0 and 1. Returns ------- contour_assembly : vtkAssembly ROI surface object displayed in space coordinates as calculated by the affine parameter. """ifdata.ndim!=3:raiseValueError('Only 3D arrays are currently supported.')else:nb_components=1data=(data>0)*1vol=np.interp(data,xp=[data.min(),data.max()],fp=[0,255])vol=vol.astype('uint8')im=vtk.vtkImageData()di,dj,dk=vol.shape[:3]im.SetDimensions(di,dj,dk)voxsz=(1.,1.,1.)# im.SetOrigin(0,0,0)im.SetSpacing(voxsz[2],voxsz[0],voxsz[1])im.AllocateScalars(vtk.VTK_UNSIGNED_CHAR,nb_components)# copy datavol=np.swapaxes(vol,0,2)vol=np.ascontiguousarray(vol)ifnb_components==1:vol=vol.ravel()else:vol=np.reshape(vol,[np.prod(vol.shape[:3]),vol.shape[3]])uchar_array=numpy_support.numpy_to_vtk(vol,deep=0)im.GetPointData().SetScalars(uchar_array)ifaffineisNone:affine=np.eye(4)# Set the transform (identity if none given)transform=vtk.vtkTransform()transform_matrix=vtk.vtkMatrix4x4()transform_matrix.DeepCopy((affine[0][0],affine[0][1],affine[0][2],affine[0][3],affine[1][0],affine[1][1],affine[1][2],affine[1][3],affine[2][0],affine[2][1],affine[2][2],affine[2][3],affine[3][0],affine[3][1],affine[3][2],affine[3][3]))transform.SetMatrix(transform_matrix)transform.Inverse()# Set the reslicingimage_resliced=vtk.vtkImageReslice()set_input(image_resliced,im)image_resliced.SetResliceTransform(transform)image_resliced.AutoCropOutputOn()# Adding this will allow to support anisotropic voxels# and also gives the opportunity to slice per voxel coordinatesrzs=affine[:3,:3]zooms=np.sqrt(np.sum(rzs*rzs,axis=0))image_resliced.SetOutputSpacing(*zooms)image_resliced.SetInterpolationModeToLinear()image_resliced.Update()skin_extractor=vtk.vtkContourFilter()skin_extractor.SetInputData(image_resliced.GetOutput())skin_extractor.SetValue(0,1)skin_normals=vtk.vtkPolyDataNormals()skin_normals.SetInputConnection(skin_extractor.GetOutputPort())skin_normals.SetFeatureAngle(60.0)skin_mapper=vtk.vtkPolyDataMapper()skin_mapper.SetInputConnection(skin_normals.GetOutputPort())skin_mapper.ScalarVisibilityOff()skin_actor=vtk.vtkActor()skin_actor.SetMapper(skin_mapper)skin_actor.GetProperty().SetOpacity(opacity)skin_actor.GetProperty().SetColor(color[0],color[1],color[2])returnskin_actor

[docs]defstreamtube(lines,colors=None,opacity=1,linewidth=0.1,tube_sides=9,lod=True,lod_points=10**4,lod_points_size=3,spline_subdiv=None,lookup_colormap=None):"""Use streamtubes to visualize polylines Parameters ---------- lines : list list of N curves represented as 2D ndarrays colors : array (N, 3), list of arrays, tuple (3,), array (K,), None If None then a standard orientation colormap is used for every line. If one tuple of color is used. Then all streamlines will have the same colour. If an array (N, 3) is given, where N is equal to the number of lines. Then every line is coloured with a different RGB color. If a list of RGB arrays is given then every point of every line takes a different color. If an array (K, ) is given, where K is the number of points of all lines then these are considered as the values to be used by the colormap. If an array (L, ) is given, where L is the number of streamlines then these are considered as the values to be used by the colormap per streamline. If an array (X, Y, Z) or (X, Y, Z, 3) is given then the values for the colormap are interpolated automatically using trilinear interpolation. opacity : float Takes values from 0 (fully transparent) to 1 (opaque). Default is 1. linewidth : float Default is 0.01. tube_sides : int Default is 9. lod : bool Use vtkLODActor(level of detail) rather than vtkActor. Default is True. Level of detail actors do not render the full geometry when the frame rate is low. lod_points : int Number of points to be used when LOD is in effect. Default is 10000. lod_points_size : int Size of points when lod is in effect. Default is 3. spline_subdiv : int Number of splines subdivision to smooth streamtubes. Default is None. lookup_colormap : vtkLookupTable Add a default lookup table to the colormap. Default is None which calls :func:`fury.actor.colormap_lookup_table`. Examples -------- >>> import numpy as np >>> from fury import actor, window >>> scene = window.Scene() >>> lines = [np.random.rand(10, 3), np.random.rand(20, 3)] >>> colors = np.random.rand(2, 3) >>> c = actor.streamtube(lines, colors) >>> scene.add(c) >>> #window.show(scene) Notes ----- Streamtubes can be heavy on GPU when loading many streamlines and therefore, you may experience slow rendering time depending on system GPU. A solution to this problem is to reduce the number of points in each streamline. In Dipy we provide an algorithm that will reduce the number of points on the straighter parts of the streamline but keep more points on the curvier parts. This can be used in the following way:: from dipy.tracking.distances import approx_polygon_track lines = [approx_polygon_track(line, 0.2) for line in lines] Alternatively we suggest using the ``line`` actor which is much more efficient. See Also -------- :func:`fury.actor.line` """# Poly data with lines and colorspoly_data,is_colormap=lines_to_vtk_polydata(lines,colors)next_input=poly_data# Set Normalspoly_normals=set_input(vtk.vtkPolyDataNormals(),next_input)poly_normals.ComputeCellNormalsOn()poly_normals.ComputePointNormalsOn()poly_normals.ConsistencyOn()poly_normals.AutoOrientNormalsOn()poly_normals.Update()next_input=poly_normals.GetOutputPort()# Spline interpolationif(spline_subdivisnotNone)and(spline_subdiv>0):spline_filter=set_input(vtk.vtkSplineFilter(),next_input)spline_filter.SetSubdivideToSpecified()spline_filter.SetNumberOfSubdivisions(spline_subdiv)spline_filter.Update()next_input=spline_filter.GetOutputPort()# Add thickness to the resulting linestube_filter=set_input(vtk.vtkTubeFilter(),next_input)tube_filter.SetNumberOfSides(tube_sides)tube_filter.SetRadius(linewidth)# TODO using the line above we will be able to visualize# streamtubes of varying radius# tube_filter.SetVaryRadiusToVaryRadiusByScalar()tube_filter.CappingOn()tube_filter.Update()next_input=tube_filter.GetOutputPort()# Poly mapperpoly_mapper=set_input(vtk.vtkPolyDataMapper(),next_input)poly_mapper.ScalarVisibilityOn()poly_mapper.SetScalarModeToUsePointFieldData()poly_mapper.SelectColorArray("Colors")poly_mapper.Update()# Color Scale with a lookup tableifis_colormap:iflookup_colormapisNone:lookup_colormap=colormap_lookup_table()poly_mapper.SetLookupTable(lookup_colormap)poly_mapper.UseLookupTableScalarRangeOn()poly_mapper.Update()# Set Actoriflod:actor=vtk.vtkLODActor()actor.SetNumberOfCloudPoints(lod_points)actor.GetProperty().SetPointSize(lod_points_size)else:actor=vtk.vtkActor()actor.SetMapper(poly_mapper)actor.GetProperty().SetInterpolationToPhong()actor.GetProperty().BackfaceCullingOn()actor.GetProperty().SetOpacity(opacity)returnactor

[docs]defline(lines,colors=None,opacity=1,linewidth=1,spline_subdiv=None,lod=True,lod_points=10**4,lod_points_size=3,lookup_colormap=None,depth_cue=False,fake_tube=False):""" Create an actor for one or more lines. Parameters ------------ lines : list of arrays colors : array (N, 3), list of arrays, tuple (3,), array (K,), None If None then a standard orientation colormap is used for every line. If one tuple of color is used. Then all streamlines will have the same colour. If an array (N, 3) is given, where N is equal to the number of lines. Then every line is coloured with a different RGB color. If a list of RGB arrays is given then every point of every line takes a different color. If an array (K, ) is given, where K is the number of points of all lines then these are considered as the values to be used by the colormap. If an array (L, ) is given, where L is the number of streamlines then these are considered as the values to be used by the colormap per streamline. If an array (X, Y, Z) or (X, Y, Z, 3) is given then the values for the colormap are interpolated automatically using trilinear interpolation. opacity : float, optional Takes values from 0 (fully transparent) to 1 (opaque). Default is 1. linewidth : float, optional Line thickness. Default is 1. spline_subdiv : int, optional Number of splines subdivision to smooth streamtubes. Default is None which means no subdivision. lod : bool Use vtkLODActor(level of detail) rather than vtkActor. Default is True. Level of detail actors do not render the full geometry when the frame rate is low. lod_points : int Number of points to be used when LOD is in effect. Default is 10000. lod_points_size : int Size of points when lod is in effect. Default is 3. lookup_colormap : bool, optional Add a default lookup table to the colormap. Default is None which calls :func:`fury.actor.colormap_lookup_table`. depth_cue : boolean Add a size depth cue so that lines shrink with distance to the camera. Works best with linewidth <= 1. fake_tube: boolean Add shading to lines to approximate the look of tubes. Returns ---------- v : vtkActor or vtkLODActor object Line. Examples ---------- >>> from fury import actor, window >>> scene = window.Scene() >>> lines = [np.random.rand(10, 3), np.random.rand(20, 3)] >>> colors = np.random.rand(2, 3) >>> c = actor.line(lines, colors) >>> scene.add(c) >>> #window.show(scene) """# Poly data with lines and colorspoly_data,is_colormap=lines_to_vtk_polydata(lines,colors)next_input=poly_data# use spline interpolationif(spline_subdivisnotNone)and(spline_subdiv>0):spline_filter=set_input(vtk.vtkSplineFilter(),next_input)spline_filter.SetSubdivideToSpecified()spline_filter.SetNumberOfSubdivisions(spline_subdiv)spline_filter.Update()next_input=spline_filter.GetOutputPort()poly_mapper=set_input(vtk.vtkPolyDataMapper(),next_input)poly_mapper.ScalarVisibilityOn()poly_mapper.SetScalarModeToUsePointFieldData()poly_mapper.SelectColorArray("Colors")poly_mapper.Update()ifdepth_cue:poly_mapper.SetGeometryShaderCode(fury.shaders.load("line.geom"))@vtk.calldata_type(vtk.VTK_OBJECT)defvtkShaderCallback(caller,event,calldata=None):program=calldataifprogramisnotNone:program.SetUniformf("linewidth",linewidth)poly_mapper.AddObserver(vtk.vtkCommand.UpdateShaderEvent,vtkShaderCallback)# Color Scale with a lookup tableifis_colormap:iflookup_colormapisNone:lookup_colormap=colormap_lookup_table()poly_mapper.SetLookupTable(lookup_colormap)poly_mapper.UseLookupTableScalarRangeOn()poly_mapper.Update()# Set Actoriflod:actor=vtk.vtkLODActor()actor.SetNumberOfCloudPoints(lod_points)actor.GetProperty().SetPointSize(lod_points_size)else:actor=vtk.vtkActor()actor.SetMapper(poly_mapper)actor.GetProperty().SetLineWidth(linewidth)actor.GetProperty().SetOpacity(opacity)iffake_tube:actor.GetProperty().SetRenderLinesAsTubes(True)returnactor

[docs]classContainer(object):""" Provides functionalities for grouping multiple actors using a given layout. Attributes ---------- anchor : 3-tuple of float Anchor of this container used when laying out items in a container. The anchor point is relative to the center of the container. Default: (0, 0, 0). padding : 6-tuple of float Padding around this container bounding box. The 6-tuple represents (pad_x_neg, pad_x_pos, pad_y_neg, pad_y_pos, pad_z_neg, pad_z_pos). Default: (0, 0, 0, 0, 0, 0) """

[docs]def__init__(self,layout=layout.Layout()):""" Parameters ---------- layout : ``fury.layout.Layout`` object Items of this container will be arranged according to `layout`. """self.layout=layoutself._items=[]self._need_update=Trueself._position=np.zeros(3)self._visibility=Trueself.anchor=np.zeros(3)self.padding=np.zeros(6)

[docs]defadd(self,*items,**kwargs):""" Adds some items to this container. Parameters ---------- items : `vtkProp3D` objects Items to add to this container. borrow : bool If True the items are added as-is, otherwise a shallow copy is made first. If you intend to reuse the items elsewhere you should set `borrow=False`. Default: True. """self._need_update=Trueforiteminitems:ifnotkwargs.get('borrow',True):item=shallow_copy(item)self._items.append(item)

[docs]defclear(self):""" Clears all items of this container. """self._need_update=Truedelself._items[:]

[docs]defupdate(self):""" Updates the position of the items of this container. """self.layout.apply(self._items)self._need_update=False

[docs]defadd_to_scene(self,ren):""" Adds the items of this container to a given renderer. """foriteminself.items:ifisinstance(item,Container):item.add_to_scene(ren)else:ren.add(item)

[docs]defgrid(actors,captions=None,caption_offset=(0,-100,0),cell_padding=0,cell_shape="rect",aspect_ratio=16/9.,dim=None):""" Creates a grid of actors that lies in the xy-plane. Parameters ---------- actors : list of `vtkProp3D` objects Actors to be layout in a grid manner. captions : list of `vtkProp3D` objects Objects serving as captions (can be any `vtkProp3D` object, not necessarily text). There should be one caption per actor. By default, there are no captions. caption_offset : tuple of float (optional) Tells where to position the caption w.r.t. the center of its associated actor. Default: (0, -100, 0). cell_padding : tuple of 2 floats or float Each grid cell will be padded according to (pad_x, pad_y) i.e. horizontally and vertically. Padding is evenly distributed on each side of the cell. If a single float is provided then both pad_x and pad_y will have the same value. cell_shape : str Specifies the desired shape of every grid cell. 'rect' ensures the cells are the tightest. 'square' ensures the cells are as wide as high. 'diagonal' ensures the content of the cells can be rotated without colliding with content of the neighboring cells. aspect_ratio : float Aspect ratio of the grid (width/height). Default: 16:9. dim : tuple of int Dimension (nb_rows, nb_cols) of the grid. If provided, `aspect_ratio` will be ignored. Returns ------- ``fury.actor.Container`` object Object that represents the grid containing all the actors and captions, if any. """grid_layout=layout.GridLayout(cell_padding=cell_padding,cell_shape=cell_shape,aspect_ratio=aspect_ratio,dim=dim)grid=Container(layout=grid_layout)ifcaptionsisnotNone:actors_with_caption=[]foractor,captioninzip(actors,captions):actor_center=np.array(actor.GetCenter())# Offset accordingly the caption w.r.t.# the center of the associated actor.caption=shallow_copy(caption)caption.SetPosition(actor_center+caption_offset)actor_with_caption=Container()actor_with_caption.add(actor,caption)# We change the anchor of the container so# the actor will be centered in the# grid cell.actor_with_caption.anchor=actor_center- \
actor_with_caption.GetCenter()actors_with_caption.append(actor_with_caption)actors=actors_with_captiongrid.add(*actors)returngrid