def __init__(self, Mgr): self.Mgr = Mgr self.m_volumeInfo = None self.m_selectedIdx = None self.m_selectedImage = None # self.m_reverseSagittal = False # self.m_reverseAxial = False self.m_shoulderSide = 'L' self.m_orientation = None ##AXL:1, COR:0, SAG:2 #Selected Volume CFGS self.m_colorFunction = vtk.vtkColorTransferFunction() self.m_opacityFunction = vtk.vtkPiecewiseFunction() self.m_scalarRange = [0.0, 1.0] self.m_volumeProperty = vtk.vtkVolumeProperty() self.m_imageProperty = vtk.vtkImageProperty() self.m_imageProperty.SetInterpolationTypeToLinear() #Volume self.volume_data = vtk.vtkImageData() self.volume_cropper = vtk.vtkImageData() self.m_volumeMapper = vtk.vtkSmartVolumeMapper() self.m_volume = vtk.vtkVolume() self.m_resliceMapper = [0, 0, 0] self.m_resliceActor = [0, 0, 0] #Color MAp Volume self.m_bShowCAM = False self.m_bShowVolume = False self.m_colorMapMapper = vtk.vtkSmartVolumeMapper() self.m_colorMapVolume = vtk.vtkVolume() self.m_colorMapResliceMapper = [None, None, None] self.m_colorMapResliceActor = [None, None, None] self.resolution = 64 #Crop View self.croppingMapper = vtk.vtkImageSliceMapper() self.croppingActor = vtk.vtkImageSlice() for i in range(3): self.m_resliceMapper[i] = vtk.vtkImageSliceMapper() self.m_resliceActor[i] = vtk.vtkImageSlice() self.m_colorMapResliceMapper[i] = vtk.vtkImageSliceMapper() self.m_colorMapResliceActor[i] = vtk.vtkImageSlice() self.m_resliceActor[0].RotateY(90) self.m_resliceActor[1].RotateX(-90) self.m_colorMapResliceActor[0].RotateY(90) self.m_colorMapResliceActor[1].RotateX(-90) #Initialize self.SetPresetFunctions( self.Mgr.mainFrm.volumeWidget.GetCurrentColorIndex()) self.InitializeVolumeFunctions() self.InitializeClassActivationMap()
def __init__(self): super(DualFlouroSceneVisualizer, self).__init__() # Remove origin information self.xray_changer_1 = vtk.vtkImageChangeInformation() self.xray_changer_1.SetOutputOrigin(0, 0, 0) self.xray_changer_2 = vtk.vtkImageChangeInformation() self.xray_changer_2.SetOutputOrigin(0, 0, 0) self.ct_changer = vtk.vtkImageChangeInformation() self.ct_changer.SetOutputOrigin(0, 0, 0) # Setup mapper and actor for x-ray images self.xray_mapper_1 = vtk.vtkImageSliceMapper() self.xray_mapper_1.SetInputConnection( self.xray_changer_1.GetOutputPort()) self.xray_mapper_2 = vtk.vtkImageSliceMapper() self.xray_mapper_2.SetInputConnection( self.xray_changer_2.GetOutputPort()) self.xray_property = vtk.vtkImageProperty() self.xray_property.SetInterpolationTypeToNearest() self.xray_slice_1 = vtk.vtkImageSlice() self.xray_slice_1.SetMapper(self.xray_mapper_1) self.xray_slice_1.SetProperty(self.xray_property) self.xray_slice_2 = vtk.vtkImageSlice() self.xray_slice_2.SetMapper(self.xray_mapper_2) self.xray_slice_2.SetProperty(self.xray_property) self.marchingCubes = vtk.vtkImageMarchingCubes() self.marchingCubes.SetInputConnection(self.ct_changer.GetOutputPort()) self.marchingCubes.ComputeGradientsOn() self.marchingCubes.ComputeNormalsOn() self.marchingCubes.ComputeScalarsOn() self.marchingCubes.SetNumberOfContours(1) self.marchingCubes.SetValue(0, 0) self.ct_mapper = vtk.vtkPolyDataMapper() self.ct_mapper.SetInputConnection(self.marchingCubes.GetOutputPort()) self.ct_mapper.ScalarVisibilityOff() self.ct_actor = vtk.vtkActor() self.ct_actor.SetMapper(self.ct_mapper) self.ct_actor.GetProperty().SetInterpolationToGouraud() self.ct_actor.GetProperty().SetColor(GetRGBColor('antique_white')) self.renderer = vtk.vtkRenderer() self.renderer.AddViewProp(self.ct_actor) self.renderer.AddViewProp(self.xray_slice_1) self.renderer.AddViewProp(self.xray_slice_2) self.renderer.SetBackground(0.1, 0.2, 0.3) self.interactor = vtk.vtkRenderWindowInteractor() self.interactor_style = vtk.vtkInteractorStyleTrackballCamera() self.interactor.SetInteractorStyle(self.interactor_style)
def addSliceZ(self): if not (self.toggleThreeSlicesFlag): return if not (self.Slices[2] == None): self.renderer.RemoveActor(self.Slices[2]) self.Slices[2] = None self.map3 = vtk.vtkImageSliceMapper() self.map3.BorderOn() self.map3.SliceAtFocalPointOff() self.map3.SliceFacesCameraOff() self.map3.SetOrientationToZ() if vtk.VTK_MAJOR_VERSION <= 5: self.map3.SetInput(self.TemplateReader.GetOutput()) else: self.map3.SetInputConnection(self.TemplateReader.GetOutputPort()) self.map3.SetSliceNumber(0) slice1 = vtk.vtkImageSlice() slice1.SetMapper(self.map3) slice1.GetProperty().SetColorWindow(self.vrange[1] - self.vrange[0]) slice1.GetProperty().SetColorLevel(0.5 * (self.vrange[0] + self.vrange[1])) self.Slices[2] = slice1 self.renderer.AddViewProp(slice1) self.renderWin.GetInteractor().Render()
def __init__(self): super(ImageSliceVisualizer, self).__init__() # Setup pipeline self.image_mapper = vtk.vtkImageSliceMapper() self.image_mapper.SliceAtFocalPointOn() self.image_mapper.SliceFacesCameraOn() self.image_property = vtk.vtkImageProperty() self.image_property.SetInterpolationTypeToNearest() self.image_slice = vtk.vtkImageSlice() self.image_slice.SetMapper(self.image_mapper) self.image_slice.SetProperty(self.image_property) self.renderer = vtk.vtkRenderer() self.renderer.AddActor2D(self.image_slice) self.interactor = vtk.vtkRenderWindowInteractor() self.interactor_style = vtk.vtkInteractorStyleImage() self.interactor_style.SetInteractionModeToImageSlicing() self.interactor_style.KeyPressActivationOn() self.interactor.SetInteractorStyle(self.interactor_style) # Add ability to switch between active layers self.interactor.AddObserver('KeyPressEvent', self._interactor_call_back, -1.0)
def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self, parent) self.frame = QtWidgets.QFrame() self.vl = QtWidgets.QVBoxLayout() self.vtkWidget = QVTKRenderWindowInteractor(self.frame) self.vl.addWidget(self.vtkWidget) self.dicom_image_path = './IM-0008-0034.dcm' # '----------set up dicom reader---------------' self.dcmReader = vtk.vtkDICOMImageReader() self.dcmReader.SetDataByteOrderToLittleEndian() self.dcmReader.SetDirectoryName( r"D:\Users\user\Desktop\NTUCT\1323\Ct_Without_ContrastBrain - 1323\InnerEar_C_06_U70u_4" ) self.dcmReader.Update() # '----------init render---------------' self.ren = vtk.vtkRenderer() # '---------set up mapper----------' self.slice_mapper = vtk.vtkImageSliceMapper() self.slice_mapper.SetInputConnection(self.dcmReader.GetOutputPort()) # set random slice number # self.slice_mapper.SetSliceNumber(50) # set up image_slice self.image_slice = vtk.vtkImageSlice() self.image_slice.SetMapper(self.slice_mapper) # '-----set up window and level of image_slice----' # self.MinMax = self.dcmReader.GetOutput().GetScalarRange() # self.image_slice_property = self.image_slice.GetProperty() # self.image_slice_property.SetColorWindow(self.MinMax[1]) # self.image_slice_property.SetColorLevel((self.MinMax[1] - self.MinMax[0]) / 2) # self.image_slice.Update() # '---------set image_slice as input for renderer------' self.ren.AddViewProp(self.image_slice) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(self.dcmReader.GetOutputPort()) # # Create an actor # actor = vtk.vtkActor() # actor.SetMapper(mapper) # self.ren.AddActor(actor) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() self.ren.ResetCamera() self.frame.setLayout(self.vl) self.setCentralWidget(self.frame) self.show() self.iren.Initialize()
def image(file): reader = vtk.vtkNIFTIImageReader() reader.SetFileName(file) reader.Update() middle = 115 min = 0 max = 255 t = threshold(reader, 10, min, max) mapper = vtk.vtkImageSliceMapper() mapper.SliceAtFocalPointOn() mapper.SetInputConnection(t.GetOutputPort()) actor = vtk.vtkImageSlice() actor.SetMapper(mapper) return actor
def __init__(self): self.colour = (0.0, 0.0, 1.0) self.opacity = 1 self.size = 15.0 self.orientation = "AXIAL" self.spacing = (1, 1, 1) if vtk.vtkVersion().GetVTKVersion() > '5.8.0': self.mapper = vtk.vtkImageSliceMapper() cursor_property = vtk.vtkImageProperty() cursor_property.SetInterpolationTypeToNearest() self.actor = vtk.vtkImageSlice() self.actor.SetMapper(self.mapper) self.actor.SetProperty(cursor_property) else: self.actor = vtk.vtkImageActor() self.mapper = None self._build_actor() self._calculate_area_pixels()
def __init__(self): self.colour = (0.0, 0.0, 1.0) self.opacity = 1 self.size = 15.0 self.orientation = "AXIAL" self.spacing = (1, 1, 1) self.position = (0, 0, 0) if vtk.vtkVersion().GetVTKVersion() > '5.8.0': self.mapper = vtk.vtkImageSliceMapper() cursor_property = vtk.vtkImageProperty() cursor_property.SetInterpolationTypeToNearest() self.actor = vtk.vtkImageSlice() self.actor.SetMapper(self.mapper) self.actor.SetProperty(cursor_property) else: self.actor = vtk.vtkImageActor() self.mapper = None self._build_actor() self._calculate_area_pixels()
def open_File(self): self.reader = vtk.vtkNIFTIImageReader() self.reader.SetFileName('brain1.nii') self.reader.Update() #Data Processing self.size = self.reader.GetOutput().GetDimensions() center = self.reader.GetOutput().GetCenter() spacing = self.reader.GetOutput().GetSpacing() print('size:' + str(self.size)) print('center:' + str(center)) self.center_cam = (center[0], center[1], center[2]) #Get graysacle Range vrange = self.reader.GetOutput().GetScalarRange() #Set Image Slicer Mappers for each view self.map = vtk.vtkImageSliceMapper() self.map.BorderOn() self.map.SliceAtFocalPointOn() self.map.SliceFacesCameraOn() self.map.SetInputConnection(self.reader.GetOutputPort()) self.slice = vtk.vtkImageSlice() self.slice.SetMapper(self.map) self.slice.GetProperty().SetColorWindow(vrange[1] - vrange[0]) self.slice.GetProperty().SetColorLevel(0.5 * (vrange[0] + vrange[1])) self.ren.AddActor(self.slice) self.cam = self.ren.GetActiveCamera() self.cam.ParallelProjectionOn() self.cam.SetParallelScale(0.5 * spacing[1] * self.size[1]) self.cam.SetFocalPoint(self.center_cam[0], self.center_cam[1], self.center_cam[2]) print(self.center_cam) self.changeView() self.spinBox.setEnabled(True)
def __init__(self, parent=None): Qt.QMainWindow.__init__(self, parent) self.frame = Qt.QFrame() self.vl = Qt.QVBoxLayout() self.vtkWidget = QVTKRenderWindowInteractor(self.frame) self.vl.addWidget(self.vtkWidget) self.sl = Qt.QSlider() self.sl.setMinimum(1.0) self.sl.setMaximum(200.0) self.sl.setValue(50.0) self.vl.addWidget(self.sl) self.sl.valueChanged.connect(self.valuechange) self.ren = vtk.vtkRenderer() self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() style = vtk.vtkInteractorStyleImage() style.SetInteractionModeToImageSlicing() self.iren.SetInteractorStyle(style) # Read the image self.reader = vtk.vtkNIFTIImageReader() self.reader.SetFileName('brain1.nii') self.reader.Update() # SLICE Mapper :-) self.map = vtk.vtkImageSliceMapper() self.map.SetSliceNumber(50) self.map.SetInputConnection(self.reader.GetOutputPort()) # Put mapper into actor and actor into renderer slice = vtk.vtkImageSlice() slice.SetMapper(self.map) self.ren.AddActor(slice) self.frame.setLayout(self.vl) self.setCentralWidget(self.frame) self.show() self.iren.Initialize()
def TestDisplay(file1): """Display the output""" inpath = os.path.join(str(VTK_DATA_ROOT), "Data", file1) reader = vtk.vtkNIFTIImageReader() reader.SetFileName(inpath) reader.Update() size = reader.GetOutput().GetDimensions() center = reader.GetOutput().GetCenter() spacing = reader.GetOutput().GetSpacing() center1 = (center[0], center[1], center[2]) center2 = (center[0], center[1], center[2]) if size[2] % 2 == 1: center1 = (center[0], center[1], center[2] + 0.5*spacing[2]) if size[0] % 2 == 1: center2 = (center[0] + 0.5*spacing[0], center[1], center[2]) vrange = reader.GetOutput().GetScalarRange() map1 = vtk.vtkImageSliceMapper() map1.BorderOn() map1.SliceAtFocalPointOn() map1.SliceFacesCameraOn() map1.SetInputConnection(reader.GetOutputPort()) map2 = vtk.vtkImageSliceMapper() map2.BorderOn() map2.SliceAtFocalPointOn() map2.SliceFacesCameraOn() map2.SetInputConnection(reader.GetOutputPort()) slice1 = vtk.vtkImageSlice() slice1.SetMapper(map1) slice1.GetProperty().SetColorWindow(vrange[1]-vrange[0]) slice1.GetProperty().SetColorLevel(0.5*(vrange[0]+vrange[1])) slice2 = vtk.vtkImageSlice() slice2.SetMapper(map2) slice2.GetProperty().SetColorWindow(vrange[1]-vrange[0]) slice2.GetProperty().SetColorLevel(0.5*(vrange[0]+vrange[1])) ratio = size[0]*1.0/(size[0]+size[2]) ren1 = vtk.vtkRenderer() ren1.SetViewport(0,0,ratio,1.0) ren2 = vtk.vtkRenderer() ren2.SetViewport(ratio,0.0,1.0,1.0) ren1.AddViewProp(slice1) ren2.AddViewProp(slice2) cam1 = ren1.GetActiveCamera() cam1.ParallelProjectionOn() cam1.SetParallelScale(0.5*spacing[1]*size[1]) cam1.SetFocalPoint(center1[0], center1[1], center1[2]) cam1.SetPosition(center1[0], center1[1], center1[2] - 100.0) cam2 = ren2.GetActiveCamera() cam2.ParallelProjectionOn() cam2.SetParallelScale(0.5*spacing[1]*size[1]) cam2.SetFocalPoint(center2[0], center2[1], center2[2]) cam2.SetPosition(center2[0] + 100.0, center2[1], center2[2]) if "-I" in sys.argv: style = vtk.vtkInteractorStyleImage() style.SetInteractionModeToImageSlicing() iren = vtk.vtkRenderWindowInteractor() iren.SetInteractorStyle(style) renwin = vtk.vtkRenderWindow() renwin.SetSize(size[0] + size[2], size[1]) renwin.AddRenderer(ren1) renwin.AddRenderer(ren2) renwin.Render() if "-I" in sys.argv: renwin.SetInteractor(iren) iren.Initialize() iren.Start() return renwin
image2 = vtk.vtkImageCanvasSource2D() image2.SetNumberOfScalarComponents(3) image2.SetScalarTypeToUnsignedChar() image2.SetExtent(0,size,0,size,0,0) image2.SetDrawColor(0,255,255) image2.FillBox(0,size,0,size) pad2 = vtk.vtkImageWrapPad() pad2.SetInputConnection(image2.GetOutputPort()) pad2.SetOutputWholeExtent(0,size,0,size,0,10) pad2.Update() checkers = vtk.vtkImageCheckerboard() checkers.SetInput1Data(pad1.GetOutput()) checkers.SetInput2Data(pad2.GetOutput()) checkers.SetNumberOfDivisions(11,6,0) mapper=vtk.vtkImageSliceMapper() mapper.SetInputConnection(checkers.GetOutputPort()) mapper.SliceAtFocalPointOn() mapper.SliceFacesCameraOn() imageSlice = vtk.vtkImageSlice() imageSlice.SetMapper(mapper) imageSlice.GetProperty().SetColorLevel(127.5) imageSlice.GetProperty().SetColorWindow(255) renderer=vtk.vtkRenderer() renderer.AddViewProp(imageSlice) window=vtk.vtkRenderWindow() window.SetSize(size,size) window.AddRenderer(renderer) window.Render()
def slice_view(image, index, width, height, zdir=2, polydata=[], colors=default_colors, transform=None, line_width=3, level_window=None, image_lut=None, interpolation="nearest"): """Return vtkRenderer for orthogonal image slice.""" # determine orientation of medical volume flip = [False, False, False] if transform: transform.Update() matrix = deep_copy(transform.GetMatrix()) try: from nibabel import aff2axcodes codes = aff2axcodes(matrix_to_affine(matrix)) except Exception: codes = ('L', 'A', 'S') if matrix.GetElement(0, 0) < 0: codes = 'R' if matrix.GetElement(1, 1) < 0: codes = 'P' if matrix.GetElement(2, 2) < 0: codes = 'I' if codes[0] == 'R': flip[0] = True if codes[1] == 'P': flip[1] = True if codes[2] == 'I': flip[2] = True dims = image.GetDimensions() axes = slice_axes(zdir) if width < 1: width = dims[axes[0]] if height < 1: height = dims[axes[1]] size = [1, 1, 1] size[axes[0]] = width size[axes[1]] = height if zdir == 2: up = (0, 1, 0) else: up = (0, 0, 1) spacing = image.GetSpacing() distance = 10. * spacing[zdir] focal_point = index_to_point(index, image.GetOrigin(), spacing) position = list(focal_point) if flip[zdir]: position[zdir] = position[zdir] - distance else: position[zdir] = position[zdir] + distance margin = 2 extent = cropping_region(index, axes, size[axes[0]] + margin, size[axes[1]] + margin) if flip[0] or flip[1] or flip[2]: flip_transform = vtk.vtkTransform() flip_transform.Translate(+focal_point[0], +focal_point[1], +focal_point[2]) flip_transform.Scale(-1. if flip[0] else 1., -1. if flip[1] else 1., -1. if flip[2] else 1.) flip_transform.Translate(-focal_point[0], -focal_point[1], -focal_point[2]) points_transform = vtk.vtkTransform() points_transform.SetMatrix(matrix) points_transform.PostMultiply() points_transform.Concatenate(flip_transform) else: flip_transform = None points_transform = None mapper = vtk.vtkImageSliceMapper() mapper.SetInputData(image) mapper.SetOrientation(zdir) mapper.SetSliceNumber(extent[2 * zdir]) mapper.SetCroppingRegion(extent) mapper.CroppingOn() mapper.Update() actor = vtk.vtkImageSlice() actor.SetMapper(mapper) if flip_transform: actor.SetUserTransform(flip_transform) prop = actor.GetProperty() interpolation = interpolation.lower() if interpolation in ("nn", "nearest"): prop.SetInterpolationTypeToNearest() elif interpolation == "linear": prop.SetInterpolationTypeToLinear() elif interpolation == "cubic": prop.SetInterpolationTypeToCubic() else: raise ValueError( "Invalid interpolation mode: {}".format(interpolation)) if not level_window: level_window = auto_level_window(image) prop.SetColorLevel(level_window[0]) prop.SetColorWindow(level_window[1]) if image_lut: prop.SetLookupTable(image_lut) prop.UseLookupTableScalarRangeOn() renderer = vtk.vtkRenderer() renderer.AddActor(actor) camera = renderer.GetActiveCamera() camera.SetViewUp(up) camera.SetPosition(position) camera.SetFocalPoint(focal_point) camera.SetParallelScale(.5 * max((size[axes[0]] - 1) * spacing[axes[0]], (size[axes[1]] - 1) * spacing[axes[1]])) camera.SetClippingRange(distance - .5 * spacing[zdir], distance + .5 * spacing[zdir]) camera.ParallelProjectionOn() # add contours of polygonal data intersected by slice plane if isinstance(polydata, vtk.vtkPolyData): polydata = [polydata] if isinstance(line_width, int): line_width = [line_width] if isinstance(colors[0], float): colors = [colors] for i in xrange(len(polydata)): if i < len(colors): color = colors[i] else: color = colors[-1] if i < len(line_width): width = line_width[i] else: width = line_width[-1] add_contour(renderer, plane=mapper.GetSlicePlane(), polydata=polydata[i], transform=points_transform, line_width=width, color=color) return renderer
dens0.SetDensityEstimateToFixedRadius() dens0.SetRadius(0.05) #dens0.SetDensityEstimateToRelativeRadius() dens0.SetRelativeRadius(2.5) #dens0.SetDensityFormToVolumeNormalized() dens0.SetDensityFormToNumberOfPoints() dens0.ComputeGradientOn() dens0.Update() vrange = dens0.GetOutput().GetPointData().GetArray("Gradient Magnitude").GetRange() # Show the gradient magnitude assign0 = vtk.vtkAssignAttribute() assign0.SetInputConnection(dens0.GetOutputPort()) assign0.Assign("Gradient Magnitude", "SCALARS", "POINT_DATA") map0 = vtk.vtkImageSliceMapper() map0.BorderOn() map0.SliceAtFocalPointOn() map0.SliceFacesCameraOn() map0.SetInputConnection(assign0.GetOutputPort()) slice0 = vtk.vtkImageSlice() slice0.SetMapper(map0) slice0.GetProperty().SetColorWindow(vrange[1]-vrange[0]) slice0.GetProperty().SetColorLevel(0.5*(vrange[0]+vrange[1])) # Show the region labels assign1 = vtk.vtkAssignAttribute() assign1.SetInputConnection(dens0.GetOutputPort()) assign1.Assign("Classification", "SCALARS", "POINT_DATA")
volume_actor = vtk.vtkVolume() volume_prop.SetColor(color_func) volume_prop.SetScalarOpacity(opac_func) volume_actor.SetMapper(volume_mapper) volume_actor.SetProperty(volume_prop) volume_actor.SetPosition([0, 0, 0]) volume_prop.ShadeOff() volume_prop.SetInterpolationTypeToLinear() volume_mapper.SetBlendModeToMaximumIntensity() image_prop = vtk.vtkImageProperty() slice_mapper = [] slice_actor = [] for i in range(3): slice_mapper.append(vtk.vtkImageSliceMapper()) slice_mapper[i].BorderOn() slice_actor.append(vtk.vtkImageSlice()) slice_mapper[i].SetOrientation(i) slice_actor[i].SetMapper(slice_mapper[i]) slice_actor[i].SetProperty(image_prop) def get_tmp_data(): return tmp_data def save_tmp_data(): np.savez_compressed(tmp_path, data=tmp_data, time=elapsed_time)
def render(input_file, output_file, histogram_bin_count): path, output_name = split(output_file) output_root, ext = splitext(output_name) reader = vtk.vtkNIFTIImageReader() reader.SetFileName(input_file) reader.Update() output = reader.GetOutput() size = output.GetDimensions() center = output.GetCenter() spacing = output.GetSpacing() center1 = (center[0], center[1], center[2]) center2 = (center[0], center[1], center[2]) if size[2] % 2 == 1: center1 = (center[0], center[1], center[2] + 0.5*spacing[2]) if size[0] % 2 == 1: center2 = (center[0] + 0.5*spacing[0], center[1], center[2]) vrange = output.GetScalarRange() avg_scale = 0.25 * (vrange[1]-vrange[0]) avg_map_top = vtk.vtkImageResliceMapper() avg_map_top.BorderOn() avg_map_top.SliceAtFocalPointOn() avg_map_top.SliceFacesCameraOn() avg_map_top.SetSlabThickness(max(size)) avg_map_top.SetInputConnection(reader.GetOutputPort()) avg_map_side = vtk.vtkImageResliceMapper() avg_map_side.BorderOn() avg_map_side.SliceAtFocalPointOn() avg_map_side.SliceFacesCameraOn() avg_map_side.SetSlabThickness(max(size)) avg_map_side.SetInputConnection(reader.GetOutputPort()) avg_top = vtk.vtkImageSlice() avg_top.SetMapper(avg_map_top) avg_top.GetProperty().SetColorWindow(avg_scale) avg_top.GetProperty().SetColorLevel(0.5*avg_scale) avg_side = vtk.vtkImageSlice() avg_side.SetMapper(avg_map_side) avg_side.GetProperty().SetColorWindow(avg_scale) avg_side.GetProperty().SetColorLevel(0.5*avg_scale) slice_scale = vrange[1]-vrange[0] slice_map_top = vtk.vtkImageSliceMapper() slice_map_top.BorderOn() slice_map_top.SliceAtFocalPointOn() slice_map_top.SliceFacesCameraOn() slice_map_top.SetInputConnection(reader.GetOutputPort()) slice_map_side = vtk.vtkImageSliceMapper() slice_map_side.BorderOn() slice_map_side.SliceAtFocalPointOn() slice_map_side.SliceFacesCameraOn() slice_map_side.SetInputConnection(reader.GetOutputPort()) slice_top = vtk.vtkImageSlice() slice_top.SetMapper(slice_map_top) slice_top.GetProperty().SetColorWindow(slice_scale) slice_top.GetProperty().SetColorLevel(0.5*slice_scale) slice_side = vtk.vtkImageSlice() slice_side.SetMapper(slice_map_side) slice_side.GetProperty().SetColorWindow(slice_scale) slice_side.GetProperty().SetColorLevel(0.5*slice_scale) text1_actor = vtk.vtkTextActor() text1_actor.SetInput("min {:.5g}, max {:.5g}".format(vrange[0], vrange[1])) text1_actor.SetPosition(0.1 * center1[0], 0.1 * center1[1]) text1_actor.GetTextProperty().SetFontSize(18) text1_actor.GetTextProperty().SetColor(1,1,1) text2_actor = vtk.vtkTextActor() text2_actor.SetInput("Scaled Average") text2_actor.SetPosition(0.1 * center1[0], 1.8 * size[1]) text2_actor.GetTextProperty().SetFontSize(24) text2_actor.GetTextProperty().SetColor(1,1,1) text3_actor = vtk.vtkTextActor() text3_actor.SetInput("Slice") text3_actor.SetPosition(0.1 * center1[0], 1.8 * size[1]) text3_actor.GetTextProperty().SetFontSize(24) text3_actor.GetTextProperty().SetColor(1,1,1) ren1 = vtk.vtkRenderer() ren2 = vtk.vtkRenderer() ren3 = vtk.vtkRenderer() ren4 = vtk.vtkRenderer() ren1.SetViewport(0, 0, 0.5,0.5) ren2.SetViewport(0.5,0, 1.0,0.5) ren3.SetViewport(0, 0.5,0.5,1.0) ren4.SetViewport(0.5,0.5,1.0,1.0) ren1.AddViewProp(slice_top) ren2.AddViewProp(slice_side) ren3.AddViewProp(avg_top) ren4.AddViewProp(avg_side) ren1.AddActor(text1_actor) ren3.AddActor(text2_actor) ren1.AddActor(text3_actor) cam1 = ren1.GetActiveCamera() cam1.ParallelProjectionOn() cam1.SetParallelScale(0.5*spacing[1]*size[1]) cam1.SetFocalPoint(center1[0], center1[1], center1[2]) cam1.SetPosition(center1[0], center1[1], center1[2] - 100.0) cam2 = ren2.GetActiveCamera() cam2.ParallelProjectionOn() cam2.SetParallelScale(0.5*spacing[1]*size[1]) cam2.SetFocalPoint(center2[0], center2[1], center2[2]) cam2.SetPosition(center2[0] + 100.0, center2[1], center2[2]) cam3 = ren3.GetActiveCamera() cam3.ParallelProjectionOn() cam3.SetParallelScale(0.5*spacing[1]*size[1]) cam3.SetFocalPoint(center1[0], center1[1], center1[2]) cam3.SetPosition(center1[0], center1[1], center1[2] - 100.0) cam4 = ren4.GetActiveCamera() cam4.ParallelProjectionOn() cam4.SetParallelScale(0.5*spacing[1]*size[1]) cam4.SetFocalPoint(center2[0], center2[1], center2[2]) cam4.SetPosition(center2[0] + 100.0, center2[1], center2[2]) ren_win = vtk.vtkRenderWindow() ren_win.SetSize(2 * (size[0] + size[2]) // 2 * 2, 4 * size[1] // 2 * 2) # keep size even ren_win.AddRenderer(ren1) ren_win.AddRenderer(ren2) ren_win.AddRenderer(ren3) ren_win.AddRenderer(ren4) ren_win.Render() # screenshot code: w2if = vtk.vtkWindowToImageFilter() w2if.SetInput(ren_win) w2if.Update() writer = vtk.vtkPNGWriter() writer.SetFileName(output_file) writer.SetInputConnection(w2if.GetOutputPort()) writer.Write() marching_cubes = vtk.vtkMarchingCubes() marching_cubes.SetInputConnection(reader.GetOutputPort()) marching_cubes.ComputeNormalsOn() marching_cubes.ComputeGradientsOn() marching_cubes.SetValue(0, 0.1 * vrange[1]) stl_output = join(path, output_root + '_isosurface.stl') stl_writer = vtk.vtkSTLWriter() stl_writer.SetFileName(stl_output) stl_writer.SetInputConnection(marching_cubes.GetOutputPort()) stl_writer.Write() # histogram code: num_bins = int(histogram_bin_count) histogram = vtk.vtkImageHistogram() histogram.SetInputConnection(reader.GetOutputPort()) histogram.AutomaticBinningOn() histogram.SetMaximumNumberOfBins(num_bins) histogram.Update() origin = histogram.GetBinOrigin() spacing = histogram.GetBinSpacing() bin_values = np.linspace(0, num_bins * spacing, num=num_bins, endpoint=False) hist_output = join(path, output_root + '_hist.txt') hist_values = numpy_support.vtk_to_numpy(histogram.GetHistogram()) if len(hist_values) != len(bin_values): raise Exception('Histogram values and bins do not match') hist_mat = np.column_stack((bin_values, hist_values)) np.savetxt(hist_output, hist_mat, fmt='%.9g')
if not fileName.lower().endswith('.nii'): os.sys.exit('Input \"{inputImage}\" is not of type NIfTI (*.nii). Exiting...'.format(inputImage=fileName)) # Read both images inputReader = vtk.vtkNIFTIImageReader() inputReader.SetFileName(args.inputImage) print("Reading {}".format(args.inputImage)) inputReader.Update() gridReader = vtk.vtkNIFTIImageReader() gridReader.SetFileName(args.inputGrid) print("Reading {}".format(args.inputGrid)) gridReader.Update() # Setup input Mapper + Property -> Slice inputMapper = vtk.vtkImageSliceMapper() inputMapper.SetInputConnection(inputReader.GetOutputPort()) inputMapper.SliceAtFocalPointOn() inputMapper.SliceFacesCameraOn() inputMapper.BorderOff() imageProperty = vtk.vtkImageProperty() imageProperty.SetColorLevel(args.level) imageProperty.SetColorWindow(args.window) imageProperty.SetInterpolationTypeToLinear() imageProperty.SetLayerNumber(1) inputSlice = vtk.vtkImageSlice() inputSlice.SetMapper(inputMapper) inputSlice.SetProperty(imageProperty)
def ToggleDRR(self, value): if self.DRRInitialized == True: if value == True: self.image.VisibilityOn() self.toggleDRR = True self.slicerRenderer.Render() return self.image.VisibilityOff() self.toggleDRR = False self.slicerRenderer.Render() return self.DRRInitialized = True self.toggleDRR = True # Initialize Window To Input Pipeline self.cameraTransform = vtk.vtkTransform() self.xRotationValue = 0.0 self.zRotationValue = 0.0 self.winToImage = vtk.vtkWindowToImageFilter() self.pixelData = vtk.vtkImageData() self.winToImage.SetInput(self.renderWindow) self.imageMapper = vtk.vtkImageSliceMapper() self.image = vtk.vtkImageSlice() self.imageMapper.SetInputData(self.winToImage.GetOutput()) self.image.SetMapper(self.imageMapper) # Render DRR (replace with udpate DRR) self.cameraTransform.Identity() self.cameraTransform.PostMultiply() self.cameraTransform.Translate(0, 705.81, 0) self.cameraTransform.RotateZ(self.zRotationValue) self.cameraTransform.RotateX(-self.xRotationValue) self.renderer.GetActiveCamera().SetPosition( self.cameraTransform.GetPosition()) self.renderer.GetActiveCamera().SetFocalPoint(0, 0, 0) self.renderer.GetActiveCamera().SetViewUp(0, 0, 1) self.renderer.SetBackground(1, 1, 1) self.renderWindow.Render() self.winToImage = vtk.vtkWindowToImageFilter() self.winToImage.SetInput(self.renderWindow) self.winToImage.Update() # Add DRR Image to Scene using vtkPlaneSource self.plane = vtk.vtkPlaneSource() #self.texture = vtk.vtkTexture() #self.texture.SetInputConnection(self.winToImage.GetOutputPort()) #self.texture.Update() #self.plane.SetPoint1(0, 530, 0) self.plane.SetPoint1(0, 1060, 0) #self.plane.SetPoint2(335, 0, 0) self.plane.SetPoint2(675, 0, 0) self.plane.SetOrigin(0, 0, 0) self.plane.Update() # Create DRR Model Node self.planeModelNode = slicer.mrmlScene.AddNewNodeByClass( 'vtkMRMLModelNode') self.planeModelNode.CreateDefaultDisplayNodes() #self.planeModelNode.CreateDefaultStorageNode() self.planeModelNode.SetAndObservePolyData(self.plane.GetOutput()) self.planeModelNode.SetAndObserveTransformNodeID( self.scene.dRRToMonitorTransform.GetID()) self.planeModelDisplay = self.planeModelNode.GetDisplayNode() self.planeModelDisplay.SetTextureImageDataConnection( self.winToImage.GetOutputPort()) self.planeModelDisplay.VisibilityOn() self.planeModelDisplay.SetFrontfaceCulling(False) self.planeModelDisplay.SetBackfaceCulling(False) self.renderWindow.Render() self.slicerRenderer.Render()
for x in range(10): for y in range(10): for rgb in range(3): image.SetScalarComponentFromDouble(x,y,0, rgb, 0.0) for x in range(corner, corner+3): for y in range(corner,corner+3): image.SetScalarComponentFromDouble(x,y,0, channel, 255.0) # Image 1 image1 = vtk.vtkImageData() CreateColorImage(image1, 1, 0); imageSliceMapper1 = vtk.vtkImageSliceMapper() imageSliceMapper1.SetInputData(image1) imageSlice1 = vtk.vtkImageSlice() imageSlice1.SetMapper(imageSliceMapper1) imageSlice1.GetProperty().SetOpacity(.5) # Image 2 image2 = vtk.vtkImageData() CreateColorImage(image2, 4, 1) imageSliceMapper2 = vtk.vtkImageSliceMapper() imageSliceMapper2.SetInputData(image2) imageSlice2 = vtk.vtkImageSlice() imageSlice2.SetMapper(imageSliceMapper2)
dens0.SetDensityEstimateToFixedRadius() dens0.SetRadius(0.05) # dens0.SetDensityEstimateToRelativeRadius() dens0.SetRelativeRadius(2.5) # dens0.SetDensityFormToVolumeNormalized() dens0.SetDensityFormToNumberOfPoints() dens0.ComputeGradientOn() dens0.Update() vrange = dens0.GetOutput().GetPointData().GetArray("Gradient Magnitude").GetRange() # Show the gradient magnitude assign0 = vtk.vtkAssignAttribute() assign0.SetInputConnection(dens0.GetOutputPort()) assign0.Assign("Gradient Magnitude", "SCALARS", "POINT_DATA") map0 = vtk.vtkImageSliceMapper() map0.BorderOn() map0.SliceAtFocalPointOn() map0.SliceFacesCameraOn() map0.SetInputConnection(assign0.GetOutputPort()) slice0 = vtk.vtkImageSlice() slice0.SetMapper(map0) slice0.GetProperty().SetColorWindow(vrange[1] - vrange[0]) slice0.GetProperty().SetColorLevel(0.5 * (vrange[0] + vrange[1])) # Show the region labels assign1 = vtk.vtkAssignAttribute() assign1.SetInputConnection(dens0.GetOutputPort()) assign1.Assign("Classification", "SCALARS", "POINT_DATA")
renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) DICOMimageReader = vtk.vtkDICOMImageReader() DICOMimageReader.SetDirectoryName(dirpath) #DICOMimageReader.SetFileName(dirpath) DICOMimageReader.Update() #imageViewer = vtk.vtkImageViewer2() #imageViewer.SetInputConnection(DICOMimageReader.GetOutputPort()); ism = vtk.vtkImageSliceMapper() ism.SetInputConnection(DICOMimageReader.GetOutputPort()) mapActor = vtk.vtkImageActor() mapActor.SetMapper(ism) mapActor.SetZSlice(80) #sliceTextProp = vtk.vtkTextProperty() #sliceTextProp.SetFontFamilyToCourier() #sliceTextProp.SetFontSize(20) #sliceTextProp.SetVerticalJustificationToBottom() #sliceTextProp.SetJustificationToLeft() #sliceTextMapper = vtk.vtkTextMapper() #msg = StatusMessage.Format(imageViewer.GetSliceMin(),imageViewer.GetSliceMax()) #sliceTextMapper.SetTextProperty(sliceTextProp)