def __init__(self, pos, plane, label, plane_dx, translation):

        self.start_position = (pos[0], pos[1], pos[2] + 1)

        self.point = vtk.vtkSphereSource()
        self.point.SetRadius(2)
        self.point.SetCenter(pos[0] + translation[0], pos[1] + translation[1], \
            pos[2] - plane_dx + 1)
        self.point.SetThetaResolution(100)
        self.point.SetPhiResolution(100)

        self.sphereMapper = vtk.vtkPolyDataMapper()
        self.sphereMapper.SetInputConnection(self.point.GetOutputPort())
        self.sphereMapper.Update()

        cutter = vtk.vtkCutter()
        cutter.SetCutFunction(plane)
        cutter.SetInputData(self.sphereMapper.GetInput())
        cutter.Update()

        full_point = vtk.vtkContourTriangulator()
        full_point.SetInputConnection(cutter.GetOutputPort())
        full_point.Update()

        cmapper = vtk.vtkPolyDataMapper()
        cmapper.SetResolveCoincidentTopologyToPolygonOffset()
        cmapper.SetInputConnection(full_point.GetOutputPort())
        cmapper.ScalarVisibilityOff()

        self.actor = vtk.vtkActor()
        self.actor.GetProperty().SetColor(*Settings.labels[label]['rgb'])
        self.actor.GetProperty().SetAmbient(1)
        self.actor.GetProperty().SetDiffuse(0)
        self.actor.GetProperty().SetSpecular(0)
        self.actor.SetMapper(cmapper)
Exemplo n.º 2
0
 def sliceClosestModel(self, point):
     originalModel = None
     # set up plane
     normal = np.array([
         float(self.sliceLogic.GetSliceNode().GetName() == name)
         for name in ['Yellow', 'Green', 'Red']
     ])
     plane = vtk.vtkPlane()
     plane.SetOrigin(point)  # point in plane
     plane.SetNormal(normal)
     # set up cutter
     cutter = vtk.vtkCutter()
     cutter.SetCutFunction(plane)
     cutter.SetGenerateCutScalars(0)
     cutter.Update()
     # init point locator and output
     pointsLocator = vtk.vtkPointLocator()
     globalMinDistance = 1000
     outPolyData = vtk.vtkPolyData()
     # iterate over models in scene
     nModels = slicer.mrmlScene.GetNumberOfNodesByClass('vtkMRMLModelNode')
     for i in range(nModels):
         model = slicer.mrmlScene.GetNthNodeByClass(i, 'vtkMRMLModelNode')
         polyData = model.GetPolyData()
         if model.GetDisplayNode() and model.GetDisplayNode().GetVisibility(
         ) and polyData.GetNumberOfCells() > 1 and model.GetName(
         ) != 'auxSphereModel':  # model visible and cells available
             cutter.SetInputData(polyData)
             cutter.Update()
             cutterOutput = cutter.GetOutput()
             if cutterOutput.GetNumberOfCells(
             ):  # model intersects with plane
                 # get distance from input point to closest point in model
                 pointsLocator.SetDataSet(cutterOutput)
                 pointsLocator.BuildLocator()
                 closestPoint = cutterOutput.GetPoint(
                     pointsLocator.FindClosestPoint(point))
                 localMinDistance = vtk.vtkMath().Distance2BetweenPoints(
                     closestPoint, point)
                 if localMinDistance < globalMinDistance:  # new min
                     outPolyData.DeepCopy(cutterOutput)
                     globalMinDistance = localMinDistance
                     originalModel = model
     # return in case no model found
     if not originalModel:
         return False, False
     # generate output
     triangulator = vtk.vtkContourTriangulator()
     triangulator.SetInputData(outPolyData)
     triangulator.Update()
     slicedModel = slicer.mrmlScene.AddNewNodeByClass('vtkMRMLModelNode')
     slicedModel.SetAndObservePolyData(triangulator.GetOutput())
     slicedModel.CreateDefaultDisplayNodes()
     slicedModel.GetDisplayNode().SetVisibility(0)
     return slicedModel, originalModel
Exemplo n.º 3
0
    def threshold(self, value=None, flip=False):
        """
        Create a polygonal Mesh from a Picture by filling regions with pixels
        luminosity above a specified value.

        Parameters
        ----------
        value : float, optional
            The default is None, e.i. 1/3 of the scalar range.

        flip: bool, optional
            Flip polygon orientations

        Returns
        -------
        Mesh
            A polygonal mesh.
        """
        mgf = vtk.vtkImageMagnitude()
        mgf.SetInputData(self._data)
        mgf.Update()
        msq = vtk.vtkMarchingSquares()
        msq.SetInputData(mgf.GetOutput())
        if value is None:
            r0, r1 = self._data.GetScalarRange()
            value = r0 + (r1 - r0) / 3
        msq.SetValue(0, value)
        msq.Update()
        if flip:
            rs = vtk.vtkReverseSense()
            rs.SetInputData(msq.GetOutput())
            rs.ReverseCellsOn()
            rs.ReverseNormalsOff()
            rs.Update()
            output = rs.GetOutput()
        else:
            output = msq.GetOutput()
        ctr = vtk.vtkContourTriangulator()
        ctr.SetInputData(output)
        ctr.Update()
        return vedo.Mesh(ctr.GetOutput(), c='k').bc('t').lighting('off')
Exemplo n.º 4
0
def main(argv):
  if os.name == 'nt':
    VTK_DATA_ROOT = "c:/VTK82/build_Release/ExternalData/Testing/"
  else:
    VTK_DATA_ROOT = "/home/jmh/"

  if 1:
    v16 = vtk.vtkMetaImageReader()
    v16.SetFileName("/home/jmh/github/fis/data/Abdomen/CT-Abdomen.mhd")
    v16.Update()
  elif 0:
    fname = os.path.join(VTK_DATA_ROOT, "Data/headsq/quarter")
    v16 = vtk.vtkVolume16Reader()
    v16.SetDataDimensions(64, 64)
    v16.SetDataByteOrderToLittleEndian()
    v16.SetImageRange(1, 93)
    v16.SetDataSpacing(3.2, 3.2, 1.5)
    v16.SetFilePrefix(fname)
    v16.ReleaseDataFlagOn()
    v16.SetDataMask(0x7fff)
    v16.Update()
  else:
    v16 = vtk.vtkMetaImageReader()
    v16.SetFileName("c:/github/fis/data/Abdomen/CT-Abdomen.mhd")
    v16.Update()

  rng = v16.GetOutput().GetScalarRange()

  shifter = vtk.vtkImageShiftScale()
  shifter.SetShift(-1.0*rng[0])
  shifter.SetScale(255.0/(rng[1]-rng[0]))
  shifter.SetOutputScalarTypeToUnsignedChar()
  shifter.SetInputConnection(v16.GetOutputPort())
  shifter.ReleaseDataFlagOff()
  shifter.Update()

 
  ImageViewer = vtk.vtkImageViewer2()
  ImageViewer.SetInputData(shifter.GetOutput())
  ImageViewer.SetColorLevel(127)
  ImageViewer.SetColorWindow(255)

  iren = vtk.vtkRenderWindowInteractor()
  ImageViewer.SetupInteractor(iren)

  ImageViewer.Render()
  ImageViewer.GetRenderer().ResetCamera()

  ImageViewer.Render()    
 
  dims = v16.GetOutput().GetDimensions()

  global minArea
  spacing = v16.GetOutput().GetSpacing()
  minArea = ( spacing[0] * spacing[1] ) / 0.1

  # Slider screen representation
  SliderRepres = vtk.vtkSliderRepresentation2D()
  _min = ImageViewer.GetSliceMin()
  _max = ImageViewer.GetSliceMax()
  SliderRepres.SetMinimumValue(_min)
  SliderRepres.SetMaximumValue(_max)
  SliderRepres.SetValue(int((_min + _max) / 2))
  SliderRepres.SetTitleText("Slice")
  SliderRepres.GetPoint1Coordinate().SetCoordinateSystemToNormalizedDisplay()
  SliderRepres.GetPoint1Coordinate().SetValue(0.3, 0.05)
  SliderRepres.GetPoint2Coordinate().SetCoordinateSystemToNormalizedDisplay()
  SliderRepres.GetPoint2Coordinate().SetValue(0.7, 0.05)
  SliderRepres.SetSliderLength(0.02)
  SliderRepres.SetSliderWidth(0.03)
  SliderRepres.SetEndCapLength(0.01)
  SliderRepres.SetEndCapWidth(0.03)
  SliderRepres.SetTubeWidth(0.005)
  SliderRepres.SetLabelFormat("%3.0lf")
  SliderRepres.SetTitleHeight(0.02)
  SliderRepres.SetLabelHeight(0.02)

  # Slider widget
  SliderWidget = vtk.vtkSliderWidget()
  SliderWidget.SetInteractor(iren)
  SliderWidget.SetRepresentation(SliderRepres)
  SliderWidget.KeyPressActivationOff()
  SliderWidget.SetAnimationModeToAnimate()
  SliderWidget.SetEnabled(True)
 
  SliderCb = vtkSliderCallback()
  SliderCb.SetImageViewer(ImageViewer)
  SliderWidget.AddObserver(vtk.vtkCommand.InteractionEvent, SliderCb.Execute)  

  ImageViewer.SetSlice(int(SliderRepres.GetValue()))

  # Contour representation - responsible for placement of points, calculation of lines and contour manipulation
  global rep
  rep = vtk.vtkOrientedGlyphContourRepresentation()
  # vtkContourRepresentation has GetActiveNodeWorldPostion/Orientation
  rep.GetProperty().SetOpacity(0) #1
  prop = rep.GetLinesProperty()
  from vtkUtils import renderLinesAsTubes
  from vtk.util.colors import red, green, pink, yellow
  renderLinesAsTubes(prop)
  prop.SetColor(yellow)
  propActive = rep.GetActiveProperty()
  #propActive.SetOpacity(0) # 2
  
  renderLinesAsTubes(propActive)

  propActive.SetColor(green)
  shapeActive = rep.GetActiveCursorShape()

  warp = vtk.vtkWarpVector()
  warp.SetInputData(shapeActive)
  warp.SetInputArrayToProcess(0, 0, 0,
                              vtk.vtkDataObject.FIELD_ASSOCIATION_POINTS,
                              vtk.vtkDataSetAttributes.NORMALS)
  scale = 0.4
  warp.SetScaleFactor(scale)
  warp.Update()
  rep.SetActiveCursorShape(warp.GetOutput())

  # Use vtkContourTriangulator to fill contours

  # Point placer
  imageActorPointPlacer = vtk.vtkImageActorPointPlacer()
  imageActorPointPlacer.SetImageActor(ImageViewer.GetImageActor())
  rep.SetPointPlacer(imageActorPointPlacer)

  global ContourWidget
  # Contour widget - has a  vtkWidgetEventTranslator which translate events to vtkContourWidget events
  ContourWidget = vtk.vtkContourWidget()
  ContourWidget.SetRepresentation(rep)
  ContourWidget.SetInteractor(iren)
  ContourWidget.SetEnabled(True)
  ContourWidget.ProcessEventsOn()
  ContourWidget.ContinuousDrawOn()

  # Can be Initialize() using polydata

  # Override methods that returns display position to get an overlay
  # (display postions) instead of computing it from world position and
  # the method BuildLines to interpolate using display positions
  # instead of world positions

  # Thinning of contour control points
  # AddFinalPointAction
  ContourWidget.AddObserver(vtk.vtkCommand.EndInteractionEvent, callback)



  if 0:
    # TODO: Make interior transparent
    contour = ContourWidget.GetContourRepresentation().GetContourRepresentationAsPolyData()
    tc = vtk.vtkContourTriangulator()
    tc.SetInputData(contour)
    tc.Update()

    # Extrusion towards camera
    extruder = vtk.vtkLinearExtrusionFilter()
    extruder.CappingOn()
    extruder.SetScalaFactor(1.0)
    extruder.SetInputData(tc.GetOutput())
    extruder.SetVector(0,0,1.0)
    extruder.SetExtrusionTypeToNormalExtrusion()
    
    polyMapper = vtk.vtkPolyMapper()
    polyMapper.SetInputConnection(extruder.GetOutputPort())
    polyMapper.ScalarVisibilityOn()
    polyMapper.Update()
    polyActor = vtk.vtkActor()
    polyActor.SetMapper(polyMapper)
    prop = polyActor.GetProperty()
    prop.SetColor(0,1,0)
    #prop.SetRepresentationToWireframe()
    renderer.AddActor(polyActor)
    renderer.GetRenderWindow().Render()
  


  iren.Start()
Exemplo n.º 5
0
loops.InsertNextCell(2, conn)
conn = [9, 10]
loops.InsertNextCell(2, conn)
conn = [10, 11]
loops.InsertNextCell(2, conn)
conn = [11, 8]
loops.InsertNextCell(2, conn)

pd = vtk.vtkPolyData()
pd.SetPoints(pts)
pd.SetLines(loops)

# Now triangulate
normal = [0, 0, 1]
outputCA = vtk.vtkCellArray()
ct = vtk.vtkContourTriangulator()
ct.TriangulateContours(pd, 0, 12, outputCA, normal)

outPD = vtk.vtkPolyData()
outPD.SetPoints(pts)
outPD.SetPolys(outputCA)

mapper = vtk.vtkPolyDataMapper()
mapper.SetInputData(outPD)

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

# Graphics objects
ren1 = vtk.vtkRenderer()
ren1.SetBackground(0, 0, 0)
Exemplo n.º 6
0
def main():
    inputFileName, isoValue = get_program_parameters()

    reader = vtk.vtkPNGReader()
    if not reader.CanReadFile(inputFileName):
        print("Error: Could not read %s ." % (inputFileName))
    reader.SetFileName(inputFileName)
    reader.Update()

    iso = vtk.vtkMarchingSquares()
    iso.SetInputConnection(reader.GetOutputPort())
    iso.SetValue(0, isoValue)

    # Test smoothing here
    if 1:
        # Remove duplicate points and join up lines to form polylines
        pCleaner = vtk.vtkCleanPolyData()
        pCleaner.SetInputConnection(iso.GetOutputPort())
        pStripper = vtk.vtkStripper()
        pStripper.SetInputConnection(pCleaner.GetOutputPort())

        # Downsample and smooth the polyline
        pSpline = vtk.vtkSplineFilter()
        mSplineResamplingLength = 50.0
        mReferenceLength = 40.0
        pSpline.SetLength(mSplineResamplingLength / mReferenceLength)
        pSpline.SetSubdivideToLength()
        pSpline.SetInputConnection(pStripper.GetOutputPort())

        pTriangle = vtk.vtkTriangleFilter()
        pTriangle.SetInputConnection(pSpline.GetOutputPort())
        pTriangle.Update()
        pCleaned = pTriangle.GetOutput()
        newMapper = vtk.vtkDataSetMapper()
        newMapper.SetInputConnection(pTriangle.GetOutputPort())
        newActor = vtk.vtkActor()
        newActor.SetMapper(newMapper)

    isoMapper = vtk.vtkDataSetMapper()
    isoMapper.SetInputConnection(iso.GetOutputPort())
    isoMapper.ScalarVisibilityOff()

    isoActor = vtk.vtkActor()
    isoActor.SetMapper(isoMapper)
    isoActor.GetProperty().SetColor(0.8900, 0.8100, 0.3400)

    poly = vtk.vtkContourTriangulator()
    poly.SetInputConnection(iso.GetOutputPort())

    polyMapper = vtk.vtkDataSetMapper()
    polyMapper.SetInputConnection(poly.GetOutputPort())
    polyMapper.ScalarVisibilityOff()

    polyActor = vtk.vtkActor()
    polyActor.SetMapper(polyMapper)
    polyActor.GetProperty().SetColor(1.0000, 0.3882, 0.2784)

    # Standard rendering classes
    renderer = vtk.vtkRenderer()
    renWin = vtk.vtkRenderWindow()
    renWin.SetMultiSamples(0)
    renWin.AddRenderer(renderer)
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renWin)

    renderer.AddActor(polyActor)  # Important
    renderer.AddActor(isoActor)
    renderer.AddActor(newActor)

    # Standard testing code.
    renderer.SetBackground(0.5, 0.5, 0.5)
    renWin.SetSize(800, 800)

    camera = renderer.GetActiveCamera()
    renderer.ResetCamera()
    camera.Azimuth(180)

    renWin.Render()
    iren.Initialize()
    iren.Start()
Exemplo n.º 7
0
    def processSegment(self,
                       inputSegmentation,
                       segmentID,
                       center,
                       normal,
                       closestIsland=True,
                       createModel=False,
                       controlPointLabel=None):
        if not inputSegmentation:
            raise ValueError("Input segmentation is invalid")
        if segmentID == "":
            raise ValueError("Input segment ID is invalid")

        import time
        startTime = time.time()
        logging.info('Processing started')

        # ---------------------- Generate cut polydata ---------
        closedSurfacePolyData = vtk.vtkPolyData()
        inputSegmentation.CreateClosedSurfaceRepresentation()
        inputSegmentation.GetClosedSurfaceRepresentation(
            segmentID, closedSurfacePolyData)
        # Cut through thresholded result.
        plane = vtk.vtkPlane()
        plane.SetOrigin(center)
        plane.SetNormal(normal)
        cutter = vtk.vtkCutter()
        cutter.SetCutFunction(plane)
        cutter.SetInputData(closedSurfacePolyData)
        cutter.Update()
        # Triangulate the contour points
        contourTriangulator = vtk.vtkContourTriangulator()
        # Keep the closest closed surface
        if closestIsland:
            connectivityFilter = vtk.vtkConnectivityFilter()
            connectivityFilter.SetInputData(cutter.GetOutput())
            connectivityFilter.SetClosestPoint(center)
            connectivityFilter.SetExtractionModeToClosestPointRegion()
            connectivityFilter.Update()
            contourTriangulator.SetInputData(
                connectivityFilter.GetPolyDataOutput())
        else:
            contourTriangulator.SetInputData(cutter.GetOutput())
        contourTriangulator.Update()
        # Get result
        polydata = contourTriangulator.GetOutput()
        # Get surface area
        massProperties = vtk.vtkMassProperties()
        massProperties.SetInputData(polydata)
        massProperties.Update()
        surfaceArea = massProperties.GetSurfaceArea()

        # Create a model of the polydata. Hidden by default, with no lighting.
        cutModel = None
        if createModel:
            cutModel = slicer.modules.models.logic().AddModel(polydata)
            cutModel.SetDisplayVisibility(False)
            cutModel.GetDisplayNode().SetLighting(False)
            # Set model's name : control point label + segment name.
            segment = inputSegmentation.GetSegmentation().GetSegment(segmentID)
            if controlPointLabel and segment:
                modelName = controlPointLabel + "_" + segment.GetName()
                cutModel.SetName(modelName)
            # The model's color follows the segment's color.
            if segment:
                cutModel.GetDisplayNode().SetColor(segment.GetColor())

        stopTime = time.time()
        logging.info(
            f'Processing completed in {stopTime-startTime:.2f} seconds')
        return (surfaceArea, cutModel)