def circleForTrajectory(point, direction, index=None): colors = vtk.vtkNamedColors() prop_assembly = vtk.vtkPropAssembly() source = vtk.vtkSphereSource() if direction == "left": point[0] = point[0] + 1.37 point[2] = point[2] + 1.37 source.SetCenter(point) source.SetRadius(0.09) # source.SetRadius(0.75) source.Update() circle_mapper = vtk.vtkPolyDataMapper() circle_mapper.SetInputData(source.GetOutput()) circle_mapper.Update() circle_actor = vtk.vtkActor() circle_actor.SetMapper(circle_mapper) circle_actor.GetProperty().SetColor(colors.GetColor3ub('Red')) #Color red if index == 0: circle_actor.GetProperty().SetColor(colors.GetColor3ub('Blue')) prop_assembly = vtk.vtkPropAssembly() prop_assembly.AddPart(circle_actor) return prop_assembly
def __create_box(self): xi = yi = 0.1 xf = yf = 200 line_i = vtk.vtkLineSource() line_i.SetPoint1((xi, yi, 0)) line_i.SetPoint2((xf, yi, 0)) self.line_i = line_i self.line_i_actor = self.__create_line_actor(line_i) line_s = vtk.vtkLineSource() line_s.SetPoint1((xi, yf, 0)) line_s.SetPoint2((xf, yf, 0)) self.line_s = line_s self.line_s_actor = self.__create_line_actor(line_s) line_l = vtk.vtkLineSource() line_l.SetPoint1((xi, yi, 0)) line_l.SetPoint2((xi, yf, 0)) self.line_l = line_l self.line_l_actor = self.__create_line_actor(line_l) line_r = vtk.vtkLineSource() line_r.SetPoint1((xf, yi, 0)) line_r.SetPoint2((xf, yf, 0)) self.line_r = line_r self.line_r_actor = self.__create_line_actor(line_r) box_actor = vtk.vtkPropAssembly() box_actor.AddPart(self.line_i_actor) box_actor.AddPart(self.line_s_actor) box_actor.AddPart(self.line_l_actor) box_actor.AddPart(self.line_r_actor) self.box_actor = box_actor
def create_axes_orientation_box(line_width=1, text_scale=0.366667, edge_color='black', x_color='lightblue', y_color='seagreen', z_color='tomato', x_face_color=(255, 0, 0), y_face_color=(0, 255, 0), z_face_color=(0, 0, 255), color_box=False): """Create a Box axes orientation widget with labels. """ axes_actor = vtk.vtkAnnotatedCubeActor() axes_actor.SetFaceTextScale(text_scale) axes_actor.SetXPlusFaceText("X+") axes_actor.SetXMinusFaceText("X-") axes_actor.SetYPlusFaceText("Y+") axes_actor.SetYMinusFaceText("Y-") axes_actor.SetZPlusFaceText("Z+") axes_actor.SetZMinusFaceText("Z-") axes_actor.GetTextEdgesProperty().SetColor(parse_color(edge_color)) axes_actor.GetTextEdgesProperty().SetLineWidth(line_width) axes_actor.GetXPlusFaceProperty().SetColor(parse_color(x_color)) axes_actor.GetXMinusFaceProperty().SetColor(parse_color(x_color)) axes_actor.GetYPlusFaceProperty().SetColor(parse_color(y_color)) axes_actor.GetYMinusFaceProperty().SetColor(parse_color(y_color)) axes_actor.GetZPlusFaceProperty().SetColor(parse_color(z_color)) axes_actor.GetZMinusFaceProperty().SetColor(parse_color(z_color)) if color_box: # Hide the cube so we can color each face axes_actor.GetCubeProperty().SetOpacity(0) cube = pyvista.Cube() cube.clear_arrays() # remove normals face_colors = np.array([x_face_color, x_face_color, y_face_color, y_face_color, z_face_color, z_face_color, ], dtype=np.uint8) cube.cell_arrays['face_colors'] = face_colors cube_mapper = vtk.vtkPolyDataMapper() cube_mapper.SetInputData(cube) cube_mapper.SetColorModeToDirectScalars() cube_mapper.Update() cube_actor = vtk.vtkActor() cube_actor.SetMapper(cube_mapper) cube_actor.GetProperty().BackfaceCullingOn() prop_assembly = vtk.vtkPropAssembly() prop_assembly.AddPart(axes_actor) prop_assembly.AddPart(cube_actor) actor = prop_assembly else: actor = axes_actor return actor
def pointer(x, y, z, radius): # cast the positions to text so they can be added as labels labelX = str(x) labelY = str(y) labelZ = str(z) # Create sphere sphere_source = vtk.vtkSphereSource() sphere_source.SetCenter(x, y, z) sphere_source.SetRadius(radius) sphere_source.Update() # Create the caption to show the sphere position caption = vtk.vtkCaptionActor2D() caption.SetCaption("(" + labelX + ", " + labelY + ", " + labelZ + ")") # Set the size of the caption box. The box is measured from the lower left corner to the upper right corner. # SetWidth and SetHeight are defined as fraction of the viewport. So SetWidth(0.1) sets the caption box # to 10% the width of the viewport. # The caption text will then fill the provided caption box as best possible caption.SetWidth(0.15) caption.SetHeight(0.02) caption.GetProperty().SetColor(colours['captionColour']) caption.SetAttachmentPoint(sphere_source.GetCenter()) # Formatting of the text possible with vtkTextProperty # Disable the border box for the caption caption.BorderOff() # Map texture coordinates of the cube_source map_to_plane = vtk.vtkTextureMapToPlane() map_to_plane.SetInputConnection(sphere_source.GetOutputPort()) # Create polydatamapper and set the mapped texture as input mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(map_to_plane.GetOutputPort()) # Create actor and set the mapper and the texture . uncomment if no texture # mapper = vtk.vtkPolyDataMapper() # mapper.SetInputConnection(cube_source.GetOutputPort()) mapper.Update() # create the sphere actor with the mapper sphere = vtk.vtkActor() sphere.SetMapper(mapper) sphere.GetProperty().SetColor(colours['pointer']) # Assemble the cube and annotations into a complete prop actor. pointer = vtk.vtkPropAssembly() pointer.AddPart(sphere) pointer.AddPart(caption) # actor.SetTexture(texture) return pointer
def addaxes(): arrowx=addarrow(color=(1,0,0)) arrowy=addarrow(color=(0,1,0)) arrowz=addarrow(color=(0,0,1)) arrowy.RotateZ(90) arrowz.RotateY(-90) ass=vtk.vtkPropAssembly() ass.AddPart(arrowx) ass.AddPart(arrowy) ass.AddPart(arrowz) return ass
def __init__(self, iren): # super(Marker, self).__init__() self.axes_actor = Axes().axes self.cube_actor = Cube().cube self.assembly = vtk.vtkPropAssembly() self.assembly.AddPart(self.axes_actor) self.assembly.AddPart(self.cube_actor) self.marker = vtk.vtkOrientationMarkerWidget() self.marker.SetOutlineColor(0.93, 0.57, 0.13) self.marker.SetOrientationMarker(self.assembly) # self.marker.SetViewport(0.0, 0.0, 0.15, 0.3) self.marker.SetInteractor(iren)
def MakeCubeActor(scale, xyzLabels, colors): """ :param scale: Sets the scale and direction of the axes. :param xyzLabels: Labels for the axes. :param colors: Used to set the colors of the cube faces. :return: The combined axes and annotated cube prop. """ # We are combining a vtk.vtkAxesActor and a vtk.vtkAnnotatedCubeActor # into a vtk.vtkPropAssembly cube = MakeAnnotatedCubeActor(colors) axes = MakeAxesActor(scale, xyzLabels) # Combine orientation markers into one with an assembly. assembly = vtk.vtkPropAssembly() assembly.AddPart(axes) assembly.AddPart(cube) return assembly
def get_wall_actors(renderers, blocks): # Returns a list of just the actor components from the wall cube props # Setup the list to collect the actors actorsList = [] # A vtkPropCollection, populate it with the props from the blocks renderer propCollection = vtkPropCollection() propCollection = renderers[blocks].GetViewProps() # Get the number of props so we know how many items to iterate over numberProps = propCollection.GetNumberOfItems() # Initiate traversal over the collection propCollection.InitTraversal() # Now iterate over each of the props for prop in range(numberProps): # Move to the next prop in the collection and get the number of actors in that prop currentProp = propCollection.GetNextProp() # We're just interested in wall objects, not floor objects # So only scan this prop further if it is a prop and not an actor typeBool = currentProp.IsTypeOf("vtkPropAssembly") if typeBool == 1: # The prop doesn't list any positional attributes so we're going to need to loop over the component actors to find the cube actor which does have positional attributes # Get the number of actors in this prop so we know how many iterations to make numberOfActors = currentProp.GetNumberOfPaths() # Setup a vtkPropAssembly to store the assembly of parts that make up the current prop, and populate it actorCollection = vtkPropAssembly() actorCollection = currentProp.GetParts() # and initiate traversal over the collection of parts/actors actorCollection.InitTraversal() for actor in range(numberOfActors): # Now iterate over each actor. # Move to the next actor in the collection. currentActor = actorCollection.GetNextProp() # Check if the actor is an OpenGL type, which is used for the wall and floor objects, as opposed to a CaptionActor type which is the component used for the captioning # method returns a 1 if the type of the actor matches the argument, otherwise returns a 0 typeBool = currentActor.IsTypeOf("vtkOpenGLActor") if typeBool == 1: # This actor is a wall or floor actor # check the height of the actor ... if it's less than 1 then this actor is floor actorHeight = currentActor.GetBounds( )[3] - currentActor.GetBounds()[2] if actorHeight >= 1: # This is a wall actor actorsList.append(currentActor) return actorsList
def cubeForPath(point): colors = vtk.vtkNamedColors() prop_assembly = vtk.vtkPropAssembly() direction = point[3] cube_source = vtk.vtkCubeSource() cube_source.SetCenter((point[0] + 0.49, point[1] + 0.49, point[2] + 0.49)) cube_source.Update() face_colors = vtk.vtkUnsignedCharArray() face_colors.SetNumberOfComponents(3) if direction == "top": cube_source.SetXLength(0.25) cube_source.SetYLength(0.25) cube_source.SetZLength(1.1) face_x_plus = colors.GetColor3ub('DarkGreen') face_x_minus = colors.GetColor3ub('DarkGreen') face_y_plus = colors.GetColor3ub('DarkGreen') face_y_minus = colors.GetColor3ub('DarkGreen') face_z_plus = colors.GetColor3ub('Cyan') face_z_minus = colors.GetColor3ub('DarkGreen') if direction == "bottom": face_x_plus = colors.GetColor3ub('DarkGreen') face_x_minus = colors.GetColor3ub('DarkGreen') face_y_plus = colors.GetColor3ub('DarkGreen') face_y_minus = colors.GetColor3ub('DarkGreen') face_z_plus = colors.GetColor3ub('DarkGreen') face_z_minus = colors.GetColor3ub('Cyan') if direction == "right": face_x_plus = colors.GetColor3ub('Cyan') face_x_minus = colors.GetColor3ub('DarkGreen') face_y_plus = colors.GetColor3ub('DarkGreen') face_y_minus = colors.GetColor3ub('DarkGreen') face_z_plus = colors.GetColor3ub('DarkGreen') face_z_minus = colors.GetColor3ub('DarkGreen') if direction == "left": cube_source.SetXLength(1) cube_source.SetYLength(0.25) cube_source.SetZLength(0.25) face_x_plus = colors.GetColor3ub('DarkGreen') face_x_minus = colors.GetColor3ub('Cyan') face_y_plus = colors.GetColor3ub('DarkGreen') face_y_minus = colors.GetColor3ub('DarkGreen') face_z_plus = colors.GetColor3ub('DarkGreen') face_z_minus = colors.GetColor3ub('DarkGreen') if direction == "front": face_x_plus = colors.GetColor3ub('DarkGreen') face_x_minus = colors.GetColor3ub('DarkGreen') face_y_plus = colors.GetColor3ub('DarkGreen') face_y_minus = colors.GetColor3ub('Cyan') face_z_plus = colors.GetColor3ub('DarkGreen') face_z_minus = colors.GetColor3ub('DarkGreen') if direction == "back": face_x_plus = colors.GetColor3ub('DarkGreen') face_x_minus = colors.GetColor3ub('DarkGreen') face_y_plus = colors.GetColor3ub('Cyan') face_y_minus = colors.GetColor3ub('DarkGreen') face_z_plus = colors.GetColor3ub('DarkGreen') face_z_minus = colors.GetColor3ub('DarkGreen') face_colors.InsertNextTypedTuple(face_x_minus) face_colors.InsertNextTypedTuple(face_x_plus) face_colors.InsertNextTypedTuple(face_y_minus) face_colors.InsertNextTypedTuple(face_y_plus) face_colors.InsertNextTypedTuple(face_z_minus) face_colors.InsertNextTypedTuple(face_z_plus) cube_source.GetOutput().GetCellData().SetScalars(face_colors) cube_source.Update() cube_mapper = vtk.vtkPolyDataMapper() cube_mapper.SetInputData(cube_source.GetOutput()) cube_mapper.Update() cube_actor = vtk.vtkActor() cube_actor.SetMapper(cube_mapper) # Assemble the colored cube and annotated cube texts into a composite prop. prop_assembly = vtk.vtkPropAssembly() prop_assembly.AddPart(cube_actor) return prop_assembly
def plot_fermisurface(data, equivalences, ebands, mu, nworkers=1): """Launch an interactive VTK representation of the Fermi surface. Make sure to check the module-level variable "available" before calling this function. Args: data: a DFTData object equivalences: list of k-point equivalence classes ebands: eband: (nbands, nkpoints) array with the band energies mu: initial value of the energy at which the surface will be plotted, with respect to data.fermi. This can later be changed by the user using an interactive slider. nworkers: number of worker processes to use for the band reconstruction Returns: None. """ lattvec = data.get_lattvec() rlattvec = 2. * np.pi * la.inv(lattvec).T # Obtain the first Brillouin zone as the Voronoi polyhedron of Gamma points = [] for ijk0 in itertools.product(range(5), repeat=3): ijk = [i if i <= 2 else i - 5 for i in ijk0] points.append(rlattvec @ np.array(ijk)) voronoi = scipy.spatial.Voronoi(points) region_index = voronoi.point_region[0] vertex_indices = voronoi.regions[region_index] vertices = voronoi.vertices[vertex_indices, :] # Compute a center and an outward-pointing normal for each of the facets # of the BZ facets = [] for ridge in voronoi.ridge_vertices: if all(i in vertex_indices for i in ridge): facets.append(ridge) centers = [] normals = [] for f in facets: corners = np.array([voronoi.vertices[i, :] for i in f]) center = corners.mean(axis=0) v1 = corners[0, :] for i in range(1, corners.shape[0]): v2 = corners[i, :] prod = np.cross(v1 - center, v2 - center) if not np.allclose(prod, 0.): break if np.dot(center, prod) < 0.: prod = -prod centers.append(center) normals.append(prod) # Get the extent of the regular grid in reciprocal space hdims = np.max(np.abs(np.vstack(equivalences)), axis=0) dims = 2 * hdims + 1 class PointPickerInteractorStyle(vtk.vtkInteractorStyleTrackballCamera): """Custom interaction style enabling the user to pick points on the screen. """ def __init__(self, parent=None): """Simple constructor that adds an observer to the middle mouse button press. """ self.AddObserver("MiddleButtonPressEvent", self.pick_point) def pick_point(self, obj, event): """Get the coordinates of the point selected with the middle mouse button, find the nearest data point, and print its direct coordinates. """ interactor = self.GetInteractor() picker = interactor.GetPicker() pos = interactor.GetEventPosition() picker.Pick( pos[0], pos[1], 0, interactor.GetRenderWindow().GetRenderers().GetFirstRenderer()) picked = np.array(picker.GetPickPosition()) # Move the sphere to the new coordinates and make it visible sphere.SetCenter(*picked.tolist()) sphere_actor.VisibilityOn() picked = la.solve(rlattvec, picked) print("Point picked:", picked) self.OnMiddleButtonDown() # Create the VTK representation of the grid sgrid = vtk.vtkStructuredGrid() sgrid.SetDimensions(*dims) spoints = vtk.vtkPoints() for ijk0 in itertools.product(*(range(0, d) for d in dims)): ijk = [ ijk0[i] if ijk0[i] <= hdims[i] else ijk0[i] - dims[i] for i in range(len(dims)) ] abc = np.array(ijk, dtype=np.float64) / np.array(dims) xyz = rlattvec @ abc spoints.InsertNextPoint(*xyz.tolist()) sgrid.SetPoints(spoints) # Find the shortest distance between points to compute a good # radius for the selector sphere later. dmin = np.infty for i in range(3): abc = np.zeros(3) abc[i] = 1. / dims[i] xyz = rlattvec @ abc dmin = min(dmin, la.norm(xyz)) ebands -= data.fermi emax = ebands.max(axis=1) emin = ebands.min(axis=1) # Remove all points outside the BZ for i, ijk0 in enumerate(itertools.product(*(range(0, d) for d in dims))): ijk = [ ijk0[j] if ijk0[j] <= hdims[j] else ijk0[j] - dims[j] for j in range(len(dims)) ] abc = np.array(ijk, dtype=np.float64) / np.array(dims) xyz = rlattvec @ abc for c, n in zip(centers, normals): if np.dot(xyz - c, n) > 0.: ebands[:, i] = np.nan break # Create a 2D chemical potential slider slider = vtk.vtkSliderRepresentation2D() slider.SetMinimumValue(emin.min()) slider.SetMaximumValue(emax.max()) slider.SetValue(mu) slider.SetTitleText("Chemical potential") slider.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay() slider.GetPoint1Coordinate().SetValue(0.1, 0.9) slider.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay() slider.GetPoint2Coordinate().SetValue(0.9, 0.9) slider.GetTubeProperty().SetColor(*colors.hex2color("#2e3436")) slider.GetSliderProperty().SetColor(*colors.hex2color("#a40000")) slider.GetCapProperty().SetColor(*colors.hex2color("#babdb6")) slider.GetSelectedProperty().SetColor(*colors.hex2color("#a40000")) slider.GetTitleProperty().SetColor(*colors.hex2color("#2e3436")) # Find all the isosurfaces with energy equal to the threshold allcontours = [] with TimerContext() as timer: fermiactors = [] for band in ebands: sgridp = vtk.vtkStructuredGrid() sgridp.DeepCopy(sgrid) # Feed the energies to VTK scalar = vtk.vtkFloatArray() for i in band: scalar.InsertNextValue(i) sgridp.GetPointData().SetScalars(scalar) # Estimate the isosurfaces contours = vtk.vtkMarchingContourFilter() contours.SetInputData(sgridp) contours.UseScalarTreeOn() contours.SetValue(0, mu) contours.ComputeNormalsOff() contours.ComputeGradientsOff() allcontours.append(contours) # Use vtkStrippers to plot the surfaces faster stripper = vtk.vtkStripper() stripper.SetInputConnection(contours.GetOutputPort()) # Compute the normals to the surfaces to obtain better lighting normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(stripper.GetOutputPort()) normals.ComputeCellNormalsOn() normals.ComputePointNormalsOn() # Create a mapper and an actor for the surfaces mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(normals.GetOutputPort()) mapper.ScalarVisibilityOff() fermiactors.append(vtk.vtkActor()) fermiactors[-1].SetMapper(mapper) fermiactors[-1].GetProperty().SetColor(*colors.hex2color( "#a40000")) deltat = timer.get_deltat() info("building the surfaces took {:.3g} s".format(deltat)) # Represent the BZ as a polyhedron in VTK points = vtk.vtkPoints() for v in voronoi.vertices: points.InsertNextPoint(*v) fids = vtk.vtkIdList() fids.InsertNextId(len(facets)) for f in facets: fids.InsertNextId(len(f)) for i in f: fids.InsertNextId(i) fgrid = vtk.vtkUnstructuredGrid() fgrid.SetPoints(points) fgrid.InsertNextCell(vtk.VTK_POLYHEDRON, fids) # Create an actor and a mapper for the BZ mapper = vtk.vtkDataSetMapper() mapper.SetInputData(fgrid) bzactor = vtk.vtkActor() bzactor.SetMapper(mapper) bzactor.GetProperty().SetColor(*colors.hex2color("#204a87")) bzactor.GetProperty().SetOpacity(0.2) # Create a visual representation of the selected point, and hide # it for the time being. sphere = vtk.vtkSphereSource() sphere.SetRadius(dmin / 2.) sphere_mapper = vtk.vtkPolyDataMapper() sphere_mapper.SetInputConnection(sphere.GetOutputPort()) sphere_mapper.ScalarVisibilityOff() sphere_actor = vtk.vtkActor() sphere_actor.SetMapper(sphere_mapper) sphere_actor.GetProperty().SetColor(*colors.hex2color("#f57900")) sphere_actor.VisibilityOff() # Create a VTK window and other elements of an interactive scene renderer = vtk.vtkRenderer() renderer.AddActor(bzactor) renderer.AddActor(sphere_actor) for f in fermiactors: renderer.AddActor(f) renderer.ResetCamera() renderer.GetActiveCamera().Zoom(5.) renderer.SetBackground(1., 1., 1.) window = vtk.vtkRenderWindow() window.AddRenderer(renderer) interactor = vtk.vtkRenderWindowInteractor() interactor.SetInteractorStyle(PointPickerInteractorStyle()) interactor.SetRenderWindow(window) # Add a set of axes axes = vtk.vtkAxesActor() assembly = vtk.vtkPropAssembly() assembly.AddPart(axes) marker = vtk.vtkOrientationMarkerWidget() marker.SetOrientationMarker(assembly) marker.SetInteractor(interactor) marker.SetEnabled(1) marker.InteractiveOff() def callback(obj, ev): """Update the isosurface with a new value""" mu = obj.GetRepresentation().GetValue() for e, E, c, a in zip(emin, emax, allcontours, fermiactors): visible = e <= mu and E >= mu a.SetVisibility(visible) if visible: c.SetValue(0, mu) # Add the slider widget widget = vtk.vtkSliderWidget() widget.SetInteractor(interactor) widget.SetRepresentation(slider) widget.SetAnimationModeToJump() widget.EnabledOn() widget.AddObserver(vtk.vtkCommand.InteractionEvent, callback) # Launch the visualization interactor.Initialize() window.Render() interactor.Start()
#top part cylinderMapper = vtk.vtkPolyDataMapper() cylinderMapper.SetInputConnection(cylinder.GetOutputPort()) cylinderActor = vtk.vtkActor() cylinderActor.SetMapper(cylinderMapper) cylinderActor.GetProperty().SetColor(1, 0, 0) compositeAssembly = vtk.vtkAssembly() compositeAssembly.AddPart(cylinderActor) compositeAssembly.AddPart(sphereActor) compositeAssembly.AddPart(cubeActor) compositeAssembly.AddPart(coneActor) compositeAssembly.SetOrigin(5, 10, 15) compositeAssembly.AddPosition(5, 0, 0) compositeAssembly.RotateX(15) # Build the prop assembly out of a vtkActor and a vtkAssembly assembly = vtk.vtkPropAssembly() assembly.AddPart(compositeAssembly) assembly.AddPart(coneActor) # Create the RenderWindow, Renderer and both Actors # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size # ren1.AddViewProp(assembly) ren1.SetBackground(0.1, 0.2, 0.4) renWin.SetSize(300, 300) # Get handles to some useful objects
def display(image, image_pos_pat, image_ori_pat): global xMin, xMax, yMin, yMax, zMin, zMax, xSpacing, ySpacing, zSpacing, interactor, actions, reslice, interactorStyle # The box widget observes the events invoked by the render window # interactor. These events come from user interaction in the render # window. # boxWidget = vtk.vtkBoxWidget() # boxWidget.SetInteractor(iren1) # boxWidget.SetPlaceFactor(1) # Initialize Image orienation IO = matrix( [[0, 0,-1, 0], [1, 0, 0, 0], [0,-1, 0, 0], [0, 0, 0, 1]]) # Assign the 6-Image orientation patient coordinates (from Dicomtags) IO[0,0] = image_ori_pat[0]; IO[1,0] = image_ori_pat[1]; IO[2,0] = image_ori_pat[2]; IO[0,1] = image_ori_pat[3]; IO[1,1] = image_ori_pat[4]; IO[2,1] = image_ori_pat[5]; # obtain thrid column as the cross product of column 1 y 2 IO_col1 = [image_ori_pat[0], image_ori_pat[1], image_ori_pat[2]] IO_col2 = [image_ori_pat[3], image_ori_pat[4], image_ori_pat[5]] IO_col3 = cross(IO_col1, IO_col2) # assign column 3 IO[0,2] = IO_col3[0]; IO[1,2] = IO_col3[1]; IO[2,2] = IO_col3[2]; IP = array([0, 0, 0, 1]) # Initialization Image Position IP[0] = image_pos_pat[0]; IP[1] = image_pos_pat[1]; IP[2] = image_pos_pat[2]; IO[0,3] = image_pos_pat[0]; IO[1,3] = image_pos_pat[1]; IO[2,3] = image_pos_pat[2] print "image_pos_pat :" print image_pos_pat print "image_ori_pat:" print image_ori_pat origin = IP*IO.I print "Volume Origin:" print origin[0,0], origin[0,1], origin[0,2] # Create matrix 4x4 DICOM_mat = vtk.vtkMatrix4x4(); DICOM_mat.SetElement(0, 0, IO[0,0]) DICOM_mat.SetElement(0, 1, IO[0,1]) DICOM_mat.SetElement(0, 2, IO[0,2]) DICOM_mat.SetElement(0, 3, IO[0,3]) DICOM_mat.SetElement(1, 0, IO[1,0]) DICOM_mat.SetElement(1, 1, IO[1,1]) DICOM_mat.SetElement(1, 2, IO[1,2]) DICOM_mat.SetElement(1, 3, IO[1,3]) DICOM_mat.SetElement(2, 0, IO[2,0]) DICOM_mat.SetElement(2, 1, IO[2,1]) DICOM_mat.SetElement(2, 2, IO[2,2]) DICOM_mat.SetElement(2, 3, IO[2,3]) DICOM_mat.SetElement(3, 0, IO[3,0]) DICOM_mat.SetElement(3, 1, IO[3,1]) DICOM_mat.SetElement(3, 2, IO[3,2]) DICOM_mat.SetElement(3, 3, IO[3,3]) #DICOM_mat.Invert() # Set up the axes transform = vtk.vtkTransform() transform.Concatenate(DICOM_mat) transform.Update() # Set up the cube (set up the translation back to zero DICOM_mat_cube = vtk.vtkMatrix4x4(); DICOM_mat_cube.DeepCopy(DICOM_mat) DICOM_mat_cube.SetElement(0, 3, 0) DICOM_mat_cube.SetElement(1, 3, 0) DICOM_mat_cube.SetElement(2, 3, 0) transform_cube = vtk.vtkTransform() transform_cube.Concatenate(DICOM_mat_cube) transform_cube.Update() ########################## # Calculate the center of the volume (xMin, xMax, yMin, yMax, zMin, zMax) = image.GetWholeExtent() (xSpacing, ySpacing, zSpacing) = image.GetSpacing() (x0, y0, z0) = image.GetOrigin() center = [x0 + xSpacing * 0.5 * (xMin + xMax), y0 + ySpacing * 0.5 * (yMin + yMax), z0 + zSpacing * 0.5 * (zMin + zMax)] # Matrices for axial, coronal, sagittal, oblique view orientations axial = vtk.vtkMatrix4x4() axial.DeepCopy((1, 0, 0, center[0], 0, 1, 0, center[1], 0, 0, 1, center[2], 0, 0, 0, 1)) coronal = vtk.vtkMatrix4x4() coronal.DeepCopy((1, 0, 0, center[0], 0, 0, 1, center[1], 0,-1, 0, center[2], 0, 0, 0, 1)) sagittal = vtk.vtkMatrix4x4() sagittal.DeepCopy((0, 0,-1, center[0], 1, 0, 0, center[1], 0,-1, 0, center[2], 0, 0, 0, 1)) oblique = vtk.vtkMatrix4x4() oblique.DeepCopy((1, 0, 0, center[0], 0, 0.866025, -0.5, center[1], 0, 0.5, 0.866025, center[2], 0, 0, 0, 1)) # Extract a slice in the desired orientation reslice = vtk.vtkImageReslice() reslice.SetInput(image) reslice.SetOutputDimensionality(2) reslice.SetResliceAxes(sagittal) reslice.SetInterpolationModeToLinear() # Create a greyscale lookup table table = vtk.vtkLookupTable() table.SetRange(0, 2000) # image intensity range table.SetValueRange(0.0, 1.0) # from black to white table.SetSaturationRange(0.0, 0.0) # no color saturation table.SetRampToLinear() table.Build() # Map the image through the lookup table color = vtk.vtkImageMapToColors() color.SetLookupTable(table) color.SetInputConnection(reslice.GetOutputPort()) # Display the image actor = vtk.vtkImageActor() actor.GetMapper().SetInputConnection(color.GetOutputPort()) renderer1 = vtk.vtkRenderer() renderer1.AddActor(actor) ################ # set up cube actor with Orientation(R-L, A-P, S-O) using transform_cube # Set up to ALS (+X=A, +Y=S, +Z=L) source: cube = vtk.vtkAnnotatedCubeActor() cube.SetXPlusFaceText( "S" ); cube.SetXMinusFaceText( "I" ); cube.SetYPlusFaceText( "L" ); cube.SetYMinusFaceText( "R" ); cube.SetZPlusFaceText( "A" ); cube.SetZMinusFaceText( "P" ); cube.SetFaceTextScale( 0.5 ); cube.GetAssembly().SetUserTransform( transform_cube ); # Set UP the axes axes2 = vtk.vtkAxesActor() axes2.SetShaftTypeToCylinder(); #axes2.SetUserTransform( transform_cube ); axes2.SetTotalLength( 1.5, 1.5, 1.5 ); axes2.SetCylinderRadius( 0.500 * axes2.GetCylinderRadius() ); axes2.SetConeRadius( 1.025 * axes2.GetConeRadius() ); axes2.SetSphereRadius( 1.500 * axes2.GetSphereRadius() ); tprop2 = axes2.GetXAxisCaptionActor2D() tprop2.GetCaptionTextProperty(); assembly = vtk.vtkPropAssembly(); assembly.AddPart( axes2 ); assembly.AddPart( cube ); widget = vtk.vtkOrientationMarkerWidget(); widget.SetOutlineColor( 0.9300, 0.5700, 0.1300 ); widget.SetOrientationMarker( assembly ); widget.SetInteractor( iren1 ); widget.SetViewport( 0.0, 0.0, 0.4, 0.4 ); widget.SetEnabled( 1 ); widget.InteractiveOff(); # Set Up Camera view renderer1.SetBackground(0.0, 0.0, 0.0) camera = renderer1.GetActiveCamera() # bounds and initialize camera b = image.GetBounds() renderer1.ResetCamera(b) renderer1.ResetCameraClippingRange() camera.SetViewUp(0.0,-1.0,0.0) camera.Azimuth(315) # Create a text property for both cube axes tprop = vtk.vtkTextProperty() tprop.SetColor(1, 1, 1) tprop.ShadowOff() # Create a vtkCubeAxesActor2D. Use the outer edges of the bounding box to # draw the axes. Add the actor to the renderer. axes = vtk.vtkCubeAxesActor2D() axes.SetInput(image) axes.SetCamera(renderer1.GetActiveCamera()) axes.SetLabelFormat("%6.4g") axes.SetFlyModeToOuterEdges() axes.SetFontFactor(1.2) axes.SetAxisTitleTextProperty(tprop) axes.SetAxisLabelTextProperty(tprop) renderer1.AddViewProp(axes) ############ # Place the interactor initially. The input to a 3D widget is used to # initially position and scale the widget. The "EndInteractionEvent" is # observed which invokes the SelectPolygons callback. # boxWidget.SetInput(image) # boxWidget.PlaceWidget() # boxWidget.AddObserver("InteractionEvent", SelectPolygons) # boxWidget.On() # Initizalize # Set up the interaction interactorStyle = vtk.vtkInteractorStyleImage() interactor = vtk.vtkRenderWindowInteractor() interactor.SetInteractorStyle(interactorStyle) renWin1.SetInteractor(interactor) renWin1.Render() renderer1.Render() interactor.Start() renderer1.RemoveViewProp(axes) return transform_cube, zImagePlaneWidget.GetSliceIndex()
def CreateMarker(self): # Create a composite orientation marker using # vtkAnnotatedCubeActor and vtkAxesActor. # cube = vtkAnnotatedCubeActor() cube.SetXPlusFaceText("R") cube.SetXMinusFaceText("L") cube.SetYPlusFaceText("A") cube.SetYMinusFaceText("P") cube.SetZPlusFaceText("I") cube.SetZMinusFaceText("S") cube.SetXFaceTextRotation(0) cube.SetYFaceTextRotation(0) cube.SetZFaceTextRotation(-90) cube.SetFaceTextScale(0.65) prop = cube.GetCubeProperty() prop.SetColor(0.5, 1, 1) prop = cube.GetTextEdgesProperty() prop.SetLineWidth(1) prop.SetDiffuse(0) prop.SetAmbient(1) prop.SetColor(0.18, 0.28, 0.23) for axis, colour in (('X', (0,0,1)), ('Y', (0,1,0)), ('Z', (1,0,0))): for orient in ('Plus', 'Minus'): prop = getattr(cube, 'Get'+axis+orient+'FaceProperty')() prop.SetColor(*colour) prop.SetInterpolationToFlat() continue continue axes = vtkAxesActor() axes.SetShaftTypeToCylinder() axes.SetXAxisLabelText("x") axes.SetYAxisLabelText("y") axes.SetZAxisLabelText("z") axes.SetTotalLength(1.5, 1.5, 1.5) tpropx = vtkTextProperty() tpropx.ItalicOn() tpropx.ShadowOn() tpropx.SetFontFamilyToTimes() axes.GetXAxisCaptionActor2D().SetCaptionTextProperty(tpropx) tpropy = vtkTextProperty() tpropy.ShallowCopy(tpropx) axes.GetYAxisCaptionActor2D().SetCaptionTextProperty(tpropy) tpropz = vtkTextProperty() tpropz.ShallowCopy(tpropx) axes.GetZAxisCaptionActor2D().SetCaptionTextProperty(tpropz) # Combine the two actors into one with vtkPropAssembly ... # assembly = vtkPropAssembly() assembly.AddPart(axes) assembly.AddPart(cube) # Add the composite marker to the widget. The widget # should be kept in non-interactive mode and the aspect # ratio of the render window taken into account explicitly, # since the widget currently does not take this into # account in a multi-renderer environment. # marker = vtkOrientationMarkerWidget() marker.SetOutlineColor(0.93, 0.57, 0.13) marker.SetOrientationMarker(assembly) marker.SetViewport(0.0, 0.0, 0.15, 0.3) self.OrientationMarker = marker return
def cube_from_source(x, y, z, visibility, colour, transparency): # img = 'OIZV2N0.jpg' # Cast the positions to text so they can be added as labels labelX = str(x) # labelY = str(y) # We're not displaying the y-position anymore labelZ = str(z) # Create cube cube_source = vtk.vtkCubeSource() cube_source.SetCenter(x, y, z) cube_source.SetXLength(dimensions['wallX']) cube_source.SetYLength(dimensions['wallY']) cube_source.SetZLength(dimensions['wallZ']) cube_source.Update() # Create the caption to show the cube position # caption = vtk.vtkCaptionActor2D() # caption.SetCaption("(" + labelX + ", " + labelY + ", " + labelZ + ")") # caption.SetCaption("(" + labelX + ", " + labelZ + ")") # Set the size of the caption box. The box is measured from the lower left corner to the upper right corner. # SetWidth and SetHeight are defined as fraction of the viewport. So SetWidth(0.1) sets the caption box # to 10% the width of the viewport. # The caption text will then fill the provided caption box as best possible # caption.SetWidth(0.15) # caption.SetHeight(0.02) # # caption.GetProperty().SetColor(colours['captionColour']) # caption.SetAttachmentPoint(cube_source.GetCenter()) # Formatting of the text possible with vtkTextProperty # Disable the border box for the caption # caption.BorderOff() # Set the initial visiblity of the caption # if visibility == False: # caption.GetCaptionTextProperty().SetOpacity(0) # caption.LeaderOff() # read image # reader = vtk.vtkJPEGReader() # reader.SetFileName(img) # Create texture object from image # texture = vtk.vtkTexture() # texture.SetInputConnection(reader.GetOutputPort()) # Map texture coordinates of the cube_source # map_to_plane = vtk.vtkTextureMapToPlane() # map_to_plane.SetInputConnection(cube_source.GetOutputPort()) # Create polydatamapper and set the mapped texture as input # mapper = vtk.vtkPolyDataMapper() # mapper.SetInputConnection(map_to_plane.GetOutputPort()) # Create actor and set the mapper and the texture . uncomment if no texture mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(cube_source.GetOutputPort()) mapper.Update() # create the cube actor with the mapper cube = vtk.vtkActor() cube.SetMapper(mapper) cube.GetProperty().SetColor(colours[colour]) if transparency == True: cube.GetProperty().SetOpacity(opacities['transparent']) else: cube.GetProperty().SetOpacity(opacities['opaque']) # Assemble the cube and annotations into a complete prop actor. actor = vtk.vtkPropAssembly() actor.AddPart(cube) # actor.AddPart(caption) # actor.RemovePart(caption) return actor
def visualize(self, images, image_pos_pat, image_ori_pat, sub, postS, interact=True): '''Display and render volumes, reference frames, actors and widgets''' if(sub): #subtract volumes based on indicated postS # define image based on subtraction of postS -preS image = self.subImage(images, postS) else: image = images[postS] # Proceed to build reference frame for display objects based on DICOM coords [self.transformed_image, transform_cube] = self.dicomTransform(image, image_pos_pat, image_ori_pat) # get info from image before visualization self.dims = self.transformed_image.GetDimensions() print "Image Dimensions" print self.dims self.T1spacing = self.transformed_image.GetSpacing() print "Image Spacing" print self.T1spacing self.T1origin = self.transformed_image.GetOrigin() print "Image Origin" print self.T1origin self.T1extent = list(self.transformed_image.GetExtent()) print "Image Extent" print self.T1extent # Set up ortogonal planes self.xImagePlaneWidget.SetInputData( self.transformed_image ) self.xImagePlaneWidget.SetPlaneOrientationToXAxes() self.xImagePlaneWidget.SetSliceIndex(0) self.yImagePlaneWidget.SetInputData( self.transformed_image ) self.yImagePlaneWidget.SetPlaneOrientationToYAxes() self.yImagePlaneWidget.SetSliceIndex(0) self.zImagePlaneWidget.SetInputData( self.transformed_image ) self.zImagePlaneWidget.SetPlaneOrientationToZAxes() self.zImagePlaneWidget.SetSliceIndex(0) self.xImagePlaneWidget.On() self.yImagePlaneWidget.On() self.zImagePlaneWidget.On() # set up cube actor with Orientation(A-P, S-I, L-R) using transform_cube # Set up to ALS (+X=A, +Y=S, +Z=L) source: cube = vtk.vtkAnnotatedCubeActor() cube.SetXPlusFaceText( "L" ); cube.SetXMinusFaceText( "R" ); cube.SetYPlusFaceText( "A" ); cube.SetYMinusFaceText( "P" ); cube.SetZPlusFaceText( "S" ); cube.SetZMinusFaceText( "I" ); cube.SetFaceTextScale( 0.5 ); cube.GetAssembly().SetUserTransform( transform_cube ); # Set UP the axes axes2 = vtk.vtkAxesActor() axes2.SetShaftTypeToCylinder(); #axes2.SetUserTransform( transform_cube ); axes2.SetTotalLength( 1.5, 1.5, 1.5 ); axes2.SetCylinderRadius( 0.500 * axes2.GetCylinderRadius() ); axes2.SetConeRadius( 1.025 * axes2.GetConeRadius() ); axes2.SetSphereRadius( 1.500 * axes2.GetSphereRadius() ); tprop2 = axes2.GetXAxisCaptionActor2D() tprop2.GetCaptionTextProperty(); assembly = vtk.vtkPropAssembly(); assembly.AddPart( axes2 ); assembly.AddPart( cube ); widget = vtk.vtkOrientationMarkerWidget(); widget.SetOutlineColor( 0.9300, 0.5700, 0.1300 ); widget.SetOrientationMarker( assembly ); widget.SetInteractor( self.iren1 ); widget.SetViewport( 0.0, 0.0, 0.4, 0.4 ); widget.SetEnabled( 1 ); widget.InteractiveOff(); # Create a text property for both cube axes tprop = vtk.vtkTextProperty() tprop.SetColor(1, 1, 1) tprop.ShadowOff() # Create a vtkCubeAxesActor2D. Use the outer edges of the bounding box to # draw the axes. Add the actor to the renderer. axes = vtk.vtkCubeAxesActor2D() axes.SetInputData(self.transformed_image) axes.SetCamera(self.renderer1.GetActiveCamera()) axes.SetLabelFormat("%6.4g") axes.SetFlyModeToOuterEdges() axes.SetFontFactor(1.2) axes.SetAxisTitleTextProperty(tprop) axes.SetAxisLabelTextProperty(tprop) self.renderer1.AddViewProp(axes) ############ # bounds and initialize camera bounds = self.transformed_image.GetBounds() self.renderer1.ResetCamera(bounds) self.renderer1.ResetCameraClippingRange() self.camera.SetViewUp(0.0,-1.0,0.0) self.camera.Azimuth(315) # Initizalize self.renWin1.Modified() self.renWin1.Render() self.renderer1.Render() if(interact==True): interactor = self.renWin1.GetInteractor() interactor.Start() return
def CreateMarker(self): # Create a composite orientation marker using # vtkAnnotatedCubeActor and vtkAxesActor. # cube = vtkAnnotatedCubeActor() cube.SetXPlusFaceText("R") cube.SetXMinusFaceText("L") cube.SetYPlusFaceText("A") cube.SetYMinusFaceText("P") cube.SetZPlusFaceText("I") cube.SetZMinusFaceText("S") cube.SetXFaceTextRotation(0) cube.SetYFaceTextRotation(0) cube.SetZFaceTextRotation(-90) cube.SetFaceTextScale(0.65) prop = cube.GetCubeProperty() prop.SetColor(0.5, 1, 1) prop = cube.GetTextEdgesProperty() prop.SetLineWidth(1) prop.SetDiffuse(0) prop.SetAmbient(1) prop.SetColor(0.18, 0.28, 0.23) for axis, colour in (('X', (0, 0, 1)), ('Y', (0, 1, 0)), ('Z', (1, 0, 0))): for orient in ('Plus', 'Minus'): prop = getattr(cube, 'Get' + axis + orient + 'FaceProperty')() prop.SetColor(*colour) prop.SetInterpolationToFlat() continue continue axes = vtkAxesActor() axes.SetShaftTypeToCylinder() axes.SetXAxisLabelText("x") axes.SetYAxisLabelText("y") axes.SetZAxisLabelText("z") axes.SetTotalLength(1.5, 1.5, 1.5) tpropx = vtkTextProperty() tpropx.ItalicOn() tpropx.ShadowOn() tpropx.SetFontFamilyToTimes() axes.GetXAxisCaptionActor2D().SetCaptionTextProperty(tpropx) tpropy = vtkTextProperty() tpropy.ShallowCopy(tpropx) axes.GetYAxisCaptionActor2D().SetCaptionTextProperty(tpropy) tpropz = vtkTextProperty() tpropz.ShallowCopy(tpropx) axes.GetZAxisCaptionActor2D().SetCaptionTextProperty(tpropz) # Combine the two actors into one with vtkPropAssembly ... # assembly = vtkPropAssembly() assembly.AddPart(axes) assembly.AddPart(cube) # Add the composite marker to the widget. The widget # should be kept in non-interactive mode and the aspect # ratio of the render window taken into account explicitly, # since the widget currently does not take this into # account in a multi-renderer environment. # marker = vtkOrientationMarkerWidget() marker.SetOutlineColor(0.93, 0.57, 0.13) marker.SetOrientationMarker(assembly) marker.SetViewport(0.0, 0.0, 0.15, 0.3) self.OrientationMarker = marker return
def toggleCaptionsold(renwinRef, renderers, blocks, showCoordsRef, progressBarRef, key): # Activates on keypress "c" # If the key is used, switch the status of the checkbox if (key == 'key'): if (showCoordsRef.isChecked() == True): showCoordsRef.setChecked(False) else: showCoordsRef.setChecked(True) progressBarRef.setProperty("value", 0) iteration = 0 wallProps = scanScene.get_wall_props(renderers, blocks) numberProps = len(wallProps) for currentProp in wallProps: tx, ty, tz = int(currentProp.GetBounds()[1]), int( currentProp.GetBounds()[3]), int(currentProp.GetBounds()[5]) # Now, test the world coordinate immediately "above" this prop by incrementing the y axis and performing a pick at that location. # If the picker returns a 1 then there is a prop at the modified location. # If there is a prop there then this prop is not the "highest" on the y-axis and therefore no caption is needed. modty = ty + 1 picker = vtkPropPicker() propAbove = picker.Pick3DPoint((tx, modty, tz), renderers[blocks]) if propAbove == 0: # This prop is the "highest" on the y-axis captionPossible = True else: # There is a prop "above" this prop on the y-axis captionPossible = False numberOfActors = currentProp.GetNumberOfPaths() # setup a vtkPropAssembly to store the assembly of parts that make up the current prop, and populate it actorCollection = vtkPropAssembly() actorCollection = currentProp.GetParts() # and initiate traversal over the collection of parts/actors actorCollection.InitTraversal() for actor in range(numberOfActors): # now iterate over each actor # move to the next actor in the collection currentActor = actorCollection.GetNextProp() # check if this actor is a caption type, and if so then set its opacity based on the checkbox and "height" # method returns a 1 if the type of the actor matches the argument, otherwise returns a 0 typeBool = currentActor.IsTypeOf("vtkCaptionActor2D") if typeBool == 1: # this actor is a caption type, so if captionPossible is True then set the current opacity of the text # and the leader to match the status of the checkbox if captionPossible == True and showCoordsRef.isChecked( ) == True: currentActor.GetCaptionTextProperty().SetOpacity(1) currentActor.LeaderOn() else: # captionPossible is False so there is a prop "above" this prop and the caption should be suppressed # Or the master switch for the captions is off # Force the caption opacity to 0 currentActor.GetCaptionTextProperty().SetOpacity(0) currentActor.LeaderOff() # Update the progress bar iteration += 1 percentComplete = int((iteration / numberProps) * 100) progressBarRef.setProperty("value", percentComplete) renwinRef.Render() return
def toggleCaptions(renwinRef, renderers, blocks, showCoordsRef, progressBarRef, key): # Activates on keypress "c" # If the key is used, switch the status of the checkbox if (key == 'key'): if (showCoordsRef.isChecked() == True): showCoordsRef.setChecked(False) else: showCoordsRef.setChecked(True) progressBarRef.setProperty("value", 0) iteration = 0 if showCoordsRef.isChecked() == True: wallCoordinates, _, _ = scanScene.get_wall_positions(renderers, blocks) maxLength, maxWidth, _, _ = scanScene.get_scene_bounds( renderers, blocks) for x in range(maxLength + 1): for z in range(maxWidth + 1): subList = [ point for point in wallCoordinates if point[0] == x and point[2] == z ] sortedSubList = sorted(subList, key=lambda k: [k[1]], reverse=True) if len(sortedSubList) > 0: picker = vtkPropPicker() propPicked = picker.Pick3DPoint(sortedSubList[0], renderers[blocks]) targetProp = picker.GetViewProp() caption = vtkCaptionActor2D() caption.SetCaption("(" + str(x) + ", " + str(z) + ")") caption.SetWidth(0.15) caption.SetHeight(0.02) caption.GetProperty().SetColor(colours['captionColour']) caption.SetAttachmentPoint(x, sortedSubList[0][1] + 0.4, z) caption.BorderOff() targetProp.AddPart(caption) else: # Remove all captions wallProps = scanScene.get_wall_props(renderers, blocks) numberProps = len(wallProps) for currentProp in wallProps: numberOfActors = currentProp.GetNumberOfPaths() # setup a vtkPropAssembly to store the assembly of parts that make up the current prop, and populate it actorCollection = vtkPropAssembly() actorCollection = currentProp.GetParts() # and initiate traversal over the collection of parts/actors actorCollection.InitTraversal() for actor in range(numberOfActors): # now iterate over each actor # move to the next actor in the collection currentActor = actorCollection.GetNextProp() # check if this actor is a caption type, and if so then set its opacity based on the checkbox and "height" # method returns a 1 if the type of the actor matches the argument, otherwise returns a 0 typeBool = currentActor.IsTypeOf("vtkCaptionActor2D") if typeBool == 1: # this actor is a caption type, so remove it currentProp.RemovePart(currentActor) renwinRef.Render() return
def create_axes_orientation_box( line_width=1, text_scale=0.366667, edge_color='black', x_color=None, y_color=None, z_color=None, xlabel='X', ylabel='Y', zlabel='Z', x_face_color='red', y_face_color='green', z_face_color='blue', color_box=False, label_color=None, labels_off=False, opacity=0.5, ): """Create a Box axes orientation widget with labels.""" if x_color is None: x_color = rcParams['axes']['x_color'] if y_color is None: y_color = rcParams['axes']['y_color'] if z_color is None: z_color = rcParams['axes']['z_color'] if edge_color is None: edge_color = rcParams['edge_color'] axes_actor = vtk.vtkAnnotatedCubeActor() axes_actor.SetFaceTextScale(text_scale) if xlabel is not None: axes_actor.SetXPlusFaceText(f"+{xlabel}") axes_actor.SetXMinusFaceText(f"-{xlabel}") if ylabel is not None: axes_actor.SetYPlusFaceText(f"+{ylabel}") axes_actor.SetYMinusFaceText(f"-{ylabel}") if zlabel is not None: axes_actor.SetZPlusFaceText(f"+{zlabel}") axes_actor.SetZMinusFaceText(f"-{zlabel}") axes_actor.SetFaceTextVisibility(not labels_off) axes_actor.SetTextEdgesVisibility(False) # axes_actor.GetTextEdgesProperty().SetColor(parse_color(edge_color)) # axes_actor.GetTextEdgesProperty().SetLineWidth(line_width) axes_actor.GetXPlusFaceProperty().SetColor(parse_color(x_color)) axes_actor.GetXMinusFaceProperty().SetColor(parse_color(x_color)) axes_actor.GetYPlusFaceProperty().SetColor(parse_color(y_color)) axes_actor.GetYMinusFaceProperty().SetColor(parse_color(y_color)) axes_actor.GetZPlusFaceProperty().SetColor(parse_color(z_color)) axes_actor.GetZMinusFaceProperty().SetColor(parse_color(z_color)) axes_actor.GetCubeProperty().SetOpacity(opacity) # axes_actor.GetCubeProperty().SetEdgeColor(parse_color(edge_color)) axes_actor.GetCubeProperty().SetEdgeVisibility(True) axes_actor.GetCubeProperty().BackfaceCullingOn() if opacity < 1.0: # Hide the text edges axes_actor.GetTextEdgesProperty().SetOpacity(0) if color_box: # Hide the cube so we can color each face axes_actor.GetCubeProperty().SetOpacity(0) axes_actor.GetCubeProperty().SetEdgeVisibility(False) cube = pyvista.Cube() cube.clear_arrays() # remove normals face_colors = np.array([ parse_color(x_face_color), parse_color(x_face_color), parse_color(y_face_color), parse_color(y_face_color), parse_color(z_face_color), parse_color(z_face_color), ]) face_colors = (face_colors * 255).astype(np.uint8) cube.cell_arrays['face_colors'] = face_colors cube_mapper = vtk.vtkPolyDataMapper() cube_mapper.SetInputData(cube) cube_mapper.SetColorModeToDirectScalars() cube_mapper.Update() cube_actor = vtk.vtkActor() cube_actor.SetMapper(cube_mapper) cube_actor.GetProperty().BackfaceCullingOn() cube_actor.GetProperty().SetOpacity(opacity) prop_assembly = vtk.vtkPropAssembly() prop_assembly.AddPart(axes_actor) prop_assembly.AddPart(cube_actor) actor = prop_assembly else: actor = axes_actor update_axes_label_color(actor, label_color) return actor
def MakeAnnotatedCubeActor(colors): # Annotated Cube setup annotated_cube = vtk.vtkAnnotatedCubeActor() annotated_cube.SetFaceTextScale(0.366667) # Anatomic labeling annotated_cube.SetXPlusFaceText('X+') annotated_cube.SetXMinusFaceText('X-') annotated_cube.SetYPlusFaceText('Y+') annotated_cube.SetYMinusFaceText('Y-') annotated_cube.SetZPlusFaceText('Z+') annotated_cube.SetZMinusFaceText('Z-') # Change the vector text colors annotated_cube.GetTextEdgesProperty().SetColor(colors.GetColor3d('Black')) annotated_cube.GetTextEdgesProperty().SetLineWidth(1) annotated_cube.GetXPlusFaceProperty().SetColor( colors.GetColor3d('Turquoise')) annotated_cube.GetXMinusFaceProperty().SetColor( colors.GetColor3d('Turquoise')) annotated_cube.GetYPlusFaceProperty().SetColor(colors.GetColor3d('Mint')) annotated_cube.GetYMinusFaceProperty().SetColor(colors.GetColor3d('Mint')) annotated_cube.GetZPlusFaceProperty().SetColor(colors.GetColor3d('Tomato')) annotated_cube.GetZMinusFaceProperty().SetColor( colors.GetColor3d('Tomato')) annotated_cube.SetXFaceTextRotation(90) annotated_cube.SetYFaceTextRotation(180) annotated_cube.SetZFaceTextRotation(-90) # Make the annotated cube transparent annotated_cube.GetCubeProperty().SetOpacity(0) # Colored faces cube setup cube_source = vtk.vtkCubeSource() cube_source.Update() face_colors = vtk.vtkUnsignedCharArray() face_colors.SetNumberOfComponents(3) face_x_plus = colors.GetColor3ub('Red') face_x_minus = colors.GetColor3ub('Green') face_y_plus = colors.GetColor3ub('Blue') face_y_minus = colors.GetColor3ub('Yellow') face_z_plus = colors.GetColor3ub('Cyan') face_z_minus = colors.GetColor3ub('Magenta') face_colors.InsertNextTypedTuple(face_x_minus) face_colors.InsertNextTypedTuple(face_x_plus) face_colors.InsertNextTypedTuple(face_y_minus) face_colors.InsertNextTypedTuple(face_y_plus) face_colors.InsertNextTypedTuple(face_z_minus) face_colors.InsertNextTypedTuple(face_z_plus) cube_source.GetOutput().GetCellData().SetScalars(face_colors) cube_source.Update() cube_mapper = vtk.vtkPolyDataMapper() cube_mapper.SetInputData(cube_source.GetOutput()) cube_mapper.Update() cube_actor = vtk.vtkActor() cube_actor.SetMapper(cube_mapper) # Assemble the colored cube and annotated cube texts into a composite prop. prop_assembly = vtk.vtkPropAssembly() prop_assembly.AddPart(annotated_cube) prop_assembly.AddPart(cube_actor) return prop_assembly
def visualize(self, images, image_pos_pat, image_ori_pat, sub, postS, interact): '''Display and render volumes, reference frames, actors and widgets''' if(sub): #subtract volumes based on indicated postS # define image based on subtraction of postS -preS image = self.subImage(images, postS) else: image = images[postS] # Proceed to build reference frame for display objects based on DICOM coords [self.transformed_image, transform_cube] = self.dicomTransform(image, image_pos_pat, image_ori_pat) # get info from image before visualization self.transformed_image.UpdateInformation() self.dims = self.transformed_image.GetDimensions() print "Image Dimensions" print self.dims self.T1spacing = self.transformed_image.GetSpacing() print "Image Spacing" print self.T1spacing self.T1origin = self.transformed_image.GetOrigin() print "Image Origin" print self.T1origin self.T1extent = list(self.transformed_image.GetWholeExtent()) print "Image Extent" print self.T1extent # Set up ortogonal planes self.xImagePlaneWidget.SetInput( self.transformed_image ) self.xImagePlaneWidget.SetPlaneOrientationToXAxes() self.xImagePlaneWidget.SetSliceIndex(0) self.yImagePlaneWidget.SetInput( self.transformed_image ) self.yImagePlaneWidget.SetPlaneOrientationToYAxes() self.yImagePlaneWidget.SetSliceIndex(0) self.zImagePlaneWidget.SetInput( self.transformed_image ) self.zImagePlaneWidget.SetPlaneOrientationToZAxes() self.zImagePlaneWidget.SetSliceIndex(0) self.xImagePlaneWidget.On() self.yImagePlaneWidget.On() self.zImagePlaneWidget.On() # set up cube actor with Orientation(A-P, S-I, L-R) using transform_cube # Set up to ALS (+X=A, +Y=S, +Z=L) source: cube = vtk.vtkAnnotatedCubeActor() cube.SetXPlusFaceText( "L" ); cube.SetXMinusFaceText( "R" ); cube.SetYPlusFaceText( "A" ); cube.SetYMinusFaceText( "P" ); cube.SetZPlusFaceText( "S" ); cube.SetZMinusFaceText( "I" ); cube.SetFaceTextScale( 0.5 ); cube.GetAssembly().SetUserTransform( transform_cube ); # Set UP the axes axes2 = vtk.vtkAxesActor() axes2.SetShaftTypeToCylinder(); #axes2.SetUserTransform( transform_cube ); axes2.SetTotalLength( 1.5, 1.5, 1.5 ); axes2.SetCylinderRadius( 0.500 * axes2.GetCylinderRadius() ); axes2.SetConeRadius( 1.025 * axes2.GetConeRadius() ); axes2.SetSphereRadius( 1.500 * axes2.GetSphereRadius() ); tprop2 = axes2.GetXAxisCaptionActor2D() tprop2.GetCaptionTextProperty(); assembly = vtk.vtkPropAssembly(); assembly.AddPart( axes2 ); assembly.AddPart( cube ); widget = vtk.vtkOrientationMarkerWidget(); widget.SetOutlineColor( 0.9300, 0.5700, 0.1300 ); widget.SetOrientationMarker( assembly ); widget.SetInteractor( self.iren1 ); widget.SetViewport( 0.0, 0.0, 0.4, 0.4 ); widget.SetEnabled( 1 ); widget.InteractiveOff(); # Create a text property for both cube axes tprop = vtk.vtkTextProperty() tprop.SetColor(1, 1, 1) tprop.ShadowOff() # Create a vtkCubeAxesActor2D. Use the outer edges of the bounding box to # draw the axes. Add the actor to the renderer. axes = vtk.vtkCubeAxesActor2D() axes.SetInput(self.transformed_image) axes.SetCamera(self.renderer1.GetActiveCamera()) axes.SetLabelFormat("%6.4g") axes.SetFlyModeToOuterEdges() axes.SetFontFactor(1.2) axes.SetAxisTitleTextProperty(tprop) axes.SetAxisLabelTextProperty(tprop) self.renderer1.AddViewProp(axes) ############ # bounds and initialize camera bounds = self.transformed_image.GetBounds() self.renderer1.ResetCamera(bounds) self.renderer1.ResetCameraClippingRange() self.camera.SetViewUp(0.0,-1.0,0.0) self.camera.Azimuth(315) # Initizalize self.renWin1.Modified() self.renWin1.Render() self.renderer1.Render() if(interact==True): interactor = self.renWin1.GetInteractor() interactor.Start() return
def vtk_show(_renderer, window_name='VTK Show Window', width=640, height=480, has_picker=False): """ Show the vtkRenderer in an vtkRenderWindow Only support ONE vtkRenderer :return: No return value """ # render_window = vtk.vtkRenderWindow() render_window.AddRenderer(_renderer) render_window.SetSize(width, height) render_window.Render() # It works only after Render() is called render_window.SetWindowName(window_name) # iren = vtk.vtkRenderWindowInteractor() # iren.SetRenderWindow(render_window) interactor_style = vtk.vtkInteractorStyleTrackballCamera() iren.SetInteractorStyle(interactor_style) # Add an Annoted Cube with Arrows cube = vtk.vtkAnnotatedCubeActor() cube.SetXPlusFaceText('R') cube.SetXMinusFaceText('L') cube.SetYPlusFaceText('A') cube.SetYMinusFaceText('P') cube.SetZPlusFaceText('I') cube.SetZMinusFaceText('S') cube.SetXFaceTextRotation(180) cube.SetYFaceTextRotation(180) cube.SetZFaceTextRotation(-90) cube.SetFaceTextScale(0.65) cube.GetCubeProperty().SetColor(0.5, 1.0, 1.0) cube.GetTextEdgesProperty().SetLineWidth(1) cube.GetTextEdgesProperty().SetColor(0.18, 0.28, 0.23) cube.GetTextEdgesProperty().SetDiffuse(0) cube.GetTextEdgesProperty().SetAmbient(1) cube.GetXPlusFaceProperty().SetColor(1, 0, 0) cube.GetXPlusFaceProperty().SetInterpolationToFlat() cube.GetXMinusFaceProperty().SetColor(1, 0, 0) cube.GetXMinusFaceProperty().SetInterpolationToFlat() cube.GetYPlusFaceProperty().SetColor(0, 1, 0) cube.GetYPlusFaceProperty().SetInterpolationToFlat() cube.GetYMinusFaceProperty().SetColor(0, 1, 0) cube.GetYMinusFaceProperty().SetInterpolationToFlat() cube.GetZPlusFaceProperty().SetColor(0, 0, 1) cube.GetZPlusFaceProperty().SetInterpolationToFlat() cube.GetZMinusFaceProperty().SetColor(0, 0, 1) cube.GetZMinusFaceProperty().SetInterpolationToFlat() text_property = vtk.vtkTextProperty() text_property.ItalicOn() text_property.ShadowOn() text_property.BoldOn() text_property.SetFontFamilyToTimes() text_property.SetColor(1, 0, 0) text_property_2 = vtk.vtkTextProperty() text_property_2.ShallowCopy(text_property) text_property_2.SetColor(0, 1, 0) text_property_3 = vtk.vtkTextProperty() text_property_3.ShallowCopy(text_property) text_property_3.SetColor(0, 0, 1) axes = vtk.vtkAxesActor() axes.SetShaftTypeToCylinder() axes.SetXAxisLabelText('X') axes.SetYAxisLabelText('Y') axes.SetZAxisLabelText('Z') axes.SetTotalLength(1.5, 1.5, 1.5) axes.GetXAxisCaptionActor2D().SetCaptionTextProperty(text_property) axes.GetYAxisCaptionActor2D().SetCaptionTextProperty(text_property_2) axes.GetZAxisCaptionActor2D().SetCaptionTextProperty(text_property_3) assembly = vtk.vtkPropAssembly() assembly.AddPart(axes) assembly.AddPart(cube) marker = vtk.vtkOrientationMarkerWidget() marker.SetOutlineColor(0.93, 0.57, 0.13) marker.SetOrientationMarker(assembly) marker.SetViewport(0.0, 0.0, 0.15, 0.3) marker.SetInteractor(iren) marker.EnabledOn() marker.InteractiveOn() # Add a x-y-z coordinate to the original point axes_coor = vtk.vtkAxes() axes_coor.SetOrigin(0, 0, 0) mapper_axes_coor = vtk.vtkPolyDataMapper() mapper_axes_coor.SetInputConnection(axes_coor.GetOutputPort()) actor_axes_coor = vtk.vtkActor() actor_axes_coor.SetMapper(mapper_axes_coor) _renderer.AddActor(actor_axes_coor) # Add an original point and text add_point(_renderer, color=[0, 1, 0], radius=2) add_text(_renderer, position=[0, 0, 0], text="Origin", color=[0, 1, 0], scale=2) _renderer.ResetCamera() # Coorperate with vtkFollower # iren.Initialize() # will be called by Start() autometically if has_picker: iren.AddObserver('MouseMoveEvent', MoveCursor) iren.Start()
#top part cylinderMapper = vtk.vtkPolyDataMapper() cylinderMapper.SetInputConnection(cylinder.GetOutputPort()) cylinderActor = vtk.vtkActor() cylinderActor.SetMapper(cylinderMapper) cylinderActor.GetProperty().SetColor(1,0,0) compositeAssembly = vtk.vtkAssembly() compositeAssembly.AddPart(cylinderActor) compositeAssembly.AddPart(sphereActor) compositeAssembly.AddPart(cubeActor) compositeAssembly.AddPart(coneActor) compositeAssembly.SetOrigin(5,10,15) compositeAssembly.AddPosition(5,0,0) compositeAssembly.RotateX(15) # Build the prop assembly out of a vtkActor and a vtkAssembly assembly = vtk.vtkPropAssembly() assembly.AddPart(compositeAssembly) assembly.AddPart(coneActor) # Create the RenderWindow, Renderer and both Actors # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size # ren1.AddViewProp(assembly) ren1.SetBackground(0.1,0.2,0.4) renWin.SetSize(300,300) # Get handles to some useful objects