Exemplo n.º 1
0
    def addContourObject(self, contourObject, prop3D):
        """Activate contouring for the contourObject.  The contourObject
        is usually a tdObject and specifically a vtkPolyData.  We also
        need the prop3D that represents this polydata in the 3d scene.
        """
        if self._contourObjectsDict.has_key(contourObject):
            # we already have this, thanks
            return

        try:
            contourable = contourObject.IsA('vtkPolyData')
        except:
            contourable = False

        if contourable:
            # we need a cutter to calculate the contours and then a stripper
            # to string them all together
            cutter = vtk.vtkCutter()
            plane = vtk.vtkPlane()
            cutter.SetCutFunction(plane)
            trfm = vtk.vtkTransform()
            trfm.SetMatrix(prop3D.GetMatrix())
            trfmFilter = vtk.vtkTransformPolyDataFilter()
            trfmFilter.SetTransform(trfm)
            trfmFilter.SetInput(contourObject)
            cutter.SetInput(trfmFilter.GetOutput())
            stripper = vtk.vtkStripper()
            stripper.SetInput(cutter.GetOutput())
            
            #
            #tubef = vtk.vtkTubeFilter()
            #tubef.SetNumberOfSides(12)
            #tubef.SetRadius(0.5)
            #tubef.SetInput(stripper.GetOutput())

            # and create the overlay at least for the 3d renderer
            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInput(stripper.GetOutput())
            mapper.ScalarVisibilityOff()
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            c = self.sliceDirections.slice3dVWR._tdObjects.getObjectColour(
                contourObject)
            actor.GetProperty().SetColor(c)
            actor.GetProperty().SetInterpolationToFlat()

            # add it to the renderer
            self.sliceDirections.slice3dVWR._threedRenderer.AddActor(actor)
            
            # add all necessary metadata to our dict
            contourDict = {'contourObject' : contourObject,
                           'contourObjectProp' : prop3D,
                           'trfmFilter' : trfmFilter,
                           'cutter' : cutter,
                           'tdActor' : actor}
                           
            self._contourObjectsDict[contourObject] = contourDict

            # now sync the bugger
            self.syncContourToObject(contourObject)
Exemplo n.º 2
0
    def computeContoursAndTubes(self, source):
        # Plane for intersection
        plane = vtk.vtkPlane()
        plane.SetOrigin(source.GetOrigin())
        plane.SetNormal(source.GetNormal())

        cutEdges = vtk.vtkCutter()
        cutEdges.SetInputConnection(self.vesselNormals.GetOutputPort())
        cutEdges.SetCutFunction(plane)
        cutEdges.GenerateCutScalarsOff()  # Was on
        cutEdges.SetValue(0, 0.5)
        cutEdges.Update()

        cutStrips = vtk.vtkStripper()
        cutStrips.SetInputConnection(cutEdges.GetOutputPort())
        cutStrips.Update()
        oldContours = cutStrips.GetOutput()

        tubes = vtk.vtkTubeFilter()
        tubes.SetInputConnection(cutStrips.GetOutputPort())
        tubes.CappingOn()
        tubes.SidesShareVerticesOff()
        tubes.SetNumberOfSides(12)
        tubes.SetRadius(self.worldScale * 1.0)
        return tubes, oldContours
Exemplo n.º 3
0
def createCutFromPoint(node, color, plane):
    #z=plane.GetOrigin()[2]
    #if not isCutting(node, z):
    #   return None

    segment_source = createSourceFromPoint(node)
    segment_normal = vtk.vtkPolyDataNormals()
    segment_normal.SetInputConnection(segment_source.GetOutputPort())
    cutEdges = vtk.vtkCutter()
    cutEdges.SetInputConnection(segment_normal.GetOutputPort())
    cutEdges.SetCutFunction(plane)
    cutEdges.GenerateCutScalarsOn()
    cutEdges.SetValue(0, 0.5)

    cutStrips = vtk.vtkStripper()
    cutStrips.SetInputConnection(cutEdges.GetOutputPort())
    cutStrips.Update()

    cutPoly = vtk.vtkPolyData()
    cutPoly.SetPoints(cutStrips.GetOutput().GetPoints())
    cutPoly.SetPolys(cutStrips.GetOutput().GetLines())

    cutTriangles = vtk.vtkTriangleFilter()
    cutTriangles.SetInput(cutPoly)
    cutMapper = vtk.vtkPolyDataMapper()
    cutMapper.SetInput(cutPoly)
    cutMapper.SetInputConnection(cutTriangles.GetOutputPort())

    cutActor = vtk.vtkActor()
    cutActor.SetMapper(cutMapper)
    cutActor.GetProperty().SetColor(color[0], color[1], color[2])

    return cutActor
Exemplo n.º 4
0
    def get_isosurface(self, iso_value=500):

        if not self.flag_read:
            sys.stderr.write('No Image Loaded!\n')
            return

        contour = vtk.vtkContourFilter()
        normals = vtk.vtkPolyDataNormals()
        stripper = vtk.vtkStripper()
        mapper = vtk.vtkPolyDataMapper()

        contour.SetInputData(self.reader)
        contour.SetValue(0, iso_value)

        normals.SetInputConnection(contour.GetOutputPort())
        normals.SetFeatureAngle(60.0)
        normals.ReleaseDataFlagOn()

        stripper.SetInputConnection(normals.GetOutputPort())
        stripper.ReleaseDataFlagOn()

        mapper.SetInputConnection(stripper.GetOutputPort())
        mapper.SetScalarVisibility(False)

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        # Default colour, should be changed.
        actor.GetProperty().SetDiffuseColor(
            [247.0 / 255.0, 150.0 / 255.0, 155.0 / 255.0])  # Look like red
        actor.GetProperty().SetSpecular(0.3)
        actor.GetProperty().SetSpecularPower(20)

        return actor
Exemplo n.º 5
0
def extract(color, isovalue):
    skinExtractor = vtk.vtkDiscreteMarchingCubes()
    skinExtractor.SetInputConnection(dataImporter.GetOutputPort())
    skinExtractor.SetValue(0, isovalue)

    smooth = vtk.vtkSmoothPolyDataFilter()
    smooth.SetInputConnection(skinExtractor.GetOutputPort())
    smooth.SetNumberOfIterations(15)
    smooth.SetRelaxationFactor(0.2)
    smooth.FeatureEdgeSmoothingOff()
    smooth.BoundarySmoothingOn()
    smooth.Update()

    skinStripper = vtk.vtkStripper()
    skinStripper.SetInputConnection(smooth.GetOutputPort())

    skinMapper = vtk.vtkOpenGLPolyDataMapper()
    skinMapper.SetInputConnection(skinStripper.GetOutputPort())
    skinMapper.ScalarVisibilityOff()

    skin = vtk.vtkOpenGLActor()
    skin.SetMapper(skinMapper)
    skin.GetProperty().SetDiffuseColor(colors.GetColor3d(color))
    skin.GetProperty().SetSpecular(.3)
    skin.GetProperty().SetSpecularPower(20)
    return skin
Exemplo n.º 6
0
    def get_slice_bounds(self, origin=0.0, isOriginRelative=False):
        # Plane used to cut
        plane = vtk.vtkPlane()
        if isOriginRelative:
            xmin, xmax, _, _, _, _ = self.bounds
            origin = origin * (xmax - xmin) + xmin
        if self.verbose:
            print(origin)
        plane.SetOrigin([origin, 0.0, 0.0])
        plane.SetNormal([1.0, 0.0, 0.0])

        # Cut a slice out of the surface and convert it to a PolyData object
        cutEdges = vtk.vtkCutter()
        cutEdges.SetInputConnection(self.surfaceN.GetOutputPort())
        cutEdges.SetCutFunction(plane)
        cutEdges.GenerateTrianglesOff()
        cutEdges.GenerateCutScalarsOff()
        cutEdges.SetValue(0, 0.0)
        cutStrips = vtk.vtkStripper()
        cutStrips.SetInputConnection(cutEdges.GetOutputPort())
        cutStrips.Update()
        points = cutStrips.GetOutput().GetPoints()
        for i in range(points.GetNumberOfPoints()):
            pt = points.GetPoint(i)
            points.SetPoint(i, (0.0, pt[1], pt[2]))
        cutStrips.GetOutput().SetPoints(points)
        lines = cutStrips.GetOutput().GetLines()
        points = cutStrips.GetOutput().GetPoints()

        cutPoly = vtk.vtkPolyData()
        cutPoly.SetPoints(points)
        cutPoly.SetLines(lines)
        bounds = np.array(cutPoly.GetBounds())
        return bounds
Exemplo n.º 7
0
def Test3(datadir):
    reader = vtk.vtkDataSetReader()
    reader.SetFileName(datadir + "/Data/blow.vtk")
    reader.UpdateInformation();
    reader.ReadAllScalarsOn()
    reader.ReadAllVectorsOn()

    dssf = vtk.vtkDataSetSurfaceFilter()
    dssf.SetInputConnection(reader.GetOutputPort())

    stripper = vtk.vtkStripper()
    stripper.SetInputConnection(dssf.GetOutputPort())

    f = vtk.vtkIntegrateAttributes()
    f.SetInputConnection(stripper.GetOutputPort())
    f.Update()

    result = f.GetOutputDataObject(0)
    val = result.GetPointData().GetArray("displacement1").GetValue(0)
    assert (val > 463.64 and val < 463.642)

    val = result.GetPointData().GetArray("thickness3").GetValue(0)
    assert (val > 874.61 and val < 874.618)

    val = result.GetCellData().GetArray("Area").GetValue(0)
    assert (val > 1145.405 and val < 1145.415)
Exemplo n.º 8
0
    def get_isosurface(self, iso_value=500):

        if not self.flag_read:
            sys.stderr.write('No Image Loaded!\n')
            return

        contour = vtk.vtkContourFilter()
        normals = vtk.vtkPolyDataNormals()
        stripper = vtk.vtkStripper()
        mapper = vtk.vtkPolyDataMapper()

        contour.SetInputData(self.reader)
        contour.SetValue(0, iso_value)

        normals.SetInputConnection(contour.GetOutputPort())
        normals.SetFeatureAngle(60.0)
        normals.ReleaseDataFlagOn()

        stripper.SetInputConnection(normals.GetOutputPort())
        stripper.ReleaseDataFlagOn()

        mapper.SetInputConnection(stripper.GetOutputPort())
        mapper.SetScalarVisibility(False)

        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        # Default colour, should be changed.
        actor.GetProperty().SetDiffuseColor(
            [247.0 / 255.0, 150.0 / 255.0, 155.0 / 255.0])  # Look like red
        actor.GetProperty().SetSpecular(0.3)
        actor.GetProperty().SetSpecularPower(20)

        return actor
Exemplo n.º 9
0
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
Exemplo n.º 10
0
def create_sliced_skin():
    plane = vtk.vtkPlane()

    impl_plane = vtk.vtkImplicitBoolean()
    impl_plane.SetOperationTypeToDifference()
    impl_plane.AddFunction(plane)

    cf = create_contour(SKIN_ISO_VALUE)

    cutter = vtk.vtkCutter()
    cutter.SetInputConnection(cf.GetOutputPort())
    cutter.SetCutFunction(plane)

    for i in range(19):
        cutter.SetValue(i, i * 11)

    stripper = vtk.vtkStripper()
    stripper.SetInputConnection(cutter.GetOutputPort())
    stripper.Update()

    tube_filter = vtk.vtkTubeFilter()
    tube_filter.SetInputConnection(stripper.GetOutputPort())
    tube_filter.SetRadius(2.0)

    mapper_skin = vtk.vtkPolyDataMapper()
    mapper_skin.SetInputConnection(tube_filter.GetOutputPort())
    mapper_skin.SetScalarVisibility(0)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper_skin)
    actor.GetProperty().SetColor(SKIN_COLOR)

    return actor
Exemplo n.º 11
0
def repeated_cuts(vtk_contour, nb_cuts):
    """Cut the given object nb_cuts times using a plane, a cutter and a tube filter
    :param vtk_contour: The object to cut in tubes
    :param nb_cuts: The number of tubes to cut
    :returns: An actor representing the object cut in nb_cuts tubes separated by 10
    """
    plane = vtk.vtkPlane()
    plane.SetOrigin(0, 0, 0)

    plane_cutter = vtk.vtkCutter()
    plane_cutter.SetInputConnection(vtk_contour.GetOutputPort())
    plane_cutter.SetCutFunction(plane)

    for i in range(nb_cuts + 1):
        # Add cut values and separate each cut by a space of 10
        plane_cutter.SetValue(i, i * 10)

    stripper = vtk.vtkStripper()
    stripper.SetInputConnection(plane_cutter.GetOutputPort())
    stripper.Update()

    tube_filter = vtk.vtkTubeFilter()
    tube_filter.SetInputConnection(stripper.GetOutputPort())
    tube_filter.SetRadius(1)
    tube_filter.Update()

    return create_actor(tube_filter)
Exemplo n.º 12
0
    def _SliceModel(self, plane):
        """cuts surface and returns polydata of the clipped surface and the clipped face"""
        cutter = vtk.vtkCutter()
        cutter.SetCutFunction(plane)
        cutter.SetInputData(self.Surface)
        cutter.Update()

        FeatureEdges = vtk.vtkFeatureEdges()
        FeatureEdges.SetInputConnection(cutter.GetOutputPort())
        FeatureEdges.BoundaryEdgesOn()
        FeatureEdges.FeatureEdgesOff()
        FeatureEdges.NonManifoldEdgesOff()
        FeatureEdges.ManifoldEdgesOff()
        FeatureEdges.Update()

        cutStrips = vtk.vtkStripper(
        )  # Forms loops (closed polylines) from cutter
        cutStrips.SetInputConnection(cutter.GetOutputPort())
        cutStrips.Update()
        cutPoly = vtk.vtkPolyData(
        )  # This trick defines polygons as polyline loop
        cutPoly.SetPoints((cutStrips.GetOutput()).GetPoints())
        cutPoly.SetPolys((cutStrips.GetOutput()).GetLines())

        return cutter.GetOutput(), cutPoly
def Convert(image: Image_Data, threshold1, threshold2, smooth_iterations=0):
    '''
    Input: 需转换的图像,两个阈值,平滑迭代次数
    Output: 转换得到的曲面数据
    Description: 使用Marching cube方法将标签图转换为曲面,并平滑。两个阈值间的灰度范围为前景,其余部分为背景
    '''
    label = Threshold_Seg.Threshold(image, threshold1, threshold2)

    Extractor = vtk.vtkMarchingCubes()
    Extractor.SetInputData(label.Get_vtkImageData())
    Extractor.SetValue(0, 1)
    Smoother = vtk.vtkSmoothPolyDataFilter()
    Smoother.SetInputConnection(Extractor.GetOutputPort())
    Smoother.SetNumberOfIterations(smooth_iterations)
    Smoother.SetRelaxationFactor(0.1)
    Smoother.FeatureEdgeSmoothingOff()
    Smoother.BoundarySmoothingOn()
    Smoother.Update()
    Normals = vtk.vtkPolyDataNormals()
    Normals.SetInputConnection(Smoother.GetOutputPort())
    Normals.SetFeatureAngle(60.0)
    Stripper = vtk.vtkStripper()
    Stripper.SetInputConnection(Normals.GetOutputPort())
    Stripper.Update()

    polydata = Poly_Data()
    polydata.Init_From_Vtk(Stripper.GetOutput())
    return polydata
Exemplo n.º 14
0
def CreateFrogActor(fileName, tissue):
    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())

    isoValue = 63.5
    mcubes = vtk.vtkMarchingCubes()
    mcubes.SetInputConnection(selectTissue.GetOutputPort())
    mcubes.ComputeScalarsOff()
    mcubes.ComputeGradientsOff()
    mcubes.ComputeNormalsOn()
    mcubes.SetValue(0, isoValue)

    stripper = vtk.vtkStripper()
    stripper.SetInputConnection(mcubes.GetOutputPort())

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(stripper.GetOutputPort())

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor
Exemplo n.º 15
0
    def _load_level_actor(self, map_dataset):
        '''
        sphere = vtk.vtkSphere()
        sphere.SetCenter(0, 0, 0)
        sphere.SetRadius(altitude + EARTH_RADIUS)
        '''

        # creating the cutter
        self.level_cutter = vtk.vtkCutter()
        #cutter.SetCutFunction(sphere)
        self.level_cutter.SetInputData(map_dataset)

        # making it as a tube
        # using a stripper makes the tube smoother
        stripper = vtk.vtkStripper()
        stripper.SetInputConnection(self.level_cutter.GetOutputPort())
        tubeFilter = vtk.vtkTubeFilter()
        tubeFilter.SetRadius(40)
        tubeFilter.SetInputConnection(stripper.GetOutputPort())

        # creates the mapper and the actor
        mapper = vtk.vtkDataSetMapper()
        mapper.ScalarVisibilityOff()
        mapper.SetInputConnection(tubeFilter.GetOutputPort())
        level_actor = vtk.vtkActor()
        level_actor.SetMapper(mapper)
        level_actor.GetProperty().SetColor(0, 0.633, 0.91)
        self.GetDefaultRenderer().AddActor(level_actor)
Exemplo n.º 16
0
def CreateFrogActor(fileName, tissue):
    #reader = vtk.vtkMetaImageReader()
    reader = vtk.vtkXMLImageDataReader()
    reader.SetFileName(fileName)
    reader.Update()

    selectTissue = vtk.vtkImageThreshold()
    #selectTissue.ThresholdBetween(tissue, tissue)
    selectTissue.ThresholdBetween(120, 125)
    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 = 130
    mcubes = vtk.vtkMarchingCubes()
    #mcubes.SetInputConnection(gaussian.GetOutputPort())
    mcubes.SetInputConnection(reader.GetOutputPort())
    mcubes.ComputeScalarsOff()
    mcubes.ComputeGradientsOff()
    mcubes.ComputeNormalsOff()
    mcubes.SetValue(0, isoValue)

    smoothingIterations = 5
    passBand = 0.001
    featureAngle = 60.0
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputConnection(mcubes.GetOutputPort())
    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
Exemplo n.º 17
0
def actor_mesh_cut_brainstem(polydata, color=(1.,1.,1.), wireframe=False, origin=(0,0,0),\
                   cut_plane_origin = (-60,0,0),cut_plane_normal = (1,0,0),cut_plane_width = 2):
    """
    Args:
        color (float array): rgb between 0 and 1.
        origin: the initial shift for the mesh.
    """

    if polydata.GetNumberOfPoints() == 0:
        return None

    if origin[0] == 0 and origin[1] == 0 and origin[2] == 0:
        polydata_shifted = polydata
    else:
        polydata_shifted = move_polydata(polydata, origin)
        # Note that move_polydata() discards scalar data stored in polydata.

    # Set up cut plane
    plane = vtk.vtkPlane()
    plane.SetOrigin(cut_plane_origin)
    plane.SetNormal(cut_plane_normal)

    # Set up cutter for volume display
    cutter = vtk.vtkCutter()
    cutter.SetCutFunction(plane)
    cutter.SetInputData(polydata_shifted)
    cutter.Update()
    cutterMapper = vtk.vtkPolyDataMapper()
    cutterMapper.SetInputConnection(cutter.GetOutputPort())

    # Make actor for plane display in volume
    planeCutActor = vtk.vtkActor()
    planeCutActor.GetProperty().SetColor(color)
    planeCutActor.GetProperty().SetLineWidth(cut_plane_width)
    planeCutActor.SetMapper(cutterMapper)

    # Set up cutter for slice display
    cutEdges = vtk.vtkCutter()
    cutEdges.SetInputData(polydata_shifted)
    cutEdges.SetCutFunction(plane)
    cutStrips = vtk.vtkStripper()
    cutStrips.SetInputConnection(cutEdges.GetOutputPort())
    cutStrips.Update()
    cutPoly = vtk.vtkPolyData()
    cutPoly.SetPoints(cutStrips.GetOutput().GetPoints())
    cutPoly.SetPolys(cutStrips.GetOutput().GetLines())

    cutMapper = vtk.vtkPolyDataMapper()
    cutMapper.SetInputData(cutPoly)

    sliceCutActor = vtk.vtkActor()
    sliceCutActor.GetProperty().SetEdgeColor(color)
    sliceCutActor.GetProperty().SetLineWidth(2)
    sliceCutActor.GetProperty().EdgeVisibilityOn()
    sliceCutActor.GetProperty().SetSpecular(0.0)
    sliceCutActor.GetProperty().SetDiffuse(0.0)
    sliceCutActor.SetMapper(cutMapper)

    return (planeCutActor, sliceCutActor)
Exemplo n.º 18
0
 def reverse_lines(self, source):
     strip = vtk.vtkStripper()
     strip.SetInputData(source)
     strip.Update()
     reversed = vtk.vtkReverseSense()
     reversed.SetInputConnection(strip.GetOutputPort())
     reversed.Update()
     return reversed.GetOutput()
Exemplo n.º 19
0
def Execute(Surface, cl):
    if Surface == None:
        print 'Error: no Surface.'
        sys.exit(0)

    # Initialize
    Clipper = vtk.vtkClipPolyData()
    Clipper.SetInput(Surface)
    Clipper.GenerateClippedOutputOn()
    Clipper.SetInsideOut(0)
 
    ClipFunction = vtk.vtkPlanes()
       
    Clipper.SetClipFunction(ClipFunction)

    Cutter = vtk.vtkCutter()
    Cutter.SetInput(Surface)
    Cutter.SetCutFunction(ClipFunction)

    ClippedSurface = vtk.vtkPolyData()
    CutLines = vtk.vtkPolyData()

    ClipWidget = vtk.vtkBoxWidget()
    ClipWidget.GetFaceProperty().SetColor(0.6,0.6,0.2)
    ClipWidget.GetFaceProperty().SetOpacity(0.25)

    Transform = vtk.vtkTransform()
    ClipWidget.GetTransform(Transform)

    for i in range(cl.GetNumberOfLines()):
        # TODO: Implement thing here.

    # Clean surface
    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInput(Surface)
    cleaner.Update()
    Surface = cleaner.GetOutput()

    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInput(ClippedSurface)
    cleaner.Update()
    ClippedSurface = cleaner.GetOutput()

    cleaner = vtk.vtkCleanPolyData()
    cleaner.SetInput(CutLines)
    cleaner.Update()
    stripper = vtk.vtkStripper()
    stripper.SetInput(cleaner.GetOutput())
    stripper.Update()
    CutLines = stripper.GetOutput()

    if Surface.GetSource():
        Surface.GetSource().UnRegisterAllOutputs()


if __name__=='__main__':
    surface = read_command_line()
    Execute()
Exemplo n.º 20
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkStripper(),
                                       'Processing.', ('vtkPolyData', ),
                                       ('vtkPolyData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Exemplo n.º 21
0
def get_actor(vtk_source, color=color_diffuse, opacity=1.0,
              has_scalar_visibility=False, has_decimator=False):
    """
    Set `scalar_visibility` be `True` makes `color` unavailable.
    :return: a vtkActor
    """
    if has_decimator:
        # Reduce the number of triangles
        decimator = vtk.vtkDecimatePro()
        decimator.SetInputConnection(vtk_source.GetOutputPort())
        # decimator.SetInputData(vtk_source)
        decimator.SetFeatureAngle(60)
        decimator.MaximumIterations = 1
        decimator.PreserveTopologyOn()
        decimator.SetMaximumError(0.0002)
        decimator.SetTargetReduction(1)
        decimator.SetErrorIsAbsolute(1)
        decimator.SetAbsoluteError(0.0002)
        decimator.ReleaseDataFlagOn()

    # Generate Normals
    normals = vtk.vtkPolyDataNormals()
    if has_decimator:
        normals.SetInputConnection(decimator.GetOutputPort())
    else:
        normals.SetInputConnection(vtk_source.GetOutputPort())
    normals.SetFeatureAngle(60.0)
    normals.ReleaseDataFlagOn()

    stripper = vtk.vtkStripper()
    stripper.SetInputConnection(normals.GetOutputPort())
    stripper.ReleaseDataFlagOn()

    mapper = vtk.vtkPolyDataMapper()
    # mapper.SetInputConnection(vtk_source.GetOutputPort())
    mapper.SetInputConnection(stripper.GetOutputPort())
    mapper.SetScalarVisibility(has_scalar_visibility)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetDiffuseColor(color)
    actor.GetProperty().SetSpecular(0.3)
    actor.GetProperty().SetSpecularPower(20)
    actor.GetProperty().SetInterpolation(2)
    # actor.GetProperty().SetRepresentation(2)
    # actor.GetProperty().SetEdgeVisibility(True)
    # actor.GetProperty().SetOpacity(opacity)

    if opacity < 1.0:
        if is_depth_peeling_supported(render_window, renderer, True):
            setup_evn_for_depth_peeling(render_window, renderer, max_peels, occlusion)
            actor.GetProperty().SetOpacity(opacity)
        else:
            print "Depth Peeling is not supported."

    return actor
Exemplo n.º 22
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
Exemplo n.º 23
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self,
         module_manager,
         vtk.vtkStripper(),
         "Processing.",
         ("vtkPolyData",),
         ("vtkPolyData",),
         replaceDoc=True,
         inputFunctions=None,
         outputFunctions=None,
     )
Exemplo n.º 24
0
    def __init__(self, map_actor, text_actor):
        self.AddObserver("MouseMoveEvent", self.mouse_move_event)
        self.map_actor = map_actor
        self.text_actor = text_actor

        self.elevation_actor = vtk.vtkActor()
        self.sphere = vtk.vtkSphere()
        self.cutter = vtk.vtkCutter()
        self.stripper = vtk.vtkStripper()
        self.tube_filter = vtk.vtkTubeFilter()
        self.mapper = vtk.vtkDataSetMapper()
        self.picker = vtk.vtkPointPicker()
Exemplo n.º 25
0
    def __init__(self, parent=None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)

        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        #Create a sphere
        sphere = vtk.vtkSphereSource()
        sphere.SetRadius(50)
        sphere.SetThetaResolution(100)
        sphere.SetPhiResolution(100)

        plane = vtk.vtkPlane()
        plane.SetOrigin(20, 0, 0)
        plane.SetNormal(1, 0, 0)

        #create cutter
        cutter = vtk.vtkCutter()
        cutter.SetCutFunction(plane)
        cutter.SetInputConnection(sphere.GetOutputPort())
        cutter.Update()

        cutStrips = vtk.vtkStripper()
        cutStrips.SetInputConnection(cutter.GetOutputPort())
        cutStrips.Update()
        cutPoly = vtk.vtkPolyData()
        cutPoly.SetPoints((cutStrips.GetOutput()).GetPoints())
        cutPoly.SetPolys((cutStrips.GetOutput()).GetLines())

        cutMapper = vtk.vtkPolyDataMapper()
        cutMapper.SetInput(cutPoly)
        #cutMapper.SetInputConnection(cutter.GetOutputPort())

        cutActor = vtk.vtkActor()
        cutActor.GetProperty().SetColor(1, 1, 0)
        cutActor.GetProperty().SetEdgeColor(0, 1, 0)

        cutActor.GetProperty().SetLineWidth(2)
        cutActor.GetProperty().EdgeVisibilityOn()
        cutActor.SetMapper(cutMapper)

        #create renderers and add actors of plane and cube
        self.ren.AddActor(cutActor)

        self.ren.ResetCamera()
        self._initialized = False
Exemplo n.º 26
0
    def InitializeContours(self, contourData, color=yellow):
        # Disable interactor
        self.viewer.GetRenderWindow().GetInteractor().Disable()

        if self.contourActor is not None:
            self.viewer.GetRenderer().RemoveActor(self.contourActor)
            self.contourActor = None

        # Update contours
        self.plane = vtk.vtkPlane()
        RCW = self.viewer.GetResliceCursorWidget()
        ps = RCW.GetResliceCursorRepresentation().GetPlaneSource()
        self.plane.SetOrigin(ps.GetOrigin())
        normal = ps.GetNormal()
        self.plane.SetNormal(normal)

        # We ignore empty ouput (in C++)

        # Transform polydata according to misplacement
        self.transformPolyDataFilter = vtk.vtkTransformPolyDataFilter()
        self.transformPolyDataFilter.SetInputConnection(
            contourData.GetOutputPort())
        self.transformPolyDataFilter.SetTransform(self.transform)

        # Generate line segments
        self.cutEdges = vtk.vtkCutter()
        self.cutEdges.SetInputConnection(
            self.transformPolyDataFilter.GetOutputPort())
        self.cutEdges.SetCutFunction(self.plane)
        self.cutEdges.GenerateCutScalarsOff()
        self.cutEdges.SetValue(0, 0.5)
        self.cutEdges.Update()

        # Put together into polylines
        self.cutStrips = vtk.vtkStripper()
        self.cutStrips.SetInputConnection(self.cutEdges.GetOutputPort())
        self.cutStrips.Update()

        edgeMapper = vtk.vtkPolyDataMapper()
        edgeMapper.SetInputConnection(self.cutStrips.GetOutputPort())

        self.contourActor = vtk.vtkActor()
        self.contourActor.SetMapper(edgeMapper)
        prop = self.contourActor.GetProperty()
        renderLinesAsTubes(prop)
        prop.SetColor(color)

        # Add actor to renderer
        self.viewer.GetRenderer().AddViewProp(self.contourActor)

        # Enable interactor again
        self.viewer.GetRenderWindow().GetInteractor().Enable()
Exemplo n.º 27
0
    def InitializeContours(self, data, color=yellow):
        self.data = data

        # Disable interactor
        self.viewer.GetRenderWindow().GetInteractor().Disable()

        if self.contourActor is not None:
            self.viewer.GetRenderer().RemoveActor(self.contourActor)
            self.contourActor = None

        # Update contours
        self.plane = vtk.vtkPlane()
        RCW = self.viewer.GetResliceCursorWidget()
        ps = RCW.GetResliceCursorRepresentation().GetPlaneSource()
        self.plane.SetOrigin(ps.GetOrigin())
        normal = ps.GetNormal()
        self.plane.SetNormal(normal)

        # Generate line segments
        self.cutEdges = vtk.vtkCutter()
        self.cutEdges.SetInputConnection(self.data.GetOutputPort())
        self.cutEdges.SetCutFunction(self.plane)
        self.cutEdges.GenerateCutScalarsOff()
        self.cutEdges.SetValue(0, 0.5)

        # Put together into polylines
        cutStrips = vtk.vtkStripper()
        cutStrips.SetInputConnection(self.cutEdges.GetOutputPort())
        cutStrips.Update()

        edgeMapper = vtk.vtkPolyDataMapper()
        edgeMapper.SetInputConnection(cutStrips.GetOutputPort())

        # Attach observer to mapper
        edgeMapper.AddObserver(vtk.vtkCommand.UpdateEvent, myCallback)

        self.contourActor = vtk.vtkActor()
        self.contourActor.SetMapper(edgeMapper)
        prop = self.contourActor.GetProperty()
        renderLinesAsTubes(prop)
        prop.SetColor(color)  # If Scalars are extracted - they turn green

        # Move in front of image (is this necessary?)
        transform = vtk.vtkTransform()
        transform.Translate(normal)
        self.contourActor.SetUserTransform(transform)

        # Add actor to renderer
        self.viewer.GetRenderer().AddViewProp(self.contourActor)

        # Enable interactor again
        self.viewer.GetRenderWindow().GetInteractor().Enable()
Exemplo n.º 28
0
    def __init__(self, parent = None):
        super(VTKFrame, self).__init__(parent)

        self.vtkWidget = QVTKRenderWindowInteractor(self)
        vl = QtGui.QVBoxLayout(self)
        vl.addWidget(self.vtkWidget)
        vl.setContentsMargins(0, 0, 0, 0)
 
        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
         
        #Create a sphere
        sphere = vtk.vtkSphereSource()
        sphere.SetRadius(50)
        sphere.SetThetaResolution(100)
        sphere.SetPhiResolution(100)
         
        plane = vtk.vtkPlane()
        plane.SetOrigin(20, 0, 0)
        plane.SetNormal(1, 0, 0)
         
        #create cutter
        cutter = vtk.vtkCutter()
        cutter.SetCutFunction(plane)
        cutter.SetInputConnection(sphere.GetOutputPort())
        cutter.Update()
         
        cutStrips = vtk.vtkStripper()
        cutStrips.SetInputConnection(cutter.GetOutputPort())
        cutStrips.Update()
        cutPoly = vtk.vtkPolyData()
        cutPoly.SetPoints((cutStrips.GetOutput()).GetPoints())
        cutPoly.SetPolys((cutStrips.GetOutput()).GetLines())
         
        cutMapper = vtk.vtkPolyDataMapper()
        cutMapper.SetInput(cutPoly)
        #cutMapper.SetInputConnection(cutter.GetOutputPort())
         
        cutActor = vtk.vtkActor()
        cutActor.GetProperty().SetColor(1, 1, 0)
        cutActor.GetProperty().SetEdgeColor(0, 1, 0)
         
        cutActor.GetProperty().SetLineWidth(2)
        cutActor.GetProperty().EdgeVisibilityOn()
        cutActor.SetMapper(cutMapper)

        #create renderers and add actors of plane and cube
        self.ren.AddActor(cutActor)

        self.ren.ResetCamera()
        self._initialized = False
    def marchingCubes(self, image, ijkToRasMatrix, threshold):


        transformIJKtoRAS = vtk.vtkTransform()
        transformIJKtoRAS.SetMatrix(ijkToRasMatrix)

        marchingCubes = vtk.vtkMarchingCubes()
        marchingCubes.SetInputData(image)
        marchingCubes.SetValue(0, threshold)
        marchingCubes.ComputeScalarsOn()
        marchingCubes.ComputeGradientsOn()
        marchingCubes.ComputeNormalsOn()
        marchingCubes.ReleaseDataFlagOn()
        marchingCubes.Update()


        if transformIJKtoRAS.GetMatrix().Determinant() < 0:
            reverser = vtk.vtkReverseSense()
            reverser.SetInputData(marchingCubes.GetOutput())
            reverser.ReverseNormalsOn()
            reverser.ReleaseDataFlagOn()
            reverser.Update()
            correctedOutput = reverser.GetOutput()
        else:
            correctedOutput = marchingCubes.GetOutput()

        transformer = vtk.vtkTransformPolyDataFilter()
        transformer.SetInputData(correctedOutput)
        transformer.SetTransform(transformIJKtoRAS)
        transformer.ReleaseDataFlagOn()
        transformer.Update()

        normals = vtk.vtkPolyDataNormals()
        normals.ComputePointNormalsOn()
        normals.SetInputData(transformer.GetOutput())
        normals.SetFeatureAngle(60)
        normals.SetSplitting(1)
        normals.ReleaseDataFlagOn()
        normals.Update()

        stripper = vtk.vtkStripper()
        stripper.SetInputData(normals.GetOutput())
        stripper.ReleaseDataFlagOff()
        stripper.Update()
        stripper.GetOutput()

        result = vtk.vtkPolyData()
        result.DeepCopy(stripper.GetOutput())

        return result
    def marchingCubes(self, image, ijkToRasMatrix, threshold):


        transformIJKtoRAS = vtk.vtkTransform()
        transformIJKtoRAS.SetMatrix(ijkToRasMatrix)

        marchingCubes = vtk.vtkMarchingCubes()
        marchingCubes.SetInputData(image)
        marchingCubes.SetValue(0, threshold)
        marchingCubes.ComputeScalarsOn()
        marchingCubes.ComputeGradientsOn()
        marchingCubes.ComputeNormalsOn()
        marchingCubes.ReleaseDataFlagOn()
        marchingCubes.Update()


        if transformIJKtoRAS.GetMatrix().Determinant() < 0:
            reverser = vtk.vtkReverseSense()
            reverser.SetInputData(marchingCubes.GetOutput())
            reverser.ReverseNormalsOn()
            reverser.ReleaseDataFlagOn()
            reverser.Update()
            correctedOutput = reverser.GetOutput()
        else:
            correctedOutput = marchingCubes.GetOutput()

        transformer = vtk.vtkTransformPolyDataFilter()
        transformer.SetInputData(correctedOutput)
        transformer.SetTransform(transformIJKtoRAS)
        transformer.ReleaseDataFlagOn()
        transformer.Update()

        normals = vtk.vtkPolyDataNormals()
        normals.ComputePointNormalsOn()
        normals.SetInputData(transformer.GetOutput())
        normals.SetFeatureAngle(60)
        normals.SetSplitting(1)
        normals.ReleaseDataFlagOn()
        normals.Update()

        stripper = vtk.vtkStripper()
        stripper.SetInputData(normals.GetOutput())
        stripper.ReleaseDataFlagOff()
        stripper.Update()
        stripper.GetOutput()

        result = vtk.vtkPolyData()
        result.DeepCopy(stripper.GetOutput())

        return result
Exemplo n.º 31
0
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
Exemplo n.º 32
0
 def vtkCreateFilterIsoContour(self):
    """ Fonction pour le filtrage du contour"""
    #-----------------------------------------
    # Application d'un filtre de subdivision
    #-----------------------------------------
    self.subdiviseAneurysm = vtk.vtkLoopSubdivisionFilter()
    self.subdiviseAneurysm.SetNumberOfSubdivisions(self.valFilter)
    self.subdiviseAneurysm.SetInputConnection(self.aneurysmNormals.GetOutputPort())
    
    #-----------------------------------------
    # Application d'un filtre decimate et smooth
    #-----------------------------------------
    self.aneurysmDecimator = vtk.vtkDecimatePro()
    self.aneurysmDecimator.SetInputConnection(self.subdiviseAneurysm.GetOutputPort()) 
    self.aneurysmDecimator.SetTargetReduction(self.valDecimate) 
    self.aneurysmDecimator.PreserveTopologyOn() 
    
    self.smoothAneurysm = vtk.vtkSmoothPolyDataFilter()
    self.smoothAneurysm.SetInputConnection(self.aneurysmDecimator.GetOutputPort()) 
    self.smoothAneurysm.SetNumberOfIterations(self.valSmoothIter) 
    self.smoothAneurysm.SetRelaxationFactor(0.07) 
    self.smoothAneurysm.SetFeatureAngle(90) 
    self.smoothAneurysm.FeatureEdgeSmoothingOn()
    #-----------------------------------------
    # Sauvegarde des datas pour le calcul des centerlines
    #-----------------------------------------
    surface_filter = vtk.vtkDataSetSurfaceFilter()
    surface_filter.SetInputConnection(self.smoothAneurysm.GetOutputPort())
    
    meshNormals = vtk.vtkPolyDataNormals()
    meshNormals.SetInputConnection(surface_filter.GetOutputPort())
    meshNormals.Update()
    
    self.surfNode  = vtk_to_np(self.smoothAneurysm.GetOutput().GetPoints().GetData())
    self.surfTable = vtk_to_np(self.smoothAneurysm.GetOutput().GetPolys().GetData())
    
    #-----------------------------------------
    # Realisation du mapper ppour affichage
    #-----------------------------------------
    self.aneurysmStripper = vtk.vtkStripper()
    self.aneurysmStripper.SetInputConnection(self.smoothAneurysm.GetOutputPort())
    
    self.aneurysmMapper = vtk.vtkPolyDataMapper()
    self.aneurysmMapper.SetInputConnection(self.aneurysmStripper.GetOutputPort())
    self.aneurysmMapper.ScalarVisibilityOff()
    self.aneurysmMapper.SetScalarRange(self.min_pixel_value, self.max_pixel_value)
    self.aneurysmMapper.SetScalarModeToUsePointData()
    self.aneurysmMapper.SetLookupTable(self.bwLut)
Exemplo n.º 33
0
    def OnLoadSurfaceDict(self, pubsub_evt):
        surface_dict = pubsub_evt.data
        for key in surface_dict:
            surface = surface_dict[key]
            # Map polygonal data (vtkPolyData) to graphics primitives.
            normals = vtk.vtkPolyDataNormals()
            normals.SetInput(surface.polydata)
            normals.SetFeatureAngle(80)
            normals.AutoOrientNormalsOn()
            normals.GetOutput().ReleaseDataFlagOn()

	    # Improve performance
            stripper = vtk.vtkStripper()
            stripper.SetInput(normals.GetOutput())
            stripper.PassThroughCellIdsOn()
            stripper.PassThroughPointIdsOn()

            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInput(stripper.GetOutput())
            mapper.ScalarVisibilityOff()
	    mapper.ImmediateModeRenderingOn() # improve performance

            # Represent an object (geometry & properties) in the rendered scene
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)

            # Set actor colour and transparency
            actor.GetProperty().SetColor(surface.colour)
            actor.GetProperty().SetOpacity(1-surface.transparency)

            self.actors_dict[surface.index] = actor


            # Send actor by pubsub to viewer's render
            ps.Publisher().sendMessage('Load surface actor into viewer', (actor))

            ps.Publisher().sendMessage('Update status text in GUI',
                                        _("Ready"))

            # The following lines have to be here, otherwise all volumes disappear

            ps.Publisher().sendMessage('Update surface info in GUI',
                                        (surface.index, surface.name,
                                        surface.colour, surface.volume,
                                        surface.transparency))
            if not surface.is_shown:
                self.ShowActor(key, False)
Exemplo n.º 34
0
    def InitializeContour(self, data):
        # Update contours
        self.plane = vtk.vtkPlane()
        RCW = self.viewer.GetResliceCursorWidget()
        ps = RCW.GetResliceCursorRepresentation().GetPlaneSource()
        normal = ps.GetNormal()
        origin = ps.GetOrigin()

        self.plane.SetOrigin(origin)
        self.plane.SetNormal(normal)

        if not oldWay:
            self.plane.SetOrigin(0, 0, 0)
            self.plane.SetNormal(0, 0, 1)
            self.tmp = vtk.vtkTransform()
            self.tmp.SetMatrix(
                main_window.planeWidget[self.iDim].GetResliceAxes())
            self.plane.SetTransform(self.tmp)

        # Generate line segments
        cutEdges = vtk.vtkCutter()
        cutEdges.SetInputConnection(main_window.vesselNormals.GetOutputPort())
        cutEdges.SetCutFunction(self.plane)
        cutEdges.GenerateCutScalarsOff()
        cutEdges.SetValue(0, 0.5)

        # Put together into polylines
        cutStrips = vtk.vtkStripper()
        cutStrips.SetInputConnection(cutEdges.GetOutputPort())
        cutStrips.Update()

        edgeMapper = vtk.vtkPolyDataMapper()
        edgeMapper.SetInputConnection(cutStrips.GetOutputPort())

        self.edgeActor = vtk.vtkActor()
        self.edgeActor.SetMapper(edgeMapper)
        prop = self.edgeActor.GetProperty()
        renderLinesAsTubes(prop)
        prop.SetColor(yellow)  # If Scalars are extracted - they turn green

        # Move in front of image
        transform = vtk.vtkTransform()
        transform.Translate(normal)
        self.edgeActor.SetUserTransform(transform)

        # Add actor to renderer
        self.viewer.GetRenderer().AddViewProp(self.edgeActor)
Exemplo n.º 35
0
    def OnLoadSurfaceDict(self, pubsub_evt):
        surface_dict = pubsub_evt.data
        for key in surface_dict:
            surface = surface_dict[key]

            # Map polygonal data (vtkPolyData) to graphics primitives.
            normals = vtk.vtkPolyDataNormals()
            normals.SetInputData(surface.polydata)
            normals.SetFeatureAngle(80)
            normals.AutoOrientNormalsOn()
            #  normals.GetOutput().ReleaseDataFlagOn()

            # Improve performance
            stripper = vtk.vtkStripper()
            stripper.SetInputConnection(normals.GetOutputPort())
            stripper.PassThroughCellIdsOn()
            stripper.PassThroughPointIdsOn()

            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInputConnection(stripper.GetOutputPort())
            mapper.ScalarVisibilityOff()
            mapper.ImmediateModeRenderingOn() # improve performance

            # Represent an object (geometry & properties) in the rendered scene
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)

            # Set actor colour and transparency
            actor.GetProperty().SetColor(surface.colour)
            actor.GetProperty().SetOpacity(1-surface.transparency)

            self.actors_dict[surface.index] = actor

            # Send actor by pubsub to viewer's render
            Publisher.sendMessage('Load surface actor into viewer', (actor))

            Publisher.sendMessage('Update status text in GUI',
                                        _("Ready"))

            # The following lines have to be here, otherwise all volumes disappear
            Publisher.sendMessage('Update surface info in GUI',
                                        (surface.index, surface.name,
                                         surface.colour, surface.volume,
                                         surface.area, surface.transparency))
            if not surface.is_shown:
                self.ShowActor(key, False)
Exemplo n.º 36
0
def patch(mesh):
    """
        This function...

        :param mesh:
        :return:
        """
    edges = vtk.vtkFeatureEdges()
    edges.SetInputData(mesh)
    edges.FeatureEdgesOff()
    edges.NonManifoldEdgesOn()
    edges.ManifoldEdgesOff()
    edges.BoundaryEdgesOn()
    edges.Update()
    print(
        "{0} cells and {1} points".format(
            edges.GetOutput().GetNumberOfCells(), edges.GetOutput().GetNumberOfPoints()
        )
    )
    if edges.GetOutput().GetNumberOfPoints() == 0:
        print("No defects")
        return mesh

    patchSkel = vtk.vtkStripper()
    patchSkel.SetInputData(edges.GetOutput())
    patchSkel.Update()

    patchPoly = vtk.vtkPolyData()
    patchPoly.Initialize()
    patchPoly.SetPoints(patchSkel.GetOutput().GetPoints())
    patchPoly.SetPolys(patchSkel.GetOutput().GetLines())

    patchTri = vtk.vtkTriangleFilter()
    patchTri.SetInputData(patchPoly)
    patchTri.Update()

    meshAppend = vtk.vtkAppendPolyData()
    meshAppend.AddInputData(patchTri.GetOutput())
    meshAppend.AddInputData(mesh)
    meshAppend.Update()

    poly = vtk.vtkCleanPolyData()
    poly.SetInputData(meshAppend.GetOutput())
    poly.Update()

    return poly.GetOutput()
Exemplo n.º 37
0
def resample_points(poly):

    vs = vtk.vtkStripper()
    vs.SetInputData(poly)
    vs.JoinContiguousSegmentsOn()
    vs.Update()

    cpd2 = vtk.vtkCleanPolyData()
    cpd2.SetInputData(vs.GetOutput())
    cpd2.Update()

    bc = cpd2.GetOutput().GetBounds()
    yl = bc[3] - bc[2]
    zl = bc[5] - bc[4]
    yzl = math.sqrt(yl**2 + zl**2)

    spline = vtk.vtkCardinalSpline()
    spline.SetLeftConstraint(2)
    spline.SetLeftValue(0)
    spline.SetRightConstraint(2)
    spline.SetRightValue(0)

    sp_filter = vtk.vtkSplineFilter()
    sp_filter.SetInputData(cpd2.GetOutput())
    num_points = poly.GetNumberOfPoints()
    sp_filter.SetNumberOfSubdivisions(num_points * 40)
    sp_filter.SetSpline(spline)
    sp_filter.Update()

    def_tol = yzl / 100

    print('bound diag = ', yzl)
    print('max p dist = ', def_tol)

    cpd = vtk.vtkCleanPolyData()
    cpd.SetInputData(sp_filter.GetOutput())
    cpd.ToleranceIsAbsoluteOn()
    cpd.PointMergingOn()
    cpd.ConvertStripsToPolysOn()
    cpd.GetConvertLinesToPoints()
    cpd.ConvertPolysToLinesOn()
    cpd.ToleranceIsAbsoluteOn()
    cpd.SetAbsoluteTolerance(def_tol)
    cpd.Update()

    return cpd.GetOutput()
Exemplo n.º 38
0
    def __init__(self, marker, planeWidget,
                 transform=None, lineWidth=1):
    
        self.lineWidth=lineWidth
        self.marker = marker
        self.markerSource = marker.get_source()
        self.planeWidget = planeWidget
        self.transform = transform

        self.implicitPlane = vtk.vtkPlane()
        self.ringEdges = vtk.vtkCutter()
        self.ringStrips = vtk.vtkStripper()
        self.ringPoly = vtk.vtkPolyData()
        self.ringMapper = vtk.vtkPolyDataMapper()

        self.ringEdges.SetInput(self.markerSource.GetOutput())
        self.implicitPlane.SetNormal(self.planeWidget.GetNormal())
        self.implicitPlane.SetOrigin(self.planeWidget.GetOrigin())

        #print 'implicit plane', self.implicitPlane
        self.ringEdges.SetCutFunction(self.implicitPlane)
        self.ringEdges.GenerateCutScalarsOff()
        self.ringEdges.SetValue(0, 0.0)
        self.ringStrips.SetInput(self.ringEdges.GetOutput())
        self.ringStrips.Update()
        self.ringPoly.SetPoints(self.ringStrips.GetOutput().GetPoints())
        self.ringPoly.SetPolys(self.ringStrips.GetOutput().GetLines())
        self.ringMapper.SetInput(self.ringPoly)
        self.SetMapper(self.ringMapper)

        self.lineProperty = self.GetProperty()
        self.lineProperty.SetRepresentationToWireframe()
        self.lineProperty.SetAmbient(1.0)
        self.lineProperty.SetColor(self.marker.get_color())
        self.lineProperty.SetLineWidth(lineWidth)

        self.SetProperty(self.lineProperty)
        self.VisibilityOff()

        if transform is not None:
            self.filter = vtk.vtkTransformPolyDataFilter()
            self.filter.SetTransform(transform)
        else:
            self.filter = None
        self.update()
Exemplo n.º 39
0
    def extract_isosurface(self, value):
        mc = vtk.vtkMarchingCubes()
        mc.SetInputData(self.volume)
        mc.SetValue(0, value)
        mc.Update()

        strip = vtk.vtkStripper()
        strip.SetInputData(mc.GetOutput())
        strip.Update()

        mapper = vtk.vtkDataSetMapper()
        mapper.SetInputData(strip.GetOutput())
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        #actor.GetProperty().SetRepresentationToWireframe()
        actor.GetProperty().SetColor(self.colors.GetColor3d("DarkSalmon"))
        actor.GetProperty().SetOpacity(0.5)
        self.graphics.add_actor(actor)
Exemplo n.º 40
0
def slicevtkcontour(vtkmesh, h, init=0, end=0):
    # Get limits
    xmin, xmax, ymin, ymax, zmin, zmax = vtkmesh.GetBounds()
    zmin += init
    zmax -= end

    # Plane to cut
    plane = vtk.vtkPlane()
    plane.SetOrigin(0, 0, zmin + h / 2.0)
    plane.SetNormal(0, 0, 1)

    # Cut function
    cutter = vtk.vtkCutter()
    cutter.SetInput(vtkmesh)
    cutter.SetCutFunction(plane)
    cutter.GenerateCutScalarsOn()
    cutter.SetValue(0, 0)

    # Catch the points
    cutStrips = vtk.vtkStripper()
    cutStrips.SetInputConnection(cutter.GetOutputPort())
    cutStrips.Update()

    # Slice and create polygons
    layers = list()
    # zreal = h/2.0
    z = zmin + h / 2.0  # because set an reliable zero can broke the tip
    zs = list()
    polygons = list()  # one for layer
    while z < zmax:
        zs.append(z)
        plane.SetOrigin(0, 0, z)
        cutStrips.Update()
        coords = tuple()
        for j in range(
            cutStrips.GetOutput().GetCell(0).GetPoints().GetNumberOfPoints()
        ):  # retrieve all points from the line
            vec = Vec(cutStrips.GetOutput().GetCell(0).GetPoints().GetPoint(j))
            coords += ((vec.x, vec.y),)
        polygon = Polygon(coords)
        polygons.append(polygon)
        z += h
    return polygons, zs
Exemplo n.º 41
0
 def ComputeAreas(self):
     stripper = vtk.vtkStripper()
     stripper.SetInput(self.Contour)
     stripper.SetMaximumLength(100000)
     stripper.Update()
     contour = stripper.GetOutput()
     if contour.GetNumberOfCells() != 2:
         self.InnerArea = 0.0
         self.OuterArea = 0.0
         return
     areas = [0.0,0.0]
     for n in range(2):
         points = contour.GetCell(n).GetPoints()
         numberOfPoints = points.GetNumberOfPoints()
         for i in range(numberOfPoints):
             point0 = points.GetPoint(i)
             point1 = points.GetPoint((i+1)%numberOfPoints)
             areas[n] += vtk.vtkTriangle.TriangleArea(self.Center,point0,point1)
     self.InnerArea = min(areas)
     self.OuterArea = max(areas)
Exemplo n.º 42
0
 def update(self):
     surface_extractor = vtk.vtkContourFilter()
     surface_extractor.SetInputConnection(self._image.GetOutputPort())
     surface_extractor.SetValue(0, self.__surface_value)
     
     surface_normals = vtk.vtkPolyDataNormals()
     surface_normals.SetInputConnection(surface_extractor.GetOutputPort())
     surface_normals.SetFeatureAngle(60.0)
     
     surface_stripper = vtk.vtkStripper()
     surface_stripper.SetInputConnection(surface_normals.GetOutputPort())
     
     surface_mapper = vtk.vtkPolyDataMapper()
     surface_mapper.SetInputConnection(surface_stripper.GetOutputPort())
     surface_mapper.ScalarVisibilityOff()
     
     surface_actor = vtk.vtkActor()
     surface_actor.SetMapper(surface_mapper)
     
     camera = vtk.vtkCamera()
     camera.SetViewUp(0.0, 0.0, -1.0)
     camera.SetPosition(0.0, 1.0, 0.0)
     camera.SetFocalPoint(0.0, 0.0, 0.0)
     camera.ComputeViewPlaneNormal()
     camera.Dolly(1.5)
     
     renderer = vtk.vtkRenderer()
     renderer.AddActor(surface_actor)
     renderer.SetActiveCamera(camera)
     renderer.ResetCamera()
     renderer.SetBackground(0.0,0.0,0.0)
     renderer.ResetCameraClippingRange()
     
     render_window = vtk.vtkRenderWindow()
     render_window.AddRenderer(renderer)
     
     render_window_interactor = vtk.vtkRenderWindowInteractor()
     render_window_interactor.SetRenderWindow(render_window)
     render_window_interactor.Initialize()
     render_window.Render()
     render_window_interactor.Start()
Exemplo n.º 43
0
    def get_vtk_plane(self, side_len=25):
        # cube = vtk.vtkCubeSource()
        # cube.SetXLength(side_len)
        # cube.SetYLength(side_len)
        # cube.SetZLength(side_len)
        # cube.SetCenter(*self.pos)

        cube = vtk.vtkSphereSource()
        cube.SetThetaResolution(100)
        cube.SetPhiResolution(100)
        cube.SetRadius(side_len)
        cube.SetCenter(*self.xyz)

        cubeMapper = vtk.vtkPolyDataMapper()
        cubeMapper.SetInputConnection(cube.GetOutputPort())

        plane = vtk.vtkPlane()
        plane.SetOrigin(*self.xyz)
        plane.SetNormal(*self.norm)

        #create cutter
        cutter = vtk.vtkCutter()
        cutter.SetCutFunction(plane)
        cutter.SetInputConnection(cube.GetOutputPort())
        cutter.Update()

        cutStrips = vtk.vtkStripper()
        cutStrips.SetInputConnection(cutter.GetOutputPort())
        cutStrips.Update()
        cutPoly = vtk.vtkPolyData()
        cutPoly.SetPoints((cutStrips.GetOutput()).GetPoints())
        cutPoly.SetPolys((cutStrips.GetOutput()).GetLines())

        cutMapper = vtk.vtkPolyDataMapper()
        cutMapper.SetInput(cutPoly)

        cutActor = vtk.vtkActor()
        cutActor.GetProperty().SetColor(1, 1, 1)
        cutActor.SetMapper(cutMapper)

        return cutActor
Exemplo n.º 44
0
    def __create_and_set_mapper(self):
        self.implicitPlane = vtk.vtkPlane()
        self.edges = vtk.vtkCutter()
        self.strips = vtk.vtkStripper()
        self.poly = vtk.vtkPolyData()
        self.mapper = vtk.vtkPolyDataMapper()

        self.edges.SetInputConnection(self.roiPipe.GetOutputPort())
        self.implicitPlane.SetNormal(self.planeWidget.GetNormal())
        self.implicitPlane.SetOrigin(self.planeWidget.GetOrigin())

        self.edges.SetCutFunction(self.implicitPlane)
        self.edges.GenerateCutScalarsOff()
        self.edges.SetValue(0, 0.0)
        self.strips.SetInputConnection(self.edges.GetOutputPort())
        self.strips.Update()
        self.poly.SetPoints(self.strips.GetOutput().GetPoints())
        self.poly.SetPolys(self.strips.GetOutput().GetLines())
        self.mapper.SetInput(self.poly)
        self.mapper.ScalarVisibilityOff()
        self.SetMapper(self.mapper)
Exemplo n.º 45
0
    def _Execute(self, *args):
        input = self.GetPolyDataInput()

        # Gets any edges of the mesh
        edger = vtkFeatureEdges()
        edger.BoundaryEdgesOn()
        edger.FeatureEdgesOff()
        edger.NonManifoldEdgesOff()
        edger.ManifoldEdgesOff()
        edger.SetInputData(input)

        # Converts the edges to a polyline
        stripper = vtkStripper()
        stripper.SetInputConnection(edger.GetOutputPort())
        stripper.Update()

        # Change the polylines into polygons
        boundaryPoly = vtkPolyData()
        boundaryPoly.SetPoints(stripper.GetOutput().GetPoints())
        boundaryPoly.SetPolys(stripper.GetOutput().GetLines())

        # Triangulate
        tri = vtkTriangleFilter()
        tri.SetInputData(boundaryPoly)
        tri.Update()

        # Join to the input
        merger = vtkAppendPolyData()
        merger.AddInputData(input)
        merger.AddInputData(tri.GetOutput())

        # Clean up by merging duplicate points
        cleaner = vtkCleanPolyData()
        cleaner.SetInputConnection(merger.GetOutputPort())
        cleaner.Update()

        # Set output
        output = self.GetPolyDataOutput()
        output.ShallowCopy(cleaner.GetOutput())
        return
Exemplo n.º 46
0
def get_actor(vtk_source, color=[1, 1, 0]):

    normals = vtk.vtkPolyDataNormals()
    normals.SetInputConnection(vtk_source.GetOutputPort())
    normals.SetFeatureAngle(60.0)
    normals.ReleaseDataFlagOn()

    stripper = vtk.vtkStripper()
    stripper.SetInputConnection(normals.GetOutputPort())
    stripper.ReleaseDataFlagOn()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputConnection(stripper.GetOutputPort())
    mapper.SetScalarVisibility(0)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetDiffuseColor(color)
    actor.GetProperty().SetSpecular(0.3)
    actor.GetProperty().SetSpecularPower(20)

    return actor
Exemplo n.º 47
0
 def addSurface(self, name, value, r, g, b):
     if self.surfaces.has_key(name):
         return        
         
     surface = {}
     boneExtractor = vtk.vtkMarchingCubes()
     boneExtractor.SetInput(self.vtkImageData)
     boneExtractor.SetValue(0, value)
     surface["boneExtractor"] = boneExtractor
     
     boneNormals = vtk.vtkPolyDataNormals()
     boneNormals.SetInputConnection(boneExtractor.GetOutputPort())
     boneNormals.SetFeatureAngle(60.0)
     surface["boneNormals"] = boneNormals
     
     boneStripper = vtk.vtkStripper()
     boneStripper.SetInputConnection(boneNormals.GetOutputPort())
     surface["boneStripper"] = boneStripper
     
     mapper = vtk.vtkPolyDataMapper()
     mapper.SetInputConnection(boneStripper.GetOutputPort())
     mapper.ScalarVisibilityOff()
     mapper.Update()
     surface["mapper"] = mapper
     
     boneProperty = vtk.vtkProperty()
     boneProperty.SetColor(r, g, b)
     
     volume = vtk.vtkActor()
     volume.SetMapper(mapper)
     volume.SetProperty(boneProperty)
     surface["volume"] = volume
     
     self.addVolume(volume)
     self.surfaces[name] = surface
     self.updateMapperClipPlanes(mapper)
     
     self.window.Render()
Exemplo n.º 48
0
    def _capCutPolyData(self, clipPolyData):
        # set a vtkCutter up exactly like the vtkClipPolyData
        cutter = vtk.vtkCutter()
        cutter.SetCutFunction(clipPolyData.GetClipFunction())
        cutter.SetInput(clipPolyData.GetInput())
        cutter.SetValue(0, clipPolyData.GetValue())
        cutter.SetGenerateCutScalars(clipPolyData.GetGenerateClipScalars())

        cutStripper = vtk.vtkStripper()
        cutStripper.SetInput(cutter.GetOutput())
        cutStripper.Update()

        cutPolyData = vtk.vtkPolyData()
        cutPolyData.SetPoints(cutStripper.GetOutput().GetPoints())
        cutPolyData.SetPolys(cutStripper.GetOutput().GetLines())

        cpd = vtk.vtkCleanPolyData()
        cpd.SetInput(cutPolyData)

        tf = vtk.vtkTriangleFilter()
        tf.SetInput(cpd.GetOutput())
        tf.Update()
        return tf.GetOutput()
Exemplo n.º 49
0
    def Execute(self):

        normal = [math.cos(self.RotationAngle) * math.sin(self.TiltingAngle), 
                  math.sin(self.RotationAngle) * math.sin(self.TiltingAngle), 
                  math.cos(self.TiltingAngle)]
        
        plane = vtk.vtkPlane()
        plane.SetOrigin(self.Center)
        plane.SetNormal(normal)
        cutter = vtk.vtkCutter()
        cutter.SetInput(self.Contour)
        cutter.SetCutFunction(plane)
        cutter.SetValue(0,0.0)
        cutter.Update()
        cleaner = vtk.vtkCleanPolyData()
        cleaner.SetInput(cutter.GetOutput())
        cleaner.Update()
        stripper = vtk.vtkStripper()
        stripper.SetInput(cleaner.GetOutput())
        stripper.Update()
        cutLine = stripper.GetOutput()
        self.Locations = [0.0, 0.0]
        self.Thickness = 2.0 * self.ComputeMeanRadius(cutLine)
        self.Thickness3D = self.Thickness
Exemplo n.º 50
0
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

# read the volume
reader = vtk.vtkJPEGReader()
reader.SetFileName(VTK_DATA_ROOT + "/Data/beach.jpg")

#---------------------------------------------------------
# Do the surface rendering
sphereSource = vtk.vtkSphereSource()
sphereSource.SetRadius(100)

textureSphere = vtk.vtkTextureMapToSphere()
textureSphere.SetInputConnection(sphereSource.GetOutputPort())

sphereStripper = vtk.vtkStripper()
sphereStripper.SetInputConnection(textureSphere.GetOutputPort())
sphereStripper.SetMaximumLength(5)

sphereMapper = vtk.vtkPolyDataMapper()
sphereMapper.SetInputConnection(sphereStripper.GetOutputPort())
sphereMapper.ScalarVisibilityOff()

sphereTexture = vtk.vtkTexture()
sphereTexture.SetInputConnection(reader.GetOutputPort())

sphereProperty = vtk.vtkProperty()
sphereProperty.BackfaceCullingOn()

sphere = vtk.vtkActor()
sphere.SetMapper(sphereMapper)
Exemplo n.º 51
0
clipActor = vtk.vtkActor()
clipActor.SetMapper(clipMapper)
clipActor.GetProperty().SetColor(GetRGBColor('peacock'))
clipActor.SetBackfaceProperty(backProp)

# now extract feature edges
boundaryEdges = vtk.vtkFeatureEdges()
boundaryEdges.SetInputConnection(clipper.GetOutputPort())
boundaryEdges.BoundaryEdgesOn()
boundaryEdges.FeatureEdgesOff()
boundaryEdges.NonManifoldEdgesOff()

boundaryClean = vtk.vtkCleanPolyData()
boundaryClean.SetInputConnection(boundaryEdges.GetOutputPort())

boundaryStrips = vtk.vtkStripper()
boundaryStrips.SetInputConnection(boundaryClean.GetOutputPort())
boundaryStrips.Update()

boundaryPoly = vtk.vtkPolyData()
boundaryPoly.SetPoints(boundaryStrips.GetOutput().GetPoints())
boundaryPoly.SetPolys(boundaryStrips.GetOutput().GetLines())

boundaryTriangles = vtk.vtkTriangleFilter()
boundaryTriangles.SetInputData(boundaryPoly)

boundaryMapper = vtk.vtkPolyDataMapper()
boundaryMapper.SetInputConnection(boundaryTriangles.GetOutputPort())

boundaryActor = vtk.vtkActor()
boundaryActor.SetMapper(boundaryMapper)
Exemplo n.º 52
0
cropOutlineMapper.SetInputConnection(cropOutlineSource.GetOutputPort())

cropOutline = vtk.vtkActor()
cropOutline.SetMapper(cropOutlineMapper)

#---------------------------------------------------------
# Do the surface rendering
skinExtractor = vtk.vtkMarchingCubes()
skinExtractor.SetInputConnection(reader.GetOutputPort())
skinExtractor.SetValue(0,500)

skinNormals = vtk.vtkPolyDataNormals()
skinNormals.SetInputConnection(skinExtractor.GetOutputPort())
skinNormals.SetFeatureAngle(60.0)

skinStripper = vtk.vtkStripper()
skinStripper.SetMaximumLength(10)
skinStripper.SetInputConnection(skinNormals.GetOutputPort())

skinLocator = vtk.vtkCellLocator()
skinLocator.SetDataSet(skinStripper.GetOutput())
skinLocator.LazyEvaluationOn()

skinMapper = vtk.vtkPolyDataMapper()
skinMapper.SetInputConnection(skinStripper.GetOutputPort())
skinMapper.ScalarVisibilityOff()

skinProperty = vtk.vtkProperty()
skinProperty.SetColor(1.0,1.0,0.9)

skin = vtk.vtkActor()
Exemplo n.º 53
0
    def _plotInternal(self):
        """Overrides baseclass implementation."""
        numLevels = len(self._contourLevels)

        cot = vtk.vtkContourFilter()
        if self._useCellScalars:
            cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort())
        else:
            cot.SetInputData(self._vtkDataSet)
        cot.SetNumberOfContours(numLevels)

        if self._contourLevels[0] == 1.e20:
            self._contourLevels[0] = -1.e20
        for i in range(numLevels):
            cot.SetValue(i, self._contourLevels[i])
        cot.SetValue(numLevels, self._contourLevels[-1])
        # TODO remove update
        cot.Update()

        mappers = []

        lut = vtk.vtkLookupTable()
        lut.SetNumberOfTableValues(len(self._contourColors))
        cmap = self._context().canvas.getcolormapname()
        cmap = vcs.elements["colormap"][cmap]
        for i, col in enumerate(self._contourColors):
            r, g, b = cmap.index[col]
            lut.SetTableValue(i, r / 100., g / 100., b / 100.)

        # Setup isoline labels
        if self._gm.label:
            # Setup label mapping array:
            tpropMap = vtk.vtkDoubleArray()
            tpropMap.SetNumberOfComponents(1)
            tpropMap.SetNumberOfTuples(numLevels)
            for i, val in enumerate(self._contourLevels):
                tpropMap.SetTuple(i, [val])

            # Prep text properties:
            tprops = vtk.vtkTextPropertyCollection()
            if self._gm.text or self._gm.textcolors:
                # Text objects:
                if self._gm.text:
                    texts = self._gm.text
                    while len(texts) < numLevels:
                        texts.append(texts[-1])
                else:
                    texts = [None] * len(self._gm.textcolors)

                # Custom colors:
                if self._gm.textcolors:
                    colorOverrides = self._gm.textcolors
                    while len(colorOverrides) < numLevels:
                        colorOverrides.append(colorOverrides[-1])
                else:
                    colorOverrides = [None] * len(self._gm.text)

                for tc, colorOverride in zip(texts, colorOverrides):
                    if vcs.queries.istextcombined(tc):
                        tt, to = tuple(tc.name.split(":::"))
                    elif tc is None:
                        tt = "default"
                        to = "default"
                    elif vcs.queries.istexttable(tc):
                        tt = tc.name
                        to = "default"
                    elif vcs.queries.istextorientation(tc):
                        to = tc.name
                        tt = "default"
                    if colorOverride is not None:
                        tt = vcs.createtexttable(None, tt)
                        tt.color = colorOverride
                        tt = tt.name
                    tprop = vtk.vtkTextProperty()
                    vcs2vtk.prepTextProperty(tprop,
                                             self._context().renWin.GetSize(),
                                             to, tt)
                    tprops.AddItem(tprop)
                    if colorOverride is not None:
                        del(vcs.elements["texttable"][tt])
            else:  # No text properties specified. Use the default:
                tprop = vtk.vtkTextProperty()
                vcs2vtk.prepTextProperty(tprop,
                                         self._context().renWin.GetSize())
                tprops.AddItem(tprop)
            self._resultDict["vtk_backend_contours_labels_text_properties"] = \
                tprops

            mapper = vtk.vtkLabeledContourMapper()
            mapper.SetTextProperties(tprops)
            mapper.SetTextPropertyMapping(tpropMap)
            mapper.SetLabelVisibility(1)
            mapper.SetSkipDistance(self._gm.labelskipdistance)

            pdMapper = mapper.GetPolyDataMapper()

            self._resultDict["vtk_backend_labeled_luts"] = [
                [lut,
                 [self._contourLevels[0], self._contourLevels[-1], False]]]
        else:  # No isoline labels:
            mapper = vtk.vtkPolyDataMapper()
            pdMapper = mapper
            self._resultDict["vtk_backend_luts"] = \
                [[lut, [self._contourLevels[0],
                        self._contourLevels[-1], False]]]
        pdMapper.SetLookupTable(lut)
        pdMapper.SetScalarRange(self._contourLevels[0],
                                self._contourLevels[-1])
        pdMapper.SetScalarModeToUsePointData()

        stripper = vtk.vtkStripper()
        stripper.SetInputConnection(cot.GetOutputPort())
        mapper.SetInputConnection(stripper.GetOutputPort())
        # TODO remove update, make pipeline
        stripper.Update()
        mappers.append(mapper)
        self._resultDict["vtk_backend_contours"] = [cot]

        if self._maskedDataMapper is not None:
            mappers.insert(0, self._maskedDataMapper)

        x1, x2, y1, y2 = vcs.utils.getworldcoordinates(self._gm,
                                                       self._data1.getAxis(-1),
                                                       self._data1.getAxis(-2))

        # And now we need actors to actually render this thing
        actors = []
        for mapper in mappers:
            act = vtk.vtkActor()
            act.SetMapper(mapper)

            if self._vtkGeoTransform is None:
                # If using geofilter on wireframed does not get wrppaed not
                # sure why so sticking to many mappers
                act = vcs2vtk.doWrap(act, [x1, x2, y1, y2],
                                     self._dataWrapModulo)

            # TODO See comment in boxfill.
            if mapper is self._maskedDataMapper:
                actors.append([act, self._maskedDataMapper, [x1, x2, y1, y2]])
            else:
                actors.append([act, [x1, x2, y1, y2]])

            # create a new renderer for this mapper
            # (we need one for each mapper because of cmaera flips)
            self._context().fitToViewport(
                act, [self._template.data.x1, self._template.data.x2,
                      self._template.data.y1, self._template.data.y2],
                wc=[x1, x2, y1, y2], geo=self._vtkGeoTransform,
                priority=self._template.data.priority,
                create_renderer=True)

        self._resultDict["vtk_backend_actors"] = actors

        t = self._originalData1.getTime()
        if self._originalData1.ndim > 2:
            z = self._originalData1.getAxis(-3)
        else:
            z = None

        self._resultDict.update(self._context().renderTemplate(self._template,
                                                               self._data1,
                                                               self._gm, t, z))

        if self._context().canvas._continents is None:
            self._useContinents = False
        if self._useContinents:
            projection = vcs.elements["projection"][self._gm.projection]
            self._context().plotContinents(x1, x2, y1, y2, projection,
                                           self._dataWrapModulo,
                                           self._template)
Exemplo n.º 54
0
    def AddNewActor(self, pubsub_evt):
        """
        Create surface actor, save into project and send it to viewer.
        """
        slice_, mask, surface_parameters = pubsub_evt.data
        matrix = slice_.matrix
        filename_img = slice_.matrix_filename
        spacing = slice_.spacing
        
        algorithm = surface_parameters['method']['algorithm']
        options = surface_parameters['method']['options']
        
        surface_name = surface_parameters['options']['name']
        quality = surface_parameters['options']['quality']
        fill_holes = surface_parameters['options']['fill']
        keep_largest = surface_parameters['options']['keep_largest']

        mode = 'CONTOUR' # 'GRAYSCALE'
        min_value, max_value = mask.threshold_range
        colour = mask.colour

        try:
            overwrite = surface_parameters['options']['overwrite']
        except KeyError:
            overwrite = False
        mask.matrix.flush()

        if quality in const.SURFACE_QUALITY.keys():
            imagedata_resolution = const.SURFACE_QUALITY[quality][0]
            smooth_iterations = const.SURFACE_QUALITY[quality][1]
            smooth_relaxation_factor = const.SURFACE_QUALITY[quality][2]
            decimate_reduction = const.SURFACE_QUALITY[quality][3]

        #if imagedata_resolution:
            #imagedata = iu.ResampleImage3D(imagedata, imagedata_resolution)

        pipeline_size = 4
        if decimate_reduction:
            pipeline_size += 1
        if (smooth_iterations and smooth_relaxation_factor):
            pipeline_size += 1
        if fill_holes:
            pipeline_size += 1
        if keep_largest:
            pipeline_size += 1
    
        ## Update progress value in GUI
        UpdateProgress = vu.ShowProgress(pipeline_size)
        UpdateProgress(0, _("Creating 3D surface..."))

        language = ses.Session().language

        if (prj.Project().original_orientation == const.CORONAL):
            flip_image = False
        else:
            flip_image = True

        n_processors = multiprocessing.cpu_count()
            
        pipe_in, pipe_out = multiprocessing.Pipe()
        o_piece = 1
        piece_size = 2000

        n_pieces = int(round(matrix.shape[0] / piece_size + 0.5, 0))

        q_in = multiprocessing.Queue()
        q_out = multiprocessing.Queue()

        p = []
        for i in xrange(n_processors):
            sp = surface_process.SurfaceProcess(pipe_in, filename_img,
                                                matrix.shape, matrix.dtype,
                                                mask.temp_file,
                                                mask.matrix.shape,
                                                mask.matrix.dtype,
                                                spacing, 
                                                mode, min_value, max_value,
                                                decimate_reduction,
                                                smooth_relaxation_factor,
                                                smooth_iterations, language,
                                                flip_image, q_in, q_out,
                                                algorithm != 'Default',
                                                algorithm,
                                                imagedata_resolution)
            p.append(sp)
            sp.start()

        for i in xrange(n_pieces):
            init = i * piece_size
            end = init + piece_size + o_piece
            roi = slice(init, end)
            q_in.put(roi)
            print "new_piece", roi

        for i in p:
            q_in.put(None)

        none_count = 1
        while 1:
            msg = pipe_out.recv()
            if(msg is None):
                none_count += 1
            else:
                UpdateProgress(msg[0]/(n_pieces * pipeline_size), msg[1])

            if none_count > n_pieces:
                break

        polydata_append = vtk.vtkAppendPolyData()
        polydata_append.ReleaseDataFlagOn()
        t = n_pieces
        while t:
            filename_polydata = q_out.get()

            reader = vtk.vtkXMLPolyDataReader()
            reader.SetFileName(filename_polydata)
            reader.ReleaseDataFlagOn()
            reader.Update()
            reader.GetOutput().ReleaseDataFlagOn()

            polydata = reader.GetOutput()
            polydata.SetSource(None)

            polydata_append.AddInput(polydata)
            del reader
            del polydata
            t -= 1

        polydata_append.Update()
        polydata_append.GetOutput().ReleaseDataFlagOn()
        polydata = polydata_append.GetOutput()
        #polydata.Register(None)
        polydata.SetSource(None)
        del polydata_append

        if algorithm == 'ca_smoothing':
            normals = vtk.vtkPolyDataNormals()
            normals_ref = weakref.ref(normals)
            normals_ref().AddObserver("ProgressEvent", lambda obj,evt:
                                      UpdateProgress(normals_ref(), _("Creating 3D surface...")))
            normals.SetInput(polydata)
            normals.ReleaseDataFlagOn()
            #normals.SetFeatureAngle(80)
            #normals.AutoOrientNormalsOn()
            normals.ComputeCellNormalsOn()
            normals.GetOutput().ReleaseDataFlagOn()
            normals.Update()
            del polydata
            polydata = normals.GetOutput()
            polydata.SetSource(None)
            del normals

            clean = vtk.vtkCleanPolyData()
            clean.ReleaseDataFlagOn()
            clean.GetOutput().ReleaseDataFlagOn()
            clean_ref = weakref.ref(clean)
            clean_ref().AddObserver("ProgressEvent", lambda obj,evt:
                            UpdateProgress(clean_ref(), _("Creating 3D surface...")))
            clean.SetInput(polydata)
            clean.PointMergingOn()
            clean.Update()

            del polydata
            polydata = clean.GetOutput()
            polydata.SetSource(None)
            del clean

            try:
                polydata.BuildLinks()
            except TypeError:
                polydata.BuildLinks(0)
            polydata = ca_smoothing.ca_smoothing(polydata, options['angle'],
                                                 options['max distance'],
                                                 options['min weight'],
                                                 options['steps'])
            polydata.SetSource(None)
            polydata.DebugOn()

        else:
            #smoother = vtk.vtkWindowedSincPolyDataFilter()
            smoother = vtk.vtkSmoothPolyDataFilter()
            smoother_ref = weakref.ref(smoother)
            smoother_ref().AddObserver("ProgressEvent", lambda obj,evt:
                            UpdateProgress(smoother_ref(), _("Creating 3D surface...")))
            smoother.SetInput(polydata)
            smoother.SetNumberOfIterations(smooth_iterations)
            smoother.SetRelaxationFactor(smooth_relaxation_factor)
            smoother.SetFeatureAngle(80)
            #smoother.SetEdgeAngle(90.0)
            #smoother.SetPassBand(0.1)
            smoother.BoundarySmoothingOn()
            smoother.FeatureEdgeSmoothingOn()
            #smoother.NormalizeCoordinatesOn()
            #smoother.NonManifoldSmoothingOn()
            smoother.ReleaseDataFlagOn()
            smoother.GetOutput().ReleaseDataFlagOn()
            smoother.Update()
            del polydata
            polydata = smoother.GetOutput()
            #polydata.Register(None)
            polydata.SetSource(None)
            del smoother


        if decimate_reduction:
            print "Decimating", decimate_reduction
            decimation = vtk.vtkQuadricDecimation()
            decimation.ReleaseDataFlagOn()
            decimation.SetInput(polydata)
            decimation.SetTargetReduction(decimate_reduction)
            decimation_ref = weakref.ref(decimation)
            decimation_ref().AddObserver("ProgressEvent", lambda obj,evt:
                            UpdateProgress(decimation_ref(), _("Creating 3D surface...")))
            #decimation.PreserveTopologyOn()
            #decimation.SplittingOff()
            #decimation.BoundaryVertexDeletionOff()
            decimation.GetOutput().ReleaseDataFlagOn()
            decimation.Update()
            del polydata
            polydata = decimation.GetOutput()
            #polydata.Register(None)
            polydata.SetSource(None)
            del decimation

        to_measure = polydata
        #to_measure.Register(None)
        to_measure.SetSource(None)

        if keep_largest:
            conn = vtk.vtkPolyDataConnectivityFilter()
            conn.SetInput(polydata)
            conn.SetExtractionModeToLargestRegion()
            conn_ref = weakref.ref(conn)
            conn_ref().AddObserver("ProgressEvent", lambda obj,evt:
                    UpdateProgress(conn_ref(), _("Creating 3D surface...")))
            conn.Update()
            conn.GetOutput().ReleaseDataFlagOn()
            del polydata
            polydata = conn.GetOutput()
            #polydata.Register(None)
            polydata.SetSource(None)
            del conn

        #Filter used to detect and fill holes. Only fill boundary edges holes.
        #TODO: Hey! This piece of code is the same from
        #polydata_utils.FillSurfaceHole, we need to review this.
        if fill_holes:
            filled_polydata = vtk.vtkFillHolesFilter()
            filled_polydata.ReleaseDataFlagOn()
            filled_polydata.SetInput(polydata)
            filled_polydata.SetHoleSize(300)
            filled_polydata_ref = weakref.ref(filled_polydata)
            filled_polydata_ref().AddObserver("ProgressEvent", lambda obj,evt:
                    UpdateProgress(filled_polydata_ref(), _("Creating 3D surface...")))
            filled_polydata.Update()
            filled_polydata.GetOutput().ReleaseDataFlagOn()
            del polydata
            polydata = filled_polydata.GetOutput()
            #polydata.Register(None)
            polydata.SetSource(None)
            polydata.DebugOn()
            del filled_polydata
        
        normals = vtk.vtkPolyDataNormals()
        normals.ReleaseDataFlagOn()
        normals_ref = weakref.ref(normals)
        normals_ref().AddObserver("ProgressEvent", lambda obj,evt:
                        UpdateProgress(normals_ref(), _("Creating 3D surface...")))
        normals.SetInput(polydata)
        normals.SetFeatureAngle(80)
        normals.AutoOrientNormalsOn()
        normals.GetOutput().ReleaseDataFlagOn()
        normals.Update()
        del polydata
        polydata = normals.GetOutput()
        #polydata.Register(None)
        polydata.SetSource(None)
        del normals

        # Improve performance
        stripper = vtk.vtkStripper()
        stripper.ReleaseDataFlagOn()
        stripper_ref = weakref.ref(stripper)
        stripper_ref().AddObserver("ProgressEvent", lambda obj,evt:
                        UpdateProgress(stripper_ref(), _("Creating 3D surface...")))
        stripper.SetInput(polydata)
        stripper.PassThroughCellIdsOn()
        stripper.PassThroughPointIdsOn()
        stripper.GetOutput().ReleaseDataFlagOn()
        stripper.Update()
        del polydata
        polydata = stripper.GetOutput()
        #polydata.Register(None)
        polydata.SetSource(None)
        del stripper

        # Map polygonal data (vtkPolyData) to graphics primitives.
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(polydata)
        mapper.ScalarVisibilityOff()
        mapper.ReleaseDataFlagOn()
        mapper.ImmediateModeRenderingOn() # improve performance

        # Represent an object (geometry & properties) in the rendered scene
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
        del mapper
        #Create Surface instance
        if overwrite:
            surface = Surface(index = self.last_surface_index)
        else:
            surface = Surface(name=surface_name)
        surface.colour = colour
        surface.polydata = polydata
        del polydata

        # Set actor colour and transparency
        actor.GetProperty().SetColor(colour)
        actor.GetProperty().SetOpacity(1-surface.transparency)

        prop = actor.GetProperty()

        interpolation = int(ses.Session().surface_interpolation)

        prop.SetInterpolation(interpolation)

        proj = prj.Project()
        if overwrite:
            proj.ChangeSurface(surface)
        else:
            index = proj.AddSurface(surface)
            surface.index = index
            self.last_surface_index = index

        session = ses.Session()
        session.ChangeProject()

        # The following lines have to be here, otherwise all volumes disappear
        measured_polydata = vtk.vtkMassProperties()
        measured_polydata.ReleaseDataFlagOn()
        measured_polydata.SetInput(to_measure)
        volume =  float(measured_polydata.GetVolume())
        surface.volume = volume
        self.last_surface_index = surface.index
        del measured_polydata
        del to_measure

        Publisher.sendMessage('Load surface actor into viewer', actor)

        # Send actor by pubsub to viewer's render
        if overwrite and self.actors_dict.keys():
            old_actor = self.actors_dict[self.last_surface_index]
            Publisher.sendMessage('Remove surface actor from viewer', old_actor)

        # Save actor for future management tasks
        self.actors_dict[surface.index] = actor

        Publisher.sendMessage('Update surface info in GUI',
                                    (surface.index, surface.name,
                                    surface.colour, surface.volume,
                                    surface.transparency))
        
        #When you finalize the progress. The bar is cleaned.
        UpdateProgress = vu.ShowProgress(1)
        UpdateProgress(0, _("Ready"))
        Publisher.sendMessage('Update status text in GUI', _("Ready"))
        
        Publisher.sendMessage('End busy cursor')
        del actor
Exemplo n.º 55
0
# to make arrow glyphs need an arrow source
arrow = vtk.vtkArrowSource()

# the arrows are 3D glyphs so set that up now
glyph = vtk.vtkGlyph3D()
glyph.ScalingOn()
glyph.SetScaleModeToScaleByScalar()
glyph.SetColorModeToColorByScalar()
glyph.SetVectorModeToUseVector()
glyph.SetScaleFactor(0.1/maxNorm)
glyph.SetInput(norm.GetOutput())
glyph.SetSource(arrow.GetOutput())
glyph.ClampingOff()

# set up a stripper to speed up rendering
stripper = vtk.vtkStripper()
stripper.SetInput(glyph.GetOutput())

# make a lookup table for the colour map and invert it (colours look
# better when it's inverted)
lut = vtk.vtkLookupTable()
refLut = vtk.vtkLookupTable()
lut.Build()
refLut.Build()
for j in range(256):
    lut.SetTableValue(j, refLut.GetTableValue(255-j))

# set up the mapper
mapper = vtk.vtkPolyDataMapper()
mapper.SetInput(stripper.GetOutput())
mapper.SetScalarRange(0,maxNorm)
Exemplo n.º 56
0
# Here we are cutting the cow. Cutting creates lines where the cut
# function intersects the model. (Clipping removes a portion of the
# model but the dimension of the data does not change.)
#
# The reason we are cutting is to generate a closed polygon at the
# boundary of the clipping process. The cutter generates line
# segments, the stripper then puts them together into polylines. We
# then pull a trick and define polygons using the closed line
# segements that the stripper created.
cutEdges = vtk.vtkCutter()
cutEdges.SetInputConnection(cowNormals.GetOutputPort())
cutEdges.SetCutFunction(plane)
cutEdges.GenerateCutScalarsOn()
cutEdges.SetValue(0, 0.5)
cutStrips = vtk.vtkStripper()
cutStrips.SetInputConnection(cutEdges.GetOutputPort())
cutStrips.Update()
cutPoly = vtk.vtkPolyData()
cutPoly.SetPoints(cutStrips.GetOutput().GetPoints())
cutPoly.SetPolys(cutStrips.GetOutput().GetLines())

# Triangle filter is robust enough to ignore the duplicate point at
# the beginning and end of the polygons and triangulate them.
cutTriangles = vtk.vtkTriangleFilter()
cutTriangles.SetInputData(cutPoly)
cutMapper = vtk.vtkPolyDataMapper()
cutMapper.SetInputData(cutPoly)
cutMapper.SetInputConnection(cutTriangles.GetOutputPort())
cutActor = vtk.vtkActor()
cutActor.SetMapper(cutMapper)
Exemplo n.º 57
0
def renderIBC(filePrefix, imgLow, imgHigh):
    global picker, redCone, greenCone
    #
    # This example reads a volume dataset, extracts an isosurface that
    # represents the skin and displays it.
    #
    
    
    # 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
    # usese 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.)
    #vtkVolume16Reader v13R
    #  v13R SetDataDimensions 1388 1040
    #  v13R SetDataByteOrderToBigEndian 
    #  v13R SetFilePrefix  "IBC146h.R_s"
    #  v13R SetImageRange 0  44
    #  v13R SetDataSpacing  1 1 2
      
    # Image reader
    v13G = vtk.vtkTIFFReader()
    v13G.SetDataExtent(1, 1380, 1, 1030, imgLow, imgHigh)
    v13G.SetDataByteOrderToLittleEndian() 
    v13G.SetFilePrefix(filePrefix)
    v13G.SetDataSpacing(0.1, 0.1, 0.6)
    
    # Gaussian Smoothing
    gaus_v13G = vtk.vtkImageGaussianSmooth()
    gaus_v13G.SetDimensionality(3)
    gaus_v13G.SetStandardDeviation(1)
    gaus_v13G.SetRadiusFactors(1, 1, 1)
    gaus_v13G.SetInput(v13G.GetOutput())
    
    
    # Set up the volume rendering
    volumeMapper = vtk.vtkVolumeTextureMapper3D()
    volumeMapper.SetInput(v13G.GetOutput())
    
    volume = vtk.vtkVolume()
    volume.SetMapper(volumeMapper)
    
    
    # Surface rendering
    bactExtractor = vtk.vtkMarchingCubes()
    bactExtractor.SetInputConnection(gaus_v13G.GetOutputPort())
    bactExtractor.SetValue(0,20000)
    
#    bactNormals = vtk.vtkPolyDataNormals()
#    bactNormals.SetInputConnection(bactExtractor.GetOutputPort())
#    bactNormals.SetFeatureAngle(90.0)
#    
#    bactStripper = vtk.vtkStripper()
#    bactStripper.SetInputConnection(bactNormals.GetOutputPort())
#    
    bactLocator = vtk.vtkCellLocator()
    bactLocator.SetDataSet(bactExtractor.GetOutput())
    bactLocator.LazyEvaluationOn()
#    
#    bactMapper = vtk.vtkPolyDataMapper()
#    bactMapper.SetInputConnection(bactStripper.GetOutputPort())
#    bactMapper.ScalarVisibilityOff()
    
    
#    skinE_v13G = vtk.vtkContourFilter()
##    skinE_v13G = vtk.vtkMarchingCubes()
#    skinE_v13G.UseScalarTreeOn()
#    skinE_v13G.SetInput(gaus_v13G.GetOutput())
#    skinE_v13G.SetValue(0, 10000)
#    
    smooth_v13G = vtk.vtkSmoothPolyDataFilter()
    smooth_v13G.SetInput(bactExtractor.GetOutput())
    smooth_v13G.SetNumberOfIterations(50)
    
    deci_v13G = vtk.vtkDecimatePro()
    deci_v13G.SetInput(smooth_v13G.GetOutput())
    deci_v13G.SetTargetReduction(0.5)
    deci_v13G.PreserveTopologyOn()
    
    smoother_v13G = vtk.vtkSmoothPolyDataFilter()
    smoother_v13G.SetInput(deci_v13G.GetOutput())
    smoother_v13G.SetNumberOfIterations(50)
    
    skinNormals_v13G = vtk.vtkPolyDataNormals()
    skinNormals_v13G.SetInput(deci_v13G.GetOutput())
    skinNormals_v13G.SetFeatureAngle(60.0)
    
    
    skinStripper_v13G = vtk.vtkStripper()
    skinStripper_v13G.SetInput(skinNormals_v13G.GetOutput())
    
    
    skinMapper_v13G = vtk.vtkPolyDataMapper()
    skinMapper_v13G.SetInput(skinStripper_v13G.GetOutput())
    skinMapper_v13G.ScalarVisibilityOff()
    
    skin_v13G = vtk.vtkActor()
    skin_v13G.SetMapper(skinMapper_v13G)
    skin_v13G.GetProperty().SetDiffuseColor(0.2, 1, 0.2)
    skin_v13G.GetProperty().SetSpecular(.1)
    skin_v13G.GetProperty().SetSpecularPower(5)
    skin_v13G.GetProperty().SetOpacity(0.9)
    
    
    # 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.
    aCamera = vtk.vtkCamera()
    aCamera.SetViewUp(0, 0, -1)
    aCamera.SetPosition(0, 1.1, 2)
    aCamera.SetFocalPoint(0, -0.25, 0)
    aCamera.ComputeViewPlaneNormal()
    
    
    
    # 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.
    #aRenderer AddActor skin_v13R
    ren.AddActor(skin_v13G)
    ren.SetActiveCamera(aCamera)
    ren.ResetCamera() 
    aCamera.Dolly(1.0)
   
    
    # 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.
    ren.ResetCameraClippingRange()
    
    
    # render
    renWin.Render()
    
    # CONE PICKER RENDER
    
    #---------------------------------------------------------
    # the cone points along the -x axis
    coneSource = vtk.vtkConeSource()
    coneSource.CappingOn()
    coneSource.SetHeight(2)
    coneSource.SetRadius(1)
    coneSource.SetResolution(11)
    coneSource.SetCenter(1,0,0)
    coneSource.SetDirection(-1,0,0)
    
    coneMapper = vtk.vtkDataSetMapper()
    coneMapper.SetInputConnection(coneSource.GetOutputPort())
    
    redCone = vtk.vtkActor()
    redCone.PickableOff()
    redCone.SetMapper(coneMapper)
    redCone.GetProperty().SetColor(1,0,0)
    
    greenCone = vtk.vtkActor()
    greenCone.PickableOff()
    greenCone.SetMapper(coneMapper)
    greenCone.GetProperty().SetColor(0,1,0)
    
    # Add the two cones (or just one, if you want)
    ren.AddViewProp(redCone)
    ren.AddViewProp(greenCone)
    
    #---------------------------------------------------------
    # the picker
    picker = vtk.vtkVolumePicker()
    picker.SetTolerance(1e-6)
    picker.SetVolumeOpacityIsovalue(0.1)
    # locator is optional, but improves performance for large polydata
    picker.AddLocator(bactLocator)
    
    #---------------------------------------------------------
    # custom interaction
    iren.AddObserver("MouseMoveEvent", MoveCursor)

    
    # END CONE PICKER RENDER
    
    # initialize and start the interactor
    iren.Initialize()
    iren.Start()
volume = vtk.vtkVolume()
volume.SetMapper(volumeMapper)
volume.SetProperty(volumeProperty)

# ---------------------------------------------------------
# Do the surface rendering
boneExtractor = vtk.vtkMarchingCubes()
boneExtractor.SetInputConnection(reader.GetOutputPort())
boneExtractor.SetValue(0, 1150)

boneNormals = vtk.vtkPolyDataNormals()
boneNormals.SetInputConnection(boneExtractor.GetOutputPort())
boneNormals.SetFeatureAngle(60.0)

boneStripper = vtk.vtkStripper()
boneStripper.SetInputConnection(boneNormals.GetOutputPort())

boneLocator = vtk.vtkCellLocator()
boneLocator.SetDataSet(boneExtractor.GetOutput())
boneLocator.LazyEvaluationOn()

boneMapper = vtk.vtkPolyDataMapper()
boneMapper.SetInputConnection(boneStripper.GetOutputPort())
boneMapper.ScalarVisibilityOff()

boneProperty = vtk.vtkProperty()
boneProperty.SetColor(1.0, 1.0, 0.9)

bone = vtk.vtkActor()
bone.SetMapper(boneMapper)
Exemplo n.º 59
0
v16.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter")
v16.SetImageRange(1, 93)
v16.SetDataSpacing(3.2, 3.2, 1.5)

# An isosurface, or contour value of 500 is known to correspond to the
# skin of the patient. Once generated, a vtkPolyDataNormals filter is
# is used to create normals for smooth surface shading during rendering.
# The triangle stripper is used to create triangle strips from the
# isosurface these render much faster on may systems.
skinExtractor = vtk.vtkContourFilter()
skinExtractor.SetInputConnection(v16.GetOutputPort())
skinExtractor.SetValue(0, 500)
skinNormals = vtk.vtkPolyDataNormals()
skinNormals.SetInputConnection(skinExtractor.GetOutputPort())
skinNormals.SetFeatureAngle(60.0)
skinStripper = vtk.vtkStripper()
skinStripper.SetInputConnection(skinNormals.GetOutputPort())
skinMapper = vtk.vtkPolyDataMapper()
skinMapper.SetInputConnection(skinStripper.GetOutputPort())
skinMapper.ScalarVisibilityOff()
skin = vtk.vtkActor()
skin.SetMapper(skinMapper)
skin.GetProperty().SetDiffuseColor(1, .49, .25)
skin.GetProperty().SetSpecular(.3)
skin.GetProperty().SetSpecularPower(20)

# An isosurface, or contour value of 1150 is known to correspond to the
# skin of the patient. Once generated, a vtkPolyDataNormals filter is
# is used to create normals for smooth surface shading during rendering.
# The triangle stripper is used to create triangle strips from the
# isosurface these render much faster on may systems.