def create_frog_actor(file_name, tissue, use_flying_edges): reader = vtk.vtkMetaImageReader() reader.SetFileName(str(file_name)) reader.Update() select_tissue = vtk.vtkImageThreshold() select_tissue.ThresholdBetween(tissue, tissue) select_tissue.SetInValue(255) select_tissue.SetOutValue(0) select_tissue.SetInputConnection(reader.GetOutputPort()) iso_value = 63.5 if use_flying_edges: try: iso_surface = vtk.vtkFlyingEdges3D() except AttributeError: iso_surface = vtk.vtkMarchingCubes() else: iso_surface = vtk.vtkMarchingCubes() iso_surface.SetInputConnection(select_tissue.GetOutputPort()) iso_surface.ComputeScalarsOff() iso_surface.ComputeGradientsOff() iso_surface.ComputeNormalsOn() iso_surface.SetValue(0, iso_value) stripper = vtk.vtkStripper() stripper.SetInputConnection(iso_surface.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def _contour_surface(grid: "pv.Grid", method: str = "flying_edges", isodensity: float = 0.001) -> "pv.PolyData": """Counter surface from grid. Args: grid: Electron density as PyVista Grid object isodensity: Isodensity value (electrons/bohr³) method: Method for contouring: 'contour' or 'flying_edges Returns: surface: Surface as Pyvista PolyData object """ # Select method for contouring if method == "flying_edges": contour_filter = vtk.vtkFlyingEdges3D() elif method == "contour": contour_filter = vtk.vtkContourFilter() # Run the contour filter isodensity = isodensity contour_filter.SetInputData(grid) contour_filter.SetValue(0, isodensity) contour_filter.Update() surface = contour_filter.GetOutput() surface = pv.wrap(surface) return surface
def createSTL(mha, stl): reader = vtk.vtkMetaImageReader() reader.SetFileName(mha) reader.Update() threshold = vtk.vtkImageThreshold() threshold.SetInputConnection(reader.GetOutputPort()) threshold.ThresholdByLower(0.1) threshold.ReplaceInOn() threshold.SetInValue(0) # set all values below 0.1 to 0 threshold.ReplaceOutOn() threshold.SetOutValue(1) # set all values above 0.1 to 1 threshold.Update() dmc = vtk.vtkFlyingEdges3D() dmc.SetInputConnection(threshold.GetOutputPort()) dmc.ComputeNormalsOn() dmc.GenerateValues(1, 1, 1) dmc.Update() smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(dmc.GetOutputPort()) smoother.SetNumberOfIterations(15) smoother.BoundarySmoothingOff() smoother.Update() writer = vtk.vtkSTLWriter() writer.SetInputConnection(smoother.GetOutputPort()) writer.SetFileTypeToBinary() writer.SetFileName(stl) writer.Write() return 0
def create_smooth_frog_actor(file_name, tissue): reader = vtk.vtkMetaImageReader() reader.SetFileName(str(file_name)) reader.Update() select_tissue = vtk.vtkImageThreshold() select_tissue.ThresholdBetween(tissue, tissue) select_tissue.SetInValue(255) select_tissue.SetOutValue(0) select_tissue.SetInputConnection(reader.GetOutputPort()) gaussianRadius = 1 gaussianStandardDeviation = 2.0 gaussian = vtk.vtkImageGaussianSmooth() gaussian.SetStandardDeviations(gaussianStandardDeviation, gaussianStandardDeviation, gaussianStandardDeviation) gaussian.SetRadiusFactors(gaussianRadius, gaussianRadius, gaussianRadius) gaussian.SetInputConnection(select_tissue.GetOutputPort()) isoValue = 63.5 iso_surface = vtk.vtkFlyingEdges3D() iso_surface.SetInputConnection(gaussian.GetOutputPort()) iso_surface.ComputeScalarsOff() iso_surface.ComputeGradientsOff() iso_surface.ComputeNormalsOff() iso_surface.SetValue(0, isoValue) smoothing_iterations = 20 pass_band = 0.001 feature_angle = 60.0 smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(iso_surface.GetOutputPort()) smoother.SetNumberOfIterations(smoothing_iterations) smoother.BoundarySmoothingOff() smoother.FeatureEdgeSmoothingOff() smoother.SetFeatureAngle(feature_angle) smoother.SetPassBand(pass_band) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOff() smoother.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(smoother.GetOutputPort()) normals.SetFeatureAngle(feature_angle) stripper = vtk.vtkStripper() stripper.SetInputConnection(normals.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def create_brain_extractor(brain): """ Given the output from brain (vtkNIFTIImageReader) extract it into 3D using vtkFlyingEdges3D algorithm (https://www.vtk.org/doc/nightly/html/classvtkFlyingEdges3D.html) :param brain: a vtkNIFTIImageReader volume containing the brain :return: the extracted volume from vtkFlyingEdges3D """ brain_extractor = vtk.vtkFlyingEdges3D() brain_extractor.SetInputConnection(brain.reader.GetOutputPort()) # brain_extractor.SetValue(0, sum(brain.scalar_range)/2) return brain_extractor
def flyingEdges(volume) -> pv.PolyData: # use flying edges algorithm fe = vtk.vtkFlyingEdges3D() fe.SetInputData(volume) fe.SetValue(0, 1) fe.ComputeNormalsOn() fe.Update() mesh = fe.GetOutput() mesh = pv.wrap(mesh) return mesh
def CreateFrogSkinActor(fileName, useMarchingCubes): reader = vtk.vtkMetaImageReader() reader.SetFileName(fileName) reader.Update() isoValue = 20.5 mcubes = vtk.vtkMarchingCubes() flyingEdges = vtk.vtkFlyingEdges3D() smoother = vtk.vtkWindowedSincPolyDataFilter() if useMarchingCubes: mcubes.SetInputConnection(reader.GetOutputPort()) mcubes.ComputeScalarsOff() mcubes.ComputeGradientsOff() mcubes.ComputeNormalsOff() mcubes.SetValue(0, isoValue) smoother.SetInputConnection(mcubes.GetOutputPort()) else: flyingEdges.SetInputConnection(reader.GetOutputPort()) flyingEdges.ComputeScalarsOff() flyingEdges.ComputeGradientsOff() flyingEdges.ComputeNormalsOff() flyingEdges.SetValue(0, isoValue) smoother.SetInputConnection(flyingEdges.GetOutputPort()) smoothingIterations = 5 passBand = 0.001 featureAngle = 60.0 smoother.SetNumberOfIterations(smoothingIterations) smoother.BoundarySmoothingOff() smoother.FeatureEdgeSmoothingOff() smoother.SetFeatureAngle(featureAngle) smoother.SetPassBand(passBand) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() smoother.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(smoother.GetOutputPort()) normals.SetFeatureAngle(featureAngle) stripper = vtk.vtkStripper() stripper.SetInputConnection(normals.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def main(): # vtkFlyingEdges3D was introduced in VTK >= 8.2 use_flying_edges = vtk_version_ok(8, 2, 0) colors = vtk.vtkNamedColors() colors.SetColor('SkinColor', [240, 184, 160, 255]) colors.SetColor('BackfaceColor', [255, 229, 200, 255]) colors.SetColor('BkgColor', [51, 77, 102, 255]) file_name, threshold, largest_surface = get_program_parameters() # Load data reader = vtk.vtkStructuredPointsReader() reader.SetFileName(file_name) # Create a 3D model using flying edges or marching cubes if use_flying_edges: try: mc = vtk.vtkFlyingEdges3D() except AttributeError: mc = vtk.vtkMarchingCubes() else: mc = vtk.vtkMarchingCubes() mc.SetInputConnection(reader.GetOutputPort()) mc.ComputeNormalsOn() mc.ComputeGradientsOn() mc.SetValue(0, threshold) # second value acts as threshold # To remain largest region confilter = vtk.vtkPolyDataConnectivityFilter() confilter.SetInputConnection(mc.GetOutputPort()) confilter.SetExtractionModeToLargestRegion() # Create a mapper mapper = vtk.vtkPolyDataMapper() if largest_surface: mapper.SetInputConnection(confilter.GetOutputPort()) else: mapper.SetInputConnection(mc.GetOutputPort()) mapper.ScalarVisibilityOff() # Visualize actor = vtk.vtkActor() actor.GetProperty().SetColor(colors.GetColor3d('SkinColor')) back_prop = vtk.vtkProperty() back_prop.SetDiffuseColor(colors.GetColor3d('BackfaceColor')) actor.SetBackfaceProperty(back_prop) actor.SetMapper(mapper) renderer = vtk.vtkRenderer() renderer.AddActor(actor) renderer.SetBackground(colors.GetColor3d('SlateGray')) renderer.GetActiveCamera().SetViewUp(0.0, 0.0, 1.0) renderer.GetActiveCamera().SetPosition(0.0, 1.0, 0.0) renderer.GetActiveCamera().SetFocalPoint(0.0, 0.0, 0.0) renderer.ResetCamera() renderer.GetActiveCamera().Azimuth(30.0) renderer.GetActiveCamera().Elevation(30.0) ren_win = vtk.vtkRenderWindow() ren_win.AddRenderer(renderer) ren_win.SetSize(640, 480) ren_win.SetWindowName('ExtractLargestIsosurface') iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(ren_win) ren_win.Render() iren.Initialize() iren.Start()
def main(): # vtkFlyingEdges3D was introduced in VTK >= 8.2 use_flying_edges = vtk_version_ok(8, 2, 0) colors = vtk.vtkNamedColors() file_name = get_program_parameters() colors.SetColor('SkinColor', [240, 184, 160, 255]) colors.SetColor('BkgColor', [51, 77, 102, 255]) # Create the renderer, the render window, and the interactor. The # renderer draws into the render window, the interactor enables # mouse- and keyboard-based interaction with the data within the # render window. # a_renderer = vtk.vtkRenderer() ren_win = vtk.vtkRenderWindow() ren_win.AddRenderer(a_renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(ren_win) # Set a background color for the renderer and set the size of the # render window (expressed in pixels). a_renderer.SetBackground(colors.GetColor3d('BkgColor')) ren_win.SetSize(640, 480) # The following reader is used to read a series of 2D slices (images) # that compose the volume. The slice dimensions are set, and the # pixel spacing. The data Endianness must also be specified. The # reader uses the FilePrefix in combination with the slice number to # construct filenames using the format FilePrefix.%d. (In this case # the FilePrefix is the root name of the file: quarter.) # reader = vtk.vtkMetaImageReader() # reader.SetFileName(file_name) # reader.Update() reader = vtk.vtkNIFTIImageReader() reader.SetFileName(file_name) reader.Update() # An isosurface, or contour value of 500 is known to correspond to # the skin of the patient. # The triangle stripper is used to create triangle # strips from the isosurface these render much faster on may # systems. if use_flying_edges: try: skin_extractor = vtk.vtkFlyingEdges3D() except AttributeError: skin_extractor = vtk.vtkMarchingCubes() else: skin_extractor = vtk.vtkMarchingCubes() skin_extractor.SetInputConnection(reader.GetOutputPort()) skin_extractor.SetValue(0, 500) skin_extractor.Update() skin_stripper = vtk.vtkStripper() skin_stripper.SetInputConnection(skin_extractor.GetOutputPort()) skin_stripper.Update() skin_mapper = vtk.vtkPolyDataMapper() skin_mapper.SetInputConnection(skin_stripper.GetOutputPort()) skin_mapper.ScalarVisibilityOff() skin = vtk.vtkActor() skin.SetMapper(skin_mapper) skin.GetProperty().SetDiffuseColor(colors.GetColor3d('SkinColor')) skin.GetProperty().SetSpecular(0.3) skin.GetProperty().SetSpecularPower(20) # An isosurface, or contour value of 1150 is known to correspond to # the bone of the patient. # The triangle stripper is used to create triangle # strips from the isosurface these render much faster on may # systems. if use_flying_edges: try: bone_extractor = vtk.vtkFlyingEdges3D() except AttributeError: bone_extractor = vtk.vtkMarchingCubes() else: bone_extractor = vtk.vtkMarchingCubes() bone_extractor.SetInputConnection(reader.GetOutputPort()) bone_extractor.SetValue(0, 1000) bone_stripper = vtk.vtkStripper() bone_stripper.SetInputConnection(bone_extractor.GetOutputPort()) bone_mapper = vtk.vtkPolyDataMapper() bone_mapper.SetInputConnection(bone_stripper.GetOutputPort()) bone_mapper.ScalarVisibilityOff() bone = vtk.vtkActor() bone.SetMapper(bone_mapper) bone.GetProperty().SetDiffuseColor(colors.GetColor3d('Ivory')) # An outline provides context around the data. # outline_data = vtk.vtkOutlineFilter() outline_data.SetInputConnection(reader.GetOutputPort()) outline_data.Update() map_outline = vtk.vtkPolyDataMapper() map_outline.SetInputConnection(outline_data.GetOutputPort()) outline = vtk.vtkActor() outline.SetMapper(map_outline) outline.GetProperty().SetColor(colors.GetColor3d('Black')) # Now we are creating three orthogonal planes passing through the # volume. Each plane uses a different texture map and therefore has # different coloration. # Start by creating a black/white lookup table. bw_lut = vtk.vtkLookupTable() bw_lut.SetTableRange(0, 2000) bw_lut.SetSaturationRange(0, 0) bw_lut.SetHueRange(0, 0) bw_lut.SetValueRange(0, 1) bw_lut.Build() # effective built # Now create a lookup table that consists of the full hue circle # (from HSV). hue_lut = vtk.vtkLookupTable() hue_lut.SetTableRange(0, 2000) hue_lut.SetHueRange(0, 1) hue_lut.SetSaturationRange(1, 1) hue_lut.SetValueRange(1, 1) hue_lut.Build() # effective built # Finally, create a lookup table with a single hue but having a range # in the saturation of the hue. sat_lut = vtk.vtkLookupTable() sat_lut.SetTableRange(0, 2000) sat_lut.SetHueRange(0.6, 0.6) sat_lut.SetSaturationRange(0, 1) sat_lut.SetValueRange(1, 1) sat_lut.Build() # effective built # Create the first of the three planes. The filter vtkImageMapToColors # maps the data through the corresponding lookup table created above. The # vtkImageActor is a type of vtkProp and conveniently displays an image on # a single quadrilateral plane. It does this using texture mapping and as # a result is quite fast. (Note: the input image has to be unsigned char # values, which the vtkImageMapToColors produces.) Note also that by # specifying the DisplayExtent, the pipeline requests data of this extent # and the vtkImageMapToColors only processes a slice of data. sagittal_colors = vtk.vtkImageMapToColors() sagittal_colors.SetInputConnection(reader.GetOutputPort()) sagittal_colors.SetLookupTable(bw_lut) sagittal_colors.Update() sagittal = vtk.vtkImageActor() sagittal.GetMapper().SetInputConnection(sagittal_colors.GetOutputPort()) sagittal.SetDisplayExtent(128, 128, 0, 255, 0, 92) sagittal.ForceOpaqueOn() # Create the second (axial) plane of the three planes. We use the # same approach as before except that the extent differs. axial_colors = vtk.vtkImageMapToColors() axial_colors.SetInputConnection(reader.GetOutputPort()) axial_colors.SetLookupTable(hue_lut) axial_colors.Update() axial = vtk.vtkImageActor() axial.GetMapper().SetInputConnection(axial_colors.GetOutputPort()) axial.SetDisplayExtent(0, 255, 0, 255, 46, 46) axial.ForceOpaqueOn() # Create the third (coronal) plane of the three planes. We use # the same approach as before except that the extent differs. coronal_colors = vtk.vtkImageMapToColors() coronal_colors.SetInputConnection(reader.GetOutputPort()) coronal_colors.SetLookupTable(sat_lut) coronal_colors.Update() coronal = vtk.vtkImageActor() coronal.GetMapper().SetInputConnection(coronal_colors.GetOutputPort()) coronal.SetDisplayExtent(0, 255, 128, 128, 0, 92) coronal.ForceOpaqueOn() # It is convenient to create an initial view of the data. The # FocalPoint and Position form a vector direction. Later on # (ResetCamera() method) this vector is used to position the camera # to look at the data in this direction. a_camera = vtk.vtkCamera() a_camera.SetViewUp(0, 0, -1) a_camera.SetPosition(0, -1, 0) a_camera.SetFocalPoint(0, 0, 0) a_camera.ComputeViewPlaneNormal() a_camera.Azimuth(30.0) a_camera.Elevation(30.0) # Actors are added to the renderer. a_renderer.AddActor(outline) a_renderer.AddActor(sagittal) a_renderer.AddActor(axial) a_renderer.AddActor(coronal) a_renderer.AddActor(skin) a_renderer.AddActor(bone) # Turn off bone for this example. bone.VisibilityOff() # Set skin to semi-transparent. skin.GetProperty().SetOpacity(0.5) # An initial camera view is created. The Dolly() method moves # the camera towards the FocalPoint, thereby enlarging the image. a_renderer.SetActiveCamera(a_camera) # Calling Render() directly on a vtkRenderer is strictly forbidden. # Only calling Render() on the vtkRenderWindow is a valid call. ren_win.SetWindowName('MedicalDemo3') ren_win.Render() a_renderer.ResetCamera() a_camera.Dolly(1.5) # Note that when camera movement occurs (as it does in the Dolly() # method), the clipping planes often need adjusting. Clipping planes # consist of two planes: near and far along the view direction. The # near plane clips out objects in front of the plane; the far plane # clips out objects behind the plane. This way only what is drawn # between the planes is actually rendered. a_renderer.ResetCameraClippingRange() # Interact with the data. ren_win.Render() iren.Initialize() iren.Start()
def main(): # vtkFlyingEdges3D was introduced in VTK >= 8.2 use_flying_edges = vtk_version_ok(8, 2, 0) colors = vtk.vtkNamedColors() sample_resolution = get_program_parameters() # Create a sampled sphere implicit_sphere = vtk.vtkSphere() radius = 1.0 implicit_sphere.SetRadius(radius) sampled_sphere = vtk.vtkSampleFunction() sampled_sphere.SetSampleDimensions(sample_resolution, sample_resolution, sample_resolution) x_min = -radius * 2.0 x_max = radius * 2.0 sampled_sphere.SetModelBounds(x_min, x_max, x_min, x_max, x_min, x_max) sampled_sphere.SetImplicitFunction(implicit_sphere) if use_flying_edges: try: iso_sphere = vtk.vtkFlyingEdges3D() except AttributeError: iso_sphere = vtk.vtkMarchingCubes() else: iso_sphere = vtk.vtkMarchingCubes() iso_sphere.SetValue(0, 1.0) iso_sphere.SetInputConnection(sampled_sphere.GetOutputPort()) # Create a sampled cylinder implicit_cylinder = vtk.vtkCylinder() implicit_cylinder.SetRadius(radius / 2.0) sampled_cylinder = vtk.vtkSampleFunction() sampled_cylinder.SetSampleDimensions(sample_resolution, sample_resolution, sample_resolution) sampled_cylinder.SetModelBounds(x_min, x_max, x_min, x_max, x_min, x_max) sampled_cylinder.SetImplicitFunction(implicit_cylinder) # Probe cylinder with the sphere isosurface probe_cylinder = vtk.vtkProbeFilter() probe_cylinder.SetInputConnection(0, iso_sphere.GetOutputPort()) probe_cylinder.SetInputConnection(1, sampled_cylinder.GetOutputPort()) probe_cylinder.Update() # Restore the original normals probe_cylinder.GetOutput().GetPointData().SetNormals( iso_sphere.GetOutput().GetPointData().GetNormals()) print('Scalar range: {:6.3f}, {:6.3f}'.format( probe_cylinder.GetOutput().GetScalarRange()[0], probe_cylinder.GetOutput().GetScalarRange()[1])) # Create a mapper and actor map_sphere = vtk.vtkPolyDataMapper() map_sphere.SetInputConnection(probe_cylinder.GetOutputPort()) map_sphere.SetScalarRange(probe_cylinder.GetOutput().GetScalarRange()) sphere = vtk.vtkActor() sphere.SetMapper(map_sphere) # Visualize renderer = vtk.vtkRenderer() render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) render_window.SetWindowName('IsosurfaceSampling') render_window_interactor = vtk.vtkRenderWindowInteractor() render_window_interactor.SetRenderWindow(render_window) renderer.AddActor(sphere) renderer.SetBackground(colors.GetColor3d('AliceBlue')) render_window.Render() render_window_interactor.Start()
#!/usr/bin/env python import vtk from vtk.test import Testing # Controls size of test res = 15 # Create an initial set of data wavelet = vtk.vtkRTAnalyticSource() wavelet.SetWholeExtent(-res, res, -res, res, -res, res) wavelet.Update() # Isocontour contour = vtk.vtkFlyingEdges3D() contour.SetInputConnection(wavelet.GetOutputPort()) contour.SetValue(0, 100) contour.SetValue(1, 200) contour.Update() # Build the locator locator = vtk.vtkStaticCellLocator() locator.SetDataSet(contour.GetOutput()) locator.AutomaticOn() locator.SetNumberOfCellsPerNode(20) locator.CacheCellBoundsOn() locator.BuildLocator() # Now extract cells from locator and display it origin = [0, 0, 0] normal = [1, 1, 1] cellIds = vtk.vtkIdList()
gaussian.Update() if 1: isoValue = 127.5 mcubes = vtk.vtkMarchingCubes() mcubes.SetInputConnection(gaussian.GetOutputPort()) mcubes.ComputeScalarsOff() mcubes.ComputeGradientsOff() mcubes.ComputeNormalsOff() mcubes.SetValue(0, isoValue) else: # Fast fixed-point versions #mcubes = vtk.vtkDiscreteFlyingEdges3D() #mcubes.SetInputConnection(selectTissue.GetOutputPort()) #mcubes.GenerateValues(1, 0, 254) mcubes = vtk.vtkFlyingEdges3D() mcubes.SetInputConnection(gaussian.GetOutputPort()) mcubes.GenerateValues(1, 190, 255) smoothingIterations = 5 # was 3 passBand = 0.001 featureAngle = 60.0 smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(mcubes.GetOutputPort()) smoother.SetNumberOfIterations(smoothingIterations) #smoother.BoundarySmoothingOff() smoother.BoundarySmoothingOn() #smoother.FeatureEdgeSmoothingOn() # Turn on smoothing along sharp interior edges smoother.FeatureEdgeSmoothingOff() # Turn off smoothing along sharp interior edges smoother.SetFeatureAngle(featureAngle) # Angle to distinguish a sharp edge
sample.SetImplicitFunction(sphere) sample.SetModelBounds(-0.5,0.5, -0.5,0.5, -0.5,0.5) sample.SetSampleDimensions(100,100,100) # Now create some new attributes cyl = vtk.vtkCylinder() cyl.SetRadius(0.1) cyl.SetAxis(1,1,1) attr = vtk.vtkSampleImplicitFunctionFilter() attr.SetInputConnection(sample.GetOutputPort()) attr.SetImplicitFunction(cyl) attr.ComputeGradientsOn() attr.Update() iso = vtk.vtkFlyingEdges3D() iso.SetInputConnection(attr.GetOutputPort()) iso.SetInputArrayToProcess(0, 0, 0, vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS, "scalars") iso.SetValue(0,0.25) iso.ComputeNormalsOn() iso.ComputeGradientsOn() iso.ComputeScalarsOn() iso.InterpolateAttributesOn() # Time execution timer = vtk.vtkTimerLog() timer.StartTimer() iso.Update() timer.StopTimer() time = timer.GetElapsedTime() print("Flying edges with attributes: {0}".format(time))
eKernel.SetKernelFootprintToRadius() eKernel.SetRadius(50.0) eKernel.UseScalarsOn() eKernel.UseNormalsOn() eKernel.SetScaleFactor(0.5) eKernel.SetEccentricity(3) eKernel.NormalizeWeightsOff() interpolator = vtk.vtkPointInterpolator() interpolator.SetInputData(volume) interpolator.SetSourceData(oneData) interpolator.SetKernel(eKernel) interpolator.Update() # Extract iso surface ------------------------------------------------ contour = vtk.vtkFlyingEdges3D() contour.SetInputConnection(interpolator.GetOutputPort()) contour.SetValue(0,10) intMapper = vtk.vtkPolyDataMapper() intMapper.SetInputConnection(contour.GetOutputPort()) intActor = vtk.vtkActor() intActor.SetMapper(intMapper) # Create an outline outline = vtk.vtkOutlineFilter() outline.SetInputData(volume) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort())
# ren1 = vtk.vtkRenderer() ren2 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.SetMultiSamples(0) renWin.AddRenderer(ren1) renWin.AddRenderer(ren2) ren1.SetViewport(0,0,0.5,1) ren2.SetViewport(0.5,0,1,1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Test the negative extents source = vtk.vtkRTAnalyticSource() iso = vtk.vtkFlyingEdges3D() iso.SetInputConnection(source.GetOutputPort()) iso.SetValue(0,150) isoMapper = vtk.vtkPolyDataMapper() isoMapper.SetInputConnection(iso.GetOutputPort()) isoMapper.ScalarVisibilityOff() isoActor = vtk.vtkActor() isoActor.SetMapper(isoMapper) isoActor.GetProperty().SetColor(1,1,1) isoActor.GetProperty().SetOpacity(1) outline = vtk.vtkOutlineFilter() outline.SetInputConnection(source.GetOutputPort())
def create_frog_actor(frog_fn, frog_tissue_fn, tissue, flying_edges, decimate, lut): # Get the tissue parameters pixel_size = tissue['PIXEL_SIZE'] columns = tissue['COLUMNS'] rows = tissue['ROWS'] voi = tissue['VOI'] spacing = float(tissue['SPACING']) start_slice = float(tissue['START_SLICE']) data_spacing = [pixel_size, pixel_size, spacing] data_origin = [-(columns / 2.0) * pixel_size, -(rows / 2.0) * pixel_size, start_slice * spacing] # # adjust y bounds for PNM coordinate system # tmp = voi[2] voi[2] = rows - voi[3] - 1 voi[3] = rows - tmp - 1 if tissue['NAME'] == 'skin': fn = frog_fn else: fn = frog_tissue_fn reader = vtk.vtkMetaImageReader() reader.SetFileName(str(fn)) reader.SetDataSpacing(data_spacing) reader.SetDataOrigin(data_origin) reader.SetDataExtent(voi) reader.Update() last_connection = reader if not tissue['NAME'] == 'skin': if tissue['ISLAND_REPLACE'] >= 0: island_remover = vtk.vtkImageIslandRemoval2D() island_remover.SetAreaThreshold(tissue['ISLAND_AREA']) island_remover.SetIslandValue(tissue['ISLAND_REPLACE']) island_remover.SetReplaceValue(tissue['TISSUE']) island_remover.SetInput(last_connection.GetOutput()) island_remover.Update() last_connection = island_remover select_tissue = vtk.vtkImageThreshold() select_tissue.ThresholdBetween(tissue['TISSUE'], tissue['TISSUE']) select_tissue.SetInValue(255) select_tissue.SetOutValue(0) select_tissue.SetInputConnection(last_connection.GetOutputPort()) last_connection = select_tissue shrinker = vtk.vtkImageShrink3D() shrinker.SetInputConnection(last_connection.GetOutputPort()) shrinker.SetShrinkFactors(tissue['SAMPLE_RATE']) shrinker.AveragingOn() last_connection = shrinker if not all(v == 0 for v in tissue['GAUSSIAN_STANDARD_DEVIATION']): gaussian = vtk.vtkImageGaussianSmooth() gaussian.SetStandardDeviation(*tissue['GAUSSIAN_STANDARD_DEVIATION']) gaussian.SetRadiusFactors(*tissue['GAUSSIAN_RADIUS_FACTORS']) gaussian.SetInputConnection(shrinker.GetOutputPort()) last_connection = gaussian # Time the isocontouring. ict = collections.defaultdict() iso_value = tissue['VALUE'] if flying_edges: iso_surface = vtk.vtkFlyingEdges3D() iso_surface.SetInputConnection(last_connection.GetOutputPort()) iso_surface.ComputeScalarsOff() iso_surface.ComputeGradientsOff() iso_surface.ComputeNormalsOff() iso_surface.SetValue(0, iso_value) timer = vtk.vtkExecutionTimer() timer.SetFilter(iso_surface) iso_surface.Update() ict['Flying Edges'] = timer.GetElapsedWallClockTime() else: iso_surface = vtk.vtkMarchingCubes() iso_surface.SetInputConnection(last_connection.GetOutputPort()) iso_surface.ComputeScalarsOff() iso_surface.ComputeGradientsOff() iso_surface.ComputeNormalsOff() iso_surface.SetValue(0, iso_value) timer = vtk.vtkExecutionTimer() timer.SetFilter(iso_surface) iso_surface.Update() ict['Marching Cubes'] = timer.GetElapsedWallClockTime() so = SliceOrder() # transform = so.get(tissue['SLICE_ORDER']) # Match Frog.py transform = so.get('hfap') transform.Scale(1, -1, 1) tf = vtk.vtkTransformPolyDataFilter() tf.SetTransform(transform) tf.SetInputConnection(iso_surface.GetOutputPort()) last_connection = tf if decimate: decimator = vtk.vtkDecimatePro() decimator.SetInputConnection(last_connection.GetOutputPort()) decimator.SetFeatureAngle(tissue['DECIMATE_ANGLE']) decimator.MaximumIterations = tissue['DECIMATE_ITERATIONS'] decimator.PreserveTopologyOn() decimator.SetErrorIsAbsolute(1) decimator.SetAbsoluteError(tissue['DECIMATE_ERROR']) decimator.SetTargetReduction(tissue['DECIMATE_REDUCTION']) last_connection = decimator smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(last_connection.GetOutputPort()) smoother.SetNumberOfIterations(tissue['SMOOTH_ITERATIONS']) smoother.BoundarySmoothingOff() smoother.FeatureEdgeSmoothingOff() smoother.SetFeatureAngle(tissue['SMOOTH_ANGLE']) smoother.SetPassBand(tissue['SMOOTH_FACTOR']) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOff() smoother.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(smoother.GetOutputPort()) normals.SetFeatureAngle(tissue['FEATURE_ANGLE']) stripper = vtk.vtkStripper() stripper.SetInputConnection(normals.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) # Create iso-surface contour = vtk.vtkContourFilter() contour.SetInputConnection(reader.GetOutputPort()) contour.SetValue(0, iso_value) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(tissue['OPACITY']) actor.GetProperty().SetDiffuseColor(lut.GetTableValue(tissue['TISSUE'])[:3]) actor.GetProperty().SetSpecular(0.5) actor.GetProperty().SetSpecularPower(10) return ict, actor
def CreateFrogActor(fileName, tissue, useMarchingCubes): reader = vtk.vtkMetaImageReader() reader.SetFileName(fileName) reader.Update() selectTissue = vtk.vtkImageThreshold() selectTissue.ThresholdBetween(tissue, tissue) selectTissue.SetInValue(255) selectTissue.SetOutValue(0) selectTissue.SetInputConnection(reader.GetOutputPort()) gaussianRadius = 1 gaussianStandardDeviation = 2.0 gaussian = vtk.vtkImageGaussianSmooth() gaussian.SetStandardDeviations(gaussianStandardDeviation, gaussianStandardDeviation, gaussianStandardDeviation) gaussian.SetRadiusFactors(gaussianRadius, gaussianRadius, gaussianRadius) gaussian.SetInputConnection(selectTissue.GetOutputPort()) isoValue = 127.5 smoother = vtk.vtkWindowedSincPolyDataFilter() mcubes = vtk.vtkMarchingCubes() flyingEdges = vtk.vtkFlyingEdges3D() if useMarchingCubes: mcubes.SetInputConnection(gaussian.GetOutputPort()) mcubes.ComputeScalarsOff() mcubes.ComputeGradientsOff() mcubes.ComputeNormalsOff() mcubes.SetValue(0, isoValue) smoother.SetInputConnection(mcubes.GetOutputPort()) else: flyingEdges.SetInputConnection(gaussian.GetOutputPort()) flyingEdges.ComputeScalarsOff() flyingEdges.ComputeGradientsOff() flyingEdges.ComputeNormalsOff() flyingEdges.SetValue(0, isoValue) smoother.SetInputConnection(flyingEdges.GetOutputPort()) smoothingIterations = 5 passBand = 0.001 featureAngle = 60.0 smoother.SetNumberOfIterations(smoothingIterations) smoother.BoundarySmoothingOff() smoother.FeatureEdgeSmoothingOff() smoother.SetFeatureAngle(featureAngle) smoother.SetPassBand(passBand) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() smoother.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(smoother.GetOutputPort()) normals.SetFeatureAngle(featureAngle) stripper = vtk.vtkStripper() stripper.SetInputConnection(normals.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def main(): # vtkFlyingEdges3D was introduced in VTK >= 8.2 use_flying_edges = vtk_version_ok(8, 2, 0) colors = vtk.vtkNamedColors() dicom_dir, iso_value = get_program_parameters() if iso_value is None and dicom_dir is not None: print('An ISO value is needed.') return () volume = vtk.vtkImageData() if dicom_dir is None: sphere_source = vtk.vtkSphereSource() sphere_source.SetPhiResolution(20) sphere_source.SetThetaResolution(20) sphere_source.Update() bounds = list(sphere_source.GetOutput().GetBounds()) for i in range(0, 6, 2): dist = bounds[i + 1] - bounds[i] bounds[i] = bounds[i] - 0.1 * dist bounds[i + 1] = bounds[i + 1] + 0.1 * dist voxel_modeller = vtk.vtkVoxelModeller() voxel_modeller.SetSampleDimensions(50, 50, 50) voxel_modeller.SetModelBounds(bounds) voxel_modeller.SetScalarTypeToFloat() voxel_modeller.SetMaximumDistance(0.1) voxel_modeller.SetInputConnection(sphere_source.GetOutputPort()) voxel_modeller.Update() iso_value = 0.5 volume.DeepCopy(voxel_modeller.GetOutput()) else: reader = vtk.vtkDICOMImageReader() reader.SetDirectoryName(dicom_dir) reader.Update() volume.DeepCopy(reader.GetOutput()) if use_flying_edges: try: surface = vtk.vtkFlyingEdges3D() except AttributeError: surface = vtk.vtkMarchingCubes() else: surface = vtk.vtkMarchingCubes() surface.SetInputData(volume) surface.ComputeNormalsOn() surface.SetValue(0, iso_value) renderer = vtk.vtkRenderer() renderer.SetBackground(colors.GetColor3d('DarkSlateGray')) render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) render_window.SetWindowName('MarchingCubes') interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(render_window) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(surface.GetOutputPort()) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(colors.GetColor3d('MistyRose')) renderer.AddActor(actor) render_window.Render() interactor.Start()
def main(): # vtkFlyingEdges3D was introduced in VTK >= 8.2 use_flying_edges = vtk_version_ok(8, 2, 0) colors = vtk.vtkNamedColors() file_name = get_program_parameters() colors.SetColor('SkinColor', [240, 184, 160, 255]) colors.SetColor('BackfaceColor', [255, 229, 200, 255]) colors.SetColor('BkgColor', [51, 77, 102, 255]) # Create the renderer, the render window, and the interactor. The renderer # draws into the render window, the interactor enables mouse- and # keyboard-based interaction with the data within the render window. # a_renderer = vtk.vtkRenderer() ren_win = vtk.vtkRenderWindow() ren_win.AddRenderer(a_renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(ren_win) reader = vtk.vtkMetaImageReader() reader.SetFileName(file_name) # An isosurface, or contour value of 500 is known to correspond to the # skin of the patient. if use_flying_edges: try: skin_extractor = vtk.vtkFlyingEdges3D() except AttributeError: skin_extractor = vtk.vtkMarchingCubes() else: skin_extractor = vtk.vtkMarchingCubes() skin_extractor.SetInputConnection(reader.GetOutputPort()) skin_extractor.SetValue(0, 500) skin_mapper = vtk.vtkPolyDataMapper() skin_mapper.SetInputConnection(skin_extractor.GetOutputPort()) skin_mapper.ScalarVisibilityOff() skin = vtk.vtkActor() skin.SetMapper(skin_mapper) skin.GetProperty().SetDiffuseColor(colors.GetColor3d('SkinColor')) back_prop = vtk.vtkProperty() back_prop.SetDiffuseColor(colors.GetColor3d('BackfaceColor')) skin.SetBackfaceProperty(back_prop) # An outline provides context around the data. # outline_data = vtk.vtkOutlineFilter() outline_data.SetInputConnection(reader.GetOutputPort()) map_outline = vtk.vtkPolyDataMapper() map_outline.SetInputConnection(outline_data.GetOutputPort()) outline = vtk.vtkActor() outline.SetMapper(map_outline) outline.GetProperty().SetColor(colors.GetColor3d('Black')) # It is convenient to create an initial view of the data. The FocalPoint # and Position form a vector direction. Later on (ResetCamera() method) # this vector is used to position the camera to look at the data in # this direction. a_camera = vtk.vtkCamera() a_camera.SetViewUp(0, 0, -1) a_camera.SetPosition(0, -1, 0) a_camera.SetFocalPoint(0, 0, 0) a_camera.ComputeViewPlaneNormal() a_camera.Azimuth(30.0) a_camera.Elevation(30.0) # Actors are added to the renderer. An initial camera view is created. # The Dolly() method moves the camera towards the FocalPoint, # thereby enlarging the image. a_renderer.AddActor(outline) a_renderer.AddActor(skin) a_renderer.SetActiveCamera(a_camera) a_renderer.ResetCamera() a_camera.Dolly(1.5) # Set a background color for the renderer and set the size of the # render window (expressed in pixels). a_renderer.SetBackground(colors.GetColor3d('BkgColor')) ren_win.SetSize(640, 480) ren_win.SetWindowName('MedicalDemo1') # Note that when camera movement occurs (as it does in the Dolly() # method), the clipping planes often need adjusting. Clipping planes # consist of two planes: near and far along the view direction. The # near plane clips out objects in front of the plane the far plane # clips out objects behind the plane. This way only what is drawn # between the planes is actually rendered. a_renderer.ResetCameraClippingRange() # Initialize the event loop and then start it. iren.Initialize() iren.Start()
def main(): # vtkFlyingEdges3D was introduced in VTK >= 8.2 use_flying_edges = vtk_version_ok(8, 2, 0) colors = vtk.vtkNamedColors() file_name = get_program_parameters() colors.SetColor('SkinColor', [240, 184, 160, 255]) colors.SetColor('BackfaceColor', [255, 229, 200, 255]) colors.SetColor('BkgColor', [51, 77, 102, 255]) # Read the volume data reader = vtk.vtkMetaImageReader() reader.SetFileName(file_name) reader.Update() # An isosurface, or contour value of 500 is known to correspond to the # skin of the patient. if use_flying_edges: try: skin_extractor = vtk.vtkFlyingEdges3D() except AttributeError: skin_extractor = vtk.vtkMarchingCubes() else: skin_extractor = vtk.vtkMarchingCubes() skin_extractor.SetInputConnection(reader.GetOutputPort()) skin_extractor.SetValue(0, 500) # Define a spherical clip function to clip the isosurface clip_function = vtk.vtkSphere() clip_function.SetRadius(50) clip_function.SetCenter(73, 52, 15) # Clip the isosurface with a sphere skin_clip = vtk.vtkClipDataSet() skin_clip.SetInputConnection(skin_extractor.GetOutputPort()) skin_clip.SetClipFunction(clip_function) skin_clip.SetValue(0) skin_clip.GenerateClipScalarsOn() skin_clip.Update() skin_mapper = vtk.vtkDataSetMapper() skin_mapper.SetInputConnection(skin_clip.GetOutputPort()) skin_mapper.ScalarVisibilityOff() skin = vtk.vtkActor() skin.SetMapper(skin_mapper) skin.GetProperty().SetDiffuseColor(colors.GetColor3d('SkinColor')) back_prop = vtk.vtkProperty() back_prop.SetDiffuseColor(colors.GetColor3d('BackfaceColor')) skin.SetBackfaceProperty(back_prop) # Define a model for the "lens". Its geometry matches the implicit # sphere used to clip the isosurface lens_model = vtk.vtkSphereSource() lens_model.SetRadius(50) lens_model.SetCenter(73, 52, 15) lens_model.SetPhiResolution(201) lens_model.SetThetaResolution(101) # Sample the input volume with the lens model geometry lens_probe = vtk.vtkProbeFilter() lens_probe.SetInputConnection(lens_model.GetOutputPort()) lens_probe.SetSourceConnection(reader.GetOutputPort()) # Clip the lens data with the isosurface value lens_clip = vtk.vtkClipDataSet() lens_clip.SetInputConnection(lens_probe.GetOutputPort()) lens_clip.SetValue(500) lens_clip.GenerateClipScalarsOff() lens_clip.Update() # Define a suitable grayscale lut bw_lut = vtk.vtkLookupTable() bw_lut.SetTableRange(0, 2048) bw_lut.SetSaturationRange(0, 0) bw_lut.SetHueRange(0, 0) bw_lut.SetValueRange(0.2, 1) bw_lut.Build() lens_mapper = vtk.vtkDataSetMapper() lens_mapper.SetInputConnection(lens_clip.GetOutputPort()) lens_mapper.SetScalarRange(lens_clip.GetOutput().GetScalarRange()) lens_mapper.SetLookupTable(bw_lut) lens = vtk.vtkActor() lens.SetMapper(lens_mapper) # It is convenient to create an initial view of the data. The FocalPoint # and Position form a vector direction. Later on (ResetCamera() method) # this vector is used to position the camera to look at the data in # this direction. a_camera = vtk.vtkCamera() a_camera.SetViewUp(0, 0, -1) a_camera.SetPosition(0, -1, 0) a_camera.SetFocalPoint(0, 0, 0) a_camera.ComputeViewPlaneNormal() a_camera.Azimuth(30.0) a_camera.Elevation(30.0) # Create the renderer, the render window, and the interactor. The renderer # draws into the render window, the interactor enables mouse- and # keyboard-based interaction with the data within the render window. # a_renderer = vtk.vtkRenderer() ren_win = vtk.vtkRenderWindow() ren_win.AddRenderer(a_renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(ren_win) # Actors are added to the renderer. An initial camera view is created. # The Dolly() method moves the camera towards the FocalPoint, # thereby enlarging the image. a_renderer.AddActor(lens) a_renderer.AddActor(skin) a_renderer.SetActiveCamera(a_camera) a_renderer.ResetCamera() a_camera.Dolly(1.5) # Set a background color for the renderer and set the size of the # render window (expressed in pixels). a_renderer.SetBackground(colors.GetColor3d('BkgColor')) ren_win.SetSize(640, 480) ren_win.SetWindowName('TissueLens') # Note that when camera movement occurs (as it does in the Dolly() # method), the clipping planes often need adjusting. Clipping planes # consist of two planes: near and far along the view direction. The # near plane clips out objects in front of the plane the far plane # clips out objects behind the plane. This way only what is drawn # between the planes is actually rendered. a_renderer.ResetCameraClippingRange() # Initialize the event loop and then start it. ren_win.Render() iren.Initialize() iren.Start()
pts.SetNumberOfPoints(NPts) for i in range(0,NPts): pts.SetPoint(i,math.Random(-1,1),math.Random(-1,1),math.Random(-1,1)) polyData.SetPoints(pts); # Generate signed distance function and contour it dist = vtk.vtkUnsignedDistance() dist.SetInputData(polyData) dist.SetRadius(0.25) #how far out to propagate distance calculation dist.SetDimensions(res,res,res) dist.CappingOn() dist.AdjustBoundsOn() dist.SetAdjustDistance(0.01) # Extract the surface with modified flying edges fe = vtk.vtkFlyingEdges3D() fe.SetInputConnection(dist.GetOutputPort()) fe.SetValue(0, 0.075) fe.ComputeNormalsOff() # Time the execution timer = vtk.vtkTimerLog() timer.StartTimer() fe.Update() timer.StopTimer() time = timer.GetElapsedTime() print("Points processed: {0}".format(NPts)) print(" Time to generate and extract distance function: {0}".format(time)) print(dist) feMapper = vtk.vtkPolyDataMapper()
def create_brain_extractor(reader, threshold): brain_extractor = vtk.vtkFlyingEdges3D() brain_extractor.SetInputConnection(reader.GetOutputPort()) brain_extractor.SetValue(0, threshold) return brain_extractor