示例#1
0
文件: cad_mesh.py 项目: lcpt/xc
def VtkDibujaIdsCells(uGrid, setToDraw, entTypeName, renderer):
  ids= vtk.vtkIdFilter()
  ids.SetInput(uGrid)
  ids.CellIdsOff()
  ids.PointIdsOff()

  VtkCargaIdsCells(uGrid,setToDraw,entTypeName)
    
  # Dibuja las etiquetas de las líneas.
  cc= vtk.vtkCellCenters()
  cc.SetInputConnection(ids.GetOutputPort()) #  Centroides de las celdas. 
        
  visCells= vtk.vtkSelectVisiblePoints()
  visCells.SetInputConnection(cc.GetOutputPort())
  visCells.SetRenderer(renderer)
  visCells.SelectionWindowOff()

  #Create the mapper to display the cell ids.  Specify the format to
  # use for the labels.  Also create the associated actor.
  cellMapper= vtk.vtkLabeledDataMapper()
  cellMapper.SetInputConnection(visCells.GetOutputPort())
  cellMapper.GetLabelTextProperty().SetColor(0,0,0.9)

  cellLabels= vtk.vtkActor2D()
  cellLabels.SetMapper(cellMapper)
       
  renderer.AddActor2D(cellLabels)
示例#2
0
文件: app.py 项目: jcdinis/POMES
    def Release(self, obj, event):
        if self.pega_pontos:
            iren =self.Interactor
            ren = self.renderer
            x, y = iren.GetEventPosition()
            self.x1 = x
            self.y1 = y

            xmin = min(self.x0, self.x1)
            xmax = max(self.x0, self.x1)

            ymin = min(self.y0, self.y1)
            ymax = max(self.y0, self.y1)
            # Generate ids for labeling

            ids = vtk.vtkIdFilter()
            ids.SetInputData(self.polydata)
            ids.PointIdsOn()
            ids.CellIdsOn()
            ids.FieldDataOn()
            ids.Update()

            s = vtk.vtkSelectVisiblePoints()
            s.SetRenderer(self.renderer)
            s.SetInputData(ids.GetOutput())
            s.SelectionWindowOn()
            s.SetSelection(xmin, xmax, ymin, ymax)
            s.SelectInvisibleOff()
            s.Update()

            id_points = numpy_support.vtk_to_numpy(s.GetOutput().GetPointData().GetAbstractArray("vtkIdFilter_Ids"))
            print id_points
            self.id_points.update(id_points.tolist())
        else:
            obj.EndRotate()
示例#3
0
def VtkDibujaIdsElementos(nmbUGrid, setName, renderer):
  # ****** Creamos las etiquetas para las celdas *******
  ids= vtk.vtkIdFilter()
  ids.SetInput(nmbUGrid)
  ids.CellIdsOff()
  ids.PointIdsOff()
 
  VtkCargaIdsElem(nmbUGrid,setName)()
    
  # Dibuja las etiquetas de las líneas.
  cc= vtk.vtkCellCenters()
  cc.SetInput(ids) #  Centroides de las celdas. 
        
  visElems= vtk.vtkSelectVisiblePoints()
  visElems.SetInput(cc)
  visElems.SetRenderer(renderer)
  visElems.SelectionWindowOff()

  ''' Create the mapper to display the element ids.  Specify the format to
     use for the labels.  Also create the associated actor. '''
  elemMapper= vtk.vtkLabeledShStrMapper()
  elemMapper.SetInput(visElems)
  elemMapper.LabelTextProperty.SetColor(0,0,0.9)

  elemLabels= vtk.vtkActor2D()
  elemLabels.SetMapper(elemMapper)
  renderer.AddActor2D(elemLabels)
示例#4
0
文件: cad_mesh.py 项目: ming91915/xc
def VtkDibujaIdsCells(uGrid, setToDraw, entTypeName, renderer):
    ids = vtk.vtkIdFilter()
    ids.SetInput(uGrid)
    ids.CellIdsOff()
    ids.PointIdsOff()

    VtkCargaIdsCells(uGrid, setToDraw, entTypeName)

    # Dibuja las etiquetas de las líneas.
    cc = vtk.vtkCellCenters()
    cc.SetInputConnection(ids.GetOutputPort())  #  Centroides de las celdas.

    visCells = vtk.vtkSelectVisiblePoints()
    visCells.SetInputConnection(cc.GetOutputPort())
    visCells.SetRenderer(renderer)
    visCells.SelectionWindowOff()

    #Create the mapper to display the cell ids.  Specify the format to
    # use for the labels.  Also create the associated actor.
    cellMapper = vtk.vtkLabeledDataMapper()
    cellMapper.SetInputConnection(visCells.GetOutputPort())
    cellMapper.GetLabelTextProperty().SetColor(0, 0, 0.9)

    cellLabels = vtk.vtkActor2D()
    cellLabels.SetMapper(cellMapper)

    renderer.AddActor2D(cellLabels)
示例#5
0
文件: cad_mesh.py 项目: lcpt/xc
def VtkDibujaIdsKPts(uGrid, setToDraw, renderer):
  '''Draw the point labels.'''
  numKPtsDI= setToDraw.getPoints.size
  if(numKPtsDI>0):
    ids= vtk.vtkIdFilter()
    ids.SetInput(uGrid)
    ids.CellIdsOff()
    ids.PointIdsOff()

    VtkCargaIdsKPts(uGrid,setToDraw)
            
    visPts= vtk.vtkSelectVisiblePoints()
    visPts.SetInputConnection(ids.GetOutputPort())
    visPts.SetRenderer(renderer)
    visPts.SelectionWindowOff()

    #Create the mapper to display the point ids.  Specify the format to
    #  use for the labels.  Also create the associated actor.
    ldm= vtk.vtkLabeledDataMapper()
    ldm.SetInputConnection(visPts.GetOutputPort())
    ldm.GetLabelTextProperty().SetColor(0.1,0.1,0.1)

    pointLabels= vtk.vtkActor2D()
    pointLabels.SetMapper(ldm)

    renderer.AddActor2D(pointLabels)
  else:
    print "El conjunto: '",setToDraw,"' no tiene KPts."
示例#6
0
def VtkDibujaIdsElementos(nmbUGrid, setName, renderer):
    # ****** Creamos las etiquetas para las celdas *******
    ids = vtk.vtkIdFilter()
    ids.SetInput(nmbUGrid)
    ids.CellIdsOff()
    ids.PointIdsOff()

    VtkCargaIdsElem(nmbUGrid, setName)()

    # Dibuja las etiquetas de las líneas.
    cc = vtk.vtkCellCenters()
    cc.SetInput(ids)  #  Centroides de las celdas.

    visElems = vtk.vtkSelectVisiblePoints()
    visElems.SetInput(cc)
    visElems.SetRenderer(renderer)
    visElems.SelectionWindowOff()
    ''' Create the mapper to display the element ids.  Specify the format to
     use for the labels.  Also create the associated actor. '''
    elemMapper = vtk.vtkLabeledShStrMapper()
    elemMapper.SetInput(visElems)
    elemMapper.LabelTextProperty.SetColor(0, 0, 0.9)

    elemLabels = vtk.vtkActor2D()
    elemLabels.SetMapper(elemMapper)
    renderer.AddActor2D(elemLabels)
示例#7
0
文件: cad_mesh.py 项目: ming91915/xc
def VtkDibujaIdsKPts(uGrid, setToDraw, renderer):
    numKPtsDI = setToDraw.getPoints.size
    if (numKPtsDI > 0):
        ids = vtk.vtkIdFilter()
        ids.SetInput(uGrid)
        ids.CellIdsOff()
        ids.PointIdsOff()

        VtkCargaIdsKPts(uGrid, setToDraw)

        visPts = vtk.vtkSelectVisiblePoints()
        visPts.SetInputConnection(ids.GetOutputPort())
        visPts.SetRenderer(renderer)
        visPts.SelectionWindowOff()

        #Create the mapper to display the point ids.  Specify the format to
        #  use for the labels.  Also create the associated actor.
        ldm = vtk.vtkLabeledDataMapper()
        ldm.SetInputConnection(visPts.GetOutputPort())
        ldm.GetLabelTextProperty().SetColor(0.1, 0.1, 0.1)

        pointLabels = vtk.vtkActor2D()
        pointLabels.SetMapper(ldm)

        renderer.AddActor2D(pointLabels)
    else:
        print "El conjunto: '", setToDraw, "' no tiene KPts."
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkSelectVisiblePoints(), 'Processing.',
         ('vtkDataSet',), ('vtkPolyData',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkSelectVisiblePoints(),
                                       'Processing.', ('vtkDataSet', ),
                                       ('vtkPolyData', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
示例#10
0
def VtkDibujaIdsElementos(ids):
    '''Dibuja las etiquetas de los elementos. Not implemented yet.'''
    cc = vtk.vtkCellCenters()
    vtk.SetInput(ids)  #  Centroides de las celdas.

    visCells = vtk.vtkSelectVisiblePoints()
    visCells.SetInput(cc)
    visCells.SetRenderer("renderer")
    visCells.SelectionWindowOff()

    #Create the mapper to display the cell ids.  Specify the format to
    # use for the labels.  Also create the associated actor.

    cellMapper = vtk.vtkLabeledShStrMapper
    cellMapper.SetInput(visCells)
    cellMapper.LabelTextProperty().SetColor(0, 0, 0.9)

    cellLabels = vtk.vtkActor2D()
    cellLabels.SetMapper(cellMapper)
示例#11
0
def VtkDibujaIdsNodes(recordGrid, renderer):
  '''Display node labels'''
  ids= vtk.vtkIdFilter()
  ids.SetInput(recordGrid.uGrid)
  ids.CellIdsOff()
  ids.PointIdsOff()

  VtkCargaIdsNodes(recordGrid)
    
  visPts= vtk.vtkSelectVisiblePoints()
  visPts.SetInput("ids")
  visPts.SetRenderer(renderer)
  visPts.SelectionWindowOff()

  #Create the mapper to display the point ids.  Specify the format to
  #   use for the labels.  Also create the associated actor.
  ldm= vtk.vtkLabeledShStrMapper()
  ldm.SetInput("visPts")
  ldm.LabelTextProperty().SetColor(0.1,0.1,0.1)
  nodeLabels= vtk.vtkActor2D().SetMapper(ldm)
  renderer.AddActor2D(nodeLabels)
示例#12
0
def VtkDibujaIdsNodes(recordGrid, renderer):
    '''Display node labels (not implemented yet)'''
    ids = vtk.vtkIdFilter()
    ids.SetInput(recordGrid.uGrid)
    ids.CellIdsOff()
    ids.PointIdsOff()

    VtkCargaIdsNodes(recordGrid)

    visPts = vtk.vtkSelectVisiblePoints()
    visPts.SetInput("ids")
    visPts.SetRenderer(renderer)
    visPts.SelectionWindowOff()

    #Create the mapper to display the point ids.  Specify the format to
    #   use for the labels.  Also create the associated actor.
    ldm = vtk.vtkLabeledShStrMapper()
    ldm.SetInput("visPts")
    ldm.LabelTextProperty().SetColor(0.1, 0.1, 0.1)
    nodeLabels = vtk.vtkActor2D().SetMapper(ldm)
    renderer.AddActor2D(nodeLabels)
示例#13
0
文件: app.py 项目: tfmoraes/POMES
    def Release(self, obj, event):
        if self.pega_pontos:
            iren = self.Interactor
            ren = self.renderer
            x, y = iren.GetEventPosition()
            self.x1 = x
            self.y1 = y

            xmin = min(self.x0, self.x1)
            xmax = max(self.x0, self.x1)

            ymin = min(self.y0, self.y1)
            ymax = max(self.y0, self.y1)
            # Generate ids for labeling

            ids = vtk.vtkIdFilter()
            ids.SetInputData(self.polydata)
            ids.PointIdsOn()
            ids.CellIdsOn()
            ids.FieldDataOn()
            ids.Update()

            s = vtk.vtkSelectVisiblePoints()
            s.SetRenderer(self.renderer)
            s.SetInputData(ids.GetOutput())
            s.SelectionWindowOn()
            s.SetSelection(xmin, xmax, ymin, ymax)
            s.SelectInvisibleOff()
            s.Update()

            id_points = numpy_support.vtk_to_numpy(
                s.GetOutput().GetPointData().GetAbstractArray(
                    "vtkIdFilter_Ids"))
            print id_points
            self.id_points.update(id_points.tolist())
        else:
            obj.EndRotate()
def test_vtkInteractorStyleRubberBandPick():
    ren = vtk.vtkRenderer()
    ren.SetBackground(1.0, 1.0, 1.0)

    V, T = box_model(5, 10, 1.0, 1.0)
    poly_data = numpy_to_vtkPolyData(V, faces.faces_to_cell_array(T))

    idFilter = vtk.vtkIdFilter()
    idFilter.SetInput(poly_data)
    idFilter.SetIdsArrayName('i')
    idFilter.Update()

    poly_data = idFilter.GetOutput()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(poly_data)
    mapper.SetScalarVisibility(False)

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)
    actor.GetProperty().SetColor(0.0, 0.6, 0.3)

    ren.AddActor(actor)

    visible = vtk.vtkSelectVisiblePoints()
    visible.SetInput(poly_data)
    visible.SetRenderer(ren)

    # highlight
    sphere = vtk.vtkSphereSource()
    sphere.SetRadius(0.2)

    highlight_poly_data = vtk.vtkPolyData()

    highlight_glyph = vtk.vtkGlyph3D()
    highlight_glyph.SetInput(highlight_poly_data)
    highlight_glyph.SetSourceConnection(sphere.GetOutputPort())

    highlight_mapper = vtk.vtkPolyDataMapper()
    highlight_mapper.SetInputConnection(highlight_glyph.GetOutputPort())

    highlight_actor = vtk.vtkActor()
    highlight_actor.SetMapper(highlight_mapper)
    highlight_actor.GetProperty().SetColor(1.0, 0.0, 0.0)
    highlight_actor.VisibilityOff()
    highlight_actor.PickableOff()
    ren.AddActor(highlight_actor)

    # render window
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(ren)
    render_window.SetSize(400, 400)

    picker = vtk.vtkAreaPicker()

    def pickCallback(obj, event):
        props = obj.GetProp3Ds()
        if props.GetNumberOfItems() <= 0:
            return

        extract_geometry = vtk.vtkExtractGeometry()
        extract_geometry.SetImplicitFunction(picker.GetFrustum())
        extract_geometry.SetInput(props.GetLastProp3D().GetMapper().GetInput())
        extract_geometry.Update()

        unstructured_grid = extract_geometry.GetOutput()

        if unstructured_grid.GetPoints().GetNumberOfPoints() <= 0:
            return

        visible.Update()
        if visible.GetOutput().GetPoints().GetNumberOfPoints() <= 0:
            return

        i = np.intersect1d(
            vtk_to_numpy(unstructured_grid.GetPointData().GetArray('i')),
            vtk_to_numpy(visible.GetOutput().GetPointData().GetArray('i')))

        if i.shape[0] <= 0:
            return

        vtk_points = vtk.vtkPoints()
        vtk_points.SetNumberOfPoints(i.shape[0])
        vtk_points_data = vtk_to_numpy(vtk_points.GetData())
        vtk_points_data.flat = np.require(V[i], np.float32, 'C')

        highlight_poly_data.SetPoints(vtk_points)
        highlight_actor.VisibilityOn()

    picker.AddObserver('EndPickEvent', pickCallback)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(render_window)
    iren.SetPicker(picker)

    ren.ResetCamera()

    render_window.Render()

    style = vtk.vtkInteractorStyleRubberBandPick()
    style.SetCurrentRenderer(ren)
    iren.SetInteractorStyle(style)

    iren.Initialize()
    iren.Start()
示例#15
0
label_face_ids = False
sources = []
if draw_folding:
    sources.append(folding)
if draw_plane:
    sources.append(plane)
if draw_surface:
    sources.append(surface)
for source in sources:
    if label_faces:
        cell_centers = vtk.vtkCellCenters()
        if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
            cell_centers.SetInputData(source)
        else:
            cell_centers.SetInput(source)
        visible_only = vtk.vtkSelectVisiblePoints()
        visible_only.SetRenderer(ren)
        visible_only.SetInputConnection(cell_centers.GetOutputPort())
        labels = vtk.vtkLabeledDataMapper()
        labels.SetInputConnection(visible_only.GetOutputPort())
        labels.SetLabelModeToLabelScalars()
        labels.GetLabelTextProperty().SetJustificationToCentered()
        labels.GetLabelTextProperty().SetVerticalJustificationToCentered()
        labels_actor = vtk.vtkActor2D()
        labels_actor.SetMapper(labels)
        ren.AddActor(labels_actor)
    if label_face_ids:
        cell_centers = vtk.vtkCellCenters()
        if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
            cell_centers.SetInputData(source)
        else:
示例#16
0
    boundary_tubeActor.SetMapper( boundary_tubeMapper )
    boundary_tubeActor.GetProperty().SetColor(0,0,0)
    ren.AddActor( boundary_tubeActor )

sources = [ ]
if draw_folding: sources.append( folding )
if draw_plane: sources.append( plane )
if draw_surface: sources.append( surface )
for source in sources:
    if label_faces:
        cell_centers = vtk.vtkCellCenters()
        if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
            cell_centers.SetInputData( source )
        else:
            cell_centers.SetInput( source )
        visible_only = vtk.vtkSelectVisiblePoints()
        visible_only.SetRenderer(ren)
        visible_only.SetInputConnection( cell_centers.GetOutputPort() )
        labels = vtk.vtkLabeledDataMapper()
        labels.SetInputConnection( visible_only.GetOutputPort() )
        labels.SetLabelModeToLabelScalars()
        labels.GetLabelTextProperty().SetJustificationToCentered()
        labels.GetLabelTextProperty().SetVerticalJustificationToCentered()
        labels_actor = vtk.vtkActor2D()
        labels_actor.SetMapper( labels )
        ren.AddActor( labels_actor )
    if label_face_ids:
        cell_centers = vtk.vtkCellCenters()
        if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
            cell_centers.SetInputData( source )
        else:
    def _setup_pipeline(self):
        ren = vtk.vtkRenderer()
        ren.SetBackground(1.0, 1.0, 1.0)

        color_points = vtk.vtkProgrammableFilter()

        def callback_color_points():
            input_ = color_points.GetInput()
            output = color_points.GetOutput()
            output.ShallowCopy(input_)

            lookup = vtk.vtkFloatArray()
            lookup.SetNumberOfValues(input_.GetNumberOfPoints())
            npy_lookup = vtk_to_numpy(lookup)
            npy_lookup.flat = self._k.astype(
                np.float32) / (COLORMAP.shape[0] - 1)

            output.GetPointData().SetScalars(lookup)

        color_points.SetExecuteMethod(callback_color_points)

        source = vtk.vtkCubeSource()

        vertices_glyph = vtk.vtkGlyph3D()
        vertices_glyph.SetInputConnection(color_points.GetOutputPort())
        vertices_glyph.SetSourceConnection(source.GetOutputPort())
        vertices_glyph.SetScaleModeToDataScalingOff()
        vertices_glyph.SetColorModeToColorByScalar()

        vertices_mapper = vtk.vtkPolyDataMapper()
        vertices_mapper.SetInputConnection(vertices_glyph.GetOutputPort())
        vertices_mapper.SetLookupTable(LUT)

        vertices_actor = vtk.vtkActor()
        vertices_actor.SetMapper(vertices_mapper)
        vertices_actor.GetProperty().SetColor(*COLORMAP[0, :3])
        vertices_actor.PickableOff()
        vertices_actor.VisibilityOff()
        ren.AddActor(vertices_actor)

        color_faces = vtk.vtkProgrammableFilter()

        def callback_color_faces():
            input_ = color_faces.GetInput()
            output = color_faces.GetOutput()
            output.ShallowCopy(input_)

            lookup = vtk.vtkFloatArray()
            lookup.SetNumberOfValues(input_.GetNumberOfPolys())
            npy_lookup = vtk_to_numpy(lookup)

            labelled_T = self._k[self.T]
            for i in xrange(input_.GetNumberOfPolys()):
                l = np.argmax(np.bincount(labelled_T[i]))
                npy_lookup[i] = float(l) / (COLORMAP.shape[0] - 1)

            output.GetCellData().SetScalars(lookup)

        color_faces.SetExecuteMethod(callback_color_faces)

        model_mapper = vtk.vtkPolyDataMapper()
        model_mapper.SetInputConnection(color_faces.GetOutputPort())
        model_mapper.SetLookupTable(LUT)

        model_actor = vtk.vtkActor()
        model_actor.SetMapper(model_mapper)
        model_actor.GetProperty().SetColor(*COLORMAP[0, :3])
        model_actor.VisibilityOff()
        ren.AddActor(model_actor)

        render_window = vtk.vtkRenderWindow()
        render_window.AddRenderer(ren)
        render_window.SetSize(400, 400)
        self.SetRenderWindow(render_window)

        visible = vtk.vtkSelectVisiblePoints()
        visible.SetRenderer(ren)

        picker = vtk.vtkAreaPicker()

        def callback_picker(obj, event):
            props = obj.GetProp3Ds()
            if props.GetNumberOfItems() <= 0:
                return

            extract_geometry = vtk.vtkExtractGeometry()
            extract_geometry.SetImplicitFunction(picker.GetFrustum())
            extract_geometry.SetInput(visible.GetInput())
            extract_geometry.Update()

            unstructured_grid = extract_geometry.GetOutput()
            if unstructured_grid.GetPoints().GetNumberOfPoints() <= 0:
                return

            i = vtk_to_numpy(unstructured_grid.GetPointData().GetArray('i'))

            if self.select_only_visible:
                visible.Update()

                if visible.GetOutput().GetPoints().GetNumberOfPoints() <= 0:
                    return

                i = np.intersect1d(
                    i,
                    vtk_to_numpy(
                        visible.GetOutput().GetPointData().GetArray('i')))

                if i.shape[0] <= 0:
                    return

            self.set_labels(self.current_label, i)

        picker.AddObserver('EndPickEvent', callback_picker)

        iren = self.GetInteractor()
        iren.SetRenderWindow(render_window)
        iren.SetPicker(picker)

        style = vtk.vtkInteractorStyleRubberBandPick()
        style.SetCurrentRenderer(ren)
        iren.SetInteractorStyle(style)

        self.pipeline = locals()

        self.setSizePolicy(QtGui.QSizePolicy.Expanding,
                           QtGui.QSizePolicy.Expanding)
示例#18
0
def draw_vtk(nodes,
             elements,
             values=None,
             colors_count=256,
             contours_count=10,
             use_gray=False,
             title=None,
             background=(0.95, 0.95, 0.95),
             show_mesh=False,
             mesh_color=(0.25, 0.25, 0.25),
             use_cell_data=False,
             show_labels=False,
             show_axes=False):
    """
    Function draws planar unstructured mesh using vtk
    :param show_axes: if it equals true than axes is drawn
    :param use_cell_data: if it equals true than cell data is used to colorize zones
    :param show_labels: if it equals true than labels are shown
    :param show_mesh: if it equals true than mesh lines are shown
    :param mesh_color: color of mesh lines (polygons edges)
    :param contours_count: Contour lines count
    :param title: Title of the scalar bar
    :param background: Background RGB-color value
    :param use_gray: if it equals true than gray-scale colormap is used
    :param colors_count: Colors count for values visualization
    :param nodes: nodes array [nodes_count; 2]
    :param elements: elements array [elements_count; element_nodes]
    :param values: values array (coloring rule)
    :return: nothing
    """
    import vtk
    points = vtk.vtkPoints()
    for n in nodes:
        if len(n) == 2:
            points.InsertNextPoint([n[0], n[1], 0.0])
        elif len(n) == 3:
            points.InsertNextPoint([n[0], n[1], n[2]])

    cells_array = vtk.vtkCellArray()

    for el in elements:
        polygon = vtk.vtkPolygon()
        polygon.GetPointIds().SetNumberOfIds(len(el))
        for i in range(len(el)):
            polygon.GetPointIds().SetId(i, el[i])

        cells_array.InsertNextCell(polygon)

    lut = vtk.vtkLookupTable()
    lut.SetNumberOfTableValues(colors_count)
    lut.SetHueRange(0.66667, 0.0)

    if use_gray:
        lut.SetValueRange(1.0, 0.0)
        lut.SetSaturationRange(0.0, 0.0)  # no color saturation
        lut.SetRampToLinear()

    lut.Build()
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(background)
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)
    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)

    bcf_actor = vtk.vtkActor()
    bcf_mapper = vtk.vtkPolyDataMapper()
    poly_data = vtk.vtkPolyData()
    poly_data.SetPoints(points)
    poly_data.SetPolys(cells_array)

    if values is not None:
        scalars = vtk.vtkFloatArray()

        for v in values:
            scalars.InsertNextValue(v)

        poly_data.GetPointData().SetScalars(scalars)
        bcf = vtk.vtkBandedPolyDataContourFilter()

        if vtk.VTK_MAJOR_VERSION <= 5:
            bcf.SetInput(poly_data)
        else:
            bcf.SetInputData(poly_data)

        if contours_count > 0:
            bcf.SetNumberOfContours(contours_count)
            bcf.GenerateValues(contours_count, [values.min(), values.max()])
            bcf.SetNumberOfContours(contours_count + 1)
            bcf.GenerateContourEdgesOn()

        bcf.Update()
        bcf_mapper.ImmediateModeRenderingOn()

        if vtk.VTK_MAJOR_VERSION <= 5:
            bcf_mapper.SetInput(bcf.GetOutput())
        else:
            bcf_mapper.SetInputData(bcf.GetOutput())

        bcf_mapper.SetScalarRange(values.min(), values.max())
        bcf_mapper.SetLookupTable(lut)
        bcf_mapper.ScalarVisibilityOn()

        if use_cell_data:
            bcf_mapper.SetScalarModeToUseCellData()

        bcf_actor.SetMapper(bcf_mapper)
        renderer.AddActor(bcf_actor)
        edge_mapper = vtk.vtkPolyDataMapper()

        if vtk.VTK_MAJOR_VERSION <= 5:
            edge_mapper.SetInput(bcf.GetContourEdgesOutput())
        else:
            edge_mapper.SetInputData(bcf.GetContourEdgesOutput())

        edge_mapper.SetResolveCoincidentTopologyToPolygonOffset()
        edge_actor = vtk.vtkActor()
        edge_actor.SetMapper(edge_mapper)

        if use_gray:
            edge_actor.GetProperty().SetColor(0.0, 1.0, 0.0)
        else:
            edge_actor.GetProperty().SetColor(0.0, 0.0, 0.0)

        renderer.AddActor(edge_actor)

        if show_labels:
            mask = vtk.vtkMaskPoints()

            if vtk.VTK_MAJOR_VERSION <= 5:
                mask.SetInput(bcf.GetOutput())
            else:
                mask.SetInputData(bcf.GetOutput())

            mask.SetOnRatio(bcf.GetOutput().GetNumberOfPoints() / 20)
            mask.SetMaximumNumberOfPoints(20)
            # Create labels for points - only show visible points
            visible_points = vtk.vtkSelectVisiblePoints()
            visible_points.SetInputConnection(mask.GetOutputPort())
            visible_points.SetRenderer(renderer)
            ldm = vtk.vtkLabeledDataMapper()
            ldm.SetInputConnection(mask.GetOutputPort())
            ldm.SetLabelFormat("%.2E")
            ldm.SetLabelModeToLabelScalars()
            text_property = ldm.GetLabelTextProperty()
            text_property.SetFontFamilyToArial()
            text_property.SetFontSize(10)

            if use_gray:
                text_property.SetColor(0.0, 1.0, 0.0)
            else:
                text_property.SetColor(0.0, 0.0, 0.0)

            text_property.ShadowOff()
            text_property.BoldOff()
            contour_labels = vtk.vtkActor2D()
            contour_labels.SetMapper(ldm)
            renderer.AddActor(contour_labels)

        scalar_bar = vtk.vtkScalarBarActor()
        scalar_bar.SetOrientationToHorizontal()
        scalar_bar.SetLookupTable(lut)

        if title is not None:
            scalar_bar.SetTitle(title)

        scalar_bar_widget = vtk.vtkScalarBarWidget()
        scalar_bar_widget.SetInteractor(render_window_interactor)
        scalar_bar_widget.SetScalarBarActor(scalar_bar)
        scalar_bar_widget.On()
    else:
        if vtk.VTK_MAJOR_VERSION <= 5:
            bcf_mapper.SetInput(poly_data)
        else:
            bcf_mapper.SetInputData(poly_data)

        bcf_actor.GetProperty().SetColor(0.0, 1.0, 0.0)

    if show_mesh:
        bcf_actor.GetProperty().EdgeVisibilityOn()
        bcf_actor.GetProperty().SetEdgeColor(mesh_color)

    bcf_actor.SetMapper(bcf_mapper)
    renderer.AddActor(bcf_actor)

    if show_axes:
        axes = vtk.vtkAxesActor()
        renderer.AddActor(axes)

    render_window.Render()
    render_window_interactor.Start()
示例#19
0
文件: mesh2d.py 项目: qzcad/pyfem
def draw_vtk(nodes,
             elements,
             values=None,
             colors_count=256,
             contours_count=10,
             use_gray=False,
             title=None,
             background=(0.95, 0.95, 0.95),
             show_mesh=False,
             mesh_color=(0.25, 0.25, 0.25),
             use_cell_data=False,
             show_labels=False,
             show_axes=False):
    """
    Function draws planar unstructured mesh using vtk
    :param show_axes: if it equals true than axes is drawn
    :param use_cell_data: if it equals true than cell data is used to colorize zones
    :param show_labels: if it equals true than labels are shown
    :param show_mesh: if it equals true than mesh lines are shown
    :param mesh_color: color of mesh lines (polygons edges)
    :param contours_count: Contour lines count
    :param title: Title of the scalar bar
    :param background: Background RGB-color value
    :param use_gray: if it equals true than gray-scale colormap is used
    :param colors_count: Colors count for values visualization
    :param nodes: nodes array [nodes_count; 2]
    :param elements: elements array [elements_count; element_nodes]
    :param values: values array (coloring rule)
    :return: nothing
    """
    import vtk
    points = vtk.vtkPoints()
    for n in nodes:
        points.InsertNextPoint([n[0], n[1], 0.0])
    cells_array = vtk.vtkCellArray()
    for el in elements:
        polygon = vtk.vtkPolygon()
        polygon.GetPointIds().SetNumberOfIds(len(el))
        for i in range(len(el)):
            polygon.GetPointIds().SetId(i, el[i])
        cells_array.InsertNextCell(polygon)
    lut = vtk.vtkLookupTable()
    lut.SetNumberOfTableValues(colors_count)
    lut.SetHueRange(0.66667, 0.0)
    if use_gray:
        lut.SetValueRange(1.0, 0.0)
        lut.SetSaturationRange(0.0, 0.0)  # no color saturation
        lut.SetRampToLinear()
    lut.Build()
    renderer = vtk.vtkRenderer()
    renderer.SetBackground(background)
    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)
    render_window_interactor = vtk.vtkRenderWindowInteractor()
    render_window_interactor.SetRenderWindow(render_window)

    bcf_actor = vtk.vtkActor()
    bcf_mapper = vtk.vtkPolyDataMapper()
    poly_data = vtk.vtkPolyData()
    poly_data.SetPoints(points)
    poly_data.SetPolys(cells_array)

    if values is not None:
        scalars = vtk.vtkFloatArray()
        for v in values:
            scalars.InsertNextValue(v)
        poly_data.GetPointData().SetScalars(scalars)
        bcf = vtk.vtkBandedPolyDataContourFilter()
        if vtk.VTK_MAJOR_VERSION <= 5:
            bcf.SetInput(poly_data)
        else:
            bcf.SetInputData(poly_data)
        bcf.SetNumberOfContours(contours_count)
        bcf.GenerateValues(contours_count, [values.min(), values.max()])
        bcf.SetNumberOfContours(contours_count + 1)
        bcf.SetScalarModeToValue()
        bcf.GenerateContourEdgesOn()
        bcf.Update()
        bcf_mapper.ImmediateModeRenderingOn()
        if vtk.VTK_MAJOR_VERSION <= 5:
            bcf_mapper.SetInput(bcf.GetOutput())
        else:
            bcf_mapper.SetInputData(bcf.GetOutput())
        bcf_mapper.SetScalarRange(values.min(), values.max())
        bcf_mapper.SetLookupTable(lut)
        bcf_mapper.ScalarVisibilityOn()
        if use_cell_data:
            bcf_mapper.SetScalarModeToUseCellData()

        bcf_actor.SetMapper(bcf_mapper)
        renderer.AddActor(bcf_actor)
        edge_mapper = vtk.vtkPolyDataMapper()
        if vtk.VTK_MAJOR_VERSION <= 5:
            edge_mapper.SetInput(bcf.GetContourEdgesOutput())
        else:
            edge_mapper.SetInputData(bcf.GetContourEdgesOutput())
        edge_mapper.SetResolveCoincidentTopologyToPolygonOffset()
        edge_actor = vtk.vtkActor()
        edge_actor.SetMapper(edge_mapper)
        if use_gray:
            edge_actor.GetProperty().SetColor(0.0, 1.0, 0.0)
        else:
            edge_actor.GetProperty().SetColor(0.0, 0.0, 0.0)
        renderer.AddActor(edge_actor)

        if show_labels:
            mask = vtk.vtkMaskPoints()
            if vtk.VTK_MAJOR_VERSION <= 5:
                mask.SetInput(bcf.GetOutput())
            else:
                mask.SetInputData(bcf.GetOutput())
            mask.SetOnRatio(bcf.GetOutput().GetNumberOfPoints() / 20)
            mask.SetMaximumNumberOfPoints(20)
            # Create labels for points - only show visible points
            visible_points = vtk.vtkSelectVisiblePoints()
            visible_points.SetInputConnection(mask.GetOutputPort())
            visible_points.SetRenderer(renderer)
            ldm = vtk.vtkLabeledDataMapper()
            ldm.SetInputConnection(mask.GetOutputPort())
            ldm.SetLabelFormat("%.2E")
            ldm.SetLabelModeToLabelScalars()
            text_property = ldm.GetLabelTextProperty()
            text_property.SetFontFamilyToArial()
            text_property.SetFontSize(10)
            if use_gray:
                text_property.SetColor(0.0, 1.0, 0.0)
            else:
                text_property.SetColor(0.0, 0.0, 0.0)
            text_property.ShadowOff()
            text_property.BoldOff()
            contour_labels = vtk.vtkActor2D()
            contour_labels.SetMapper(ldm)
            renderer.AddActor(contour_labels)

        scalar_bar = vtk.vtkScalarBarActor()
        scalar_bar.SetOrientationToHorizontal()
        scalar_bar.SetLookupTable(lut)
        if title is not None:
            scalar_bar.SetTitle(title)
        scalar_bar_widget = vtk.vtkScalarBarWidget()
        scalar_bar_widget.SetInteractor(render_window_interactor)
        scalar_bar_widget.SetScalarBarActor(scalar_bar)
        scalar_bar_widget.On()
    else:
        if vtk.VTK_MAJOR_VERSION <= 5:
            bcf_mapper.SetInput(poly_data)
        else:
            bcf_mapper.SetInputData(poly_data)
        bcf_actor.GetProperty().SetColor(0.0, 1.0, 0.0)

    if show_mesh:
        bcf_actor.GetProperty().EdgeVisibilityOn()
        bcf_actor.GetProperty().SetEdgeColor(mesh_color)

    bcf_actor.SetMapper(bcf_mapper)
    renderer.AddActor(bcf_actor)

    if show_axes:
        axes = vtk.vtkAxesActor()
        renderer.AddActor(axes)

    render_window.Render()
    render_window_interactor.Start()
示例#20
0
文件: labeledMesh.py 项目: 0004c/VTK
sphereMapper.GlobalImmediateModeRenderingOn()
sphereActor = vtk.vtkActor()
sphereActor.SetMapper(sphereMapper)

# Generate data arrays containing point and cell ids
ids = vtk.vtkIdFilter()
ids.SetInputConnection(sphere.GetOutputPort())
ids.PointIdsOn()
ids.CellIdsOn()
ids.FieldDataOn()

# Create the renderer here because vtkSelectVisiblePoints needs it.
ren = vtk.vtkRenderer()

# Create labels for points
visPts = vtk.vtkSelectVisiblePoints()
visPts.SetInputConnection(ids.GetOutputPort())
visPts.SetRenderer(ren)
visPts.SelectionWindowOn()
visPts.SetSelection(xmin, xmin + xLength, ymin, ymin + yLength)

# Create the mapper to display the point ids.  Specify the format to
# use for the labels.  Also create the associated actor.
ldm = vtk.vtkLabeledDataMapper()
# ldm.SetLabelFormat("%g")
ldm.SetInputConnection(visPts.GetOutputPort())
ldm.SetLabelModeToLabelFieldData()
pointLabels = vtk.vtkActor2D()
pointLabels.SetMapper(ldm)

# Create labels for cells
示例#21
0
def remove_non_visible_faces(
    polydata,
    positions=[[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]],
    remove_visible=False,
):
    polydata.BuildLinks()

    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(polydata)
    mapper.Update()

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

    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)

    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)
    render_window.SetSize(800, 800)
    render_window.OffScreenRenderingOn()

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

    pos = np.array(camera.GetPosition())
    fp = np.array(camera.GetFocalPoint())
    v = pos - fp
    mag = np.linalg.norm(v)
    vn = v / mag

    id_filter = vtk.vtkIdFilter()
    id_filter.SetInputData(polydata)
    id_filter.PointIdsOn()
    id_filter.Update()

    set_points = None

    for position in positions:
        pos = fp + np.array(position) * mag
        camera.SetPosition(pos.tolist())
        renderer.ResetCamera()
        render_window.Render()

        select_visible_points = vtk.vtkSelectVisiblePoints()
        select_visible_points.SetInputData(id_filter.GetOutput())
        select_visible_points.SetRenderer(renderer)
        #  select_visible_points.SelectInvisibleOn()
        select_visible_points.Update()
        output = select_visible_points.GetOutput()
        id_points = numpy_support.vtk_to_numpy(
            output.GetPointData().GetAbstractArray("vtkIdFilter_Ids")
        )
        if set_points is None:
            set_points = set(id_points.tolist())
        else:
            set_points.update(id_points.tolist())
        #  id_list = vtk.vtkIdList()
        #  output.GetVerts().GetCell(1000, id_list)

    if remove_visible:
        set_points = set(range(polydata.GetNumberOfPoints())) - set_points
    cells_ids = set()
    for p_id in set_points:
        id_list = vtk.vtkIdList()
        polydata.GetPointCells(p_id, id_list)
        for i in range(id_list.GetNumberOfIds()):
            cells_ids.add(id_list.GetId(i))

    try:
        id_list = numpy_support.numpy_to_vtkIdTypeArray(np.array(list(cells_ids), dtype=np.int64))
    except ValueError:
        id_list = vtk.vtkIdTypeArray()

    selection_node = vtk.vtkSelectionNode()
    selection_node.SetFieldType(vtk.vtkSelectionNode.CELL)
    selection_node.SetContentType(vtk.vtkSelectionNode.INDICES)
    selection_node.SetSelectionList(id_list)

    selection = vtk.vtkSelection()
    selection.AddNode(selection_node)

    extract_selection = vtk.vtkExtractSelection()
    extract_selection.SetInputData(0, polydata)
    extract_selection.SetInputData(1, selection)
    extract_selection.Update()

    geometry_filter = vtk.vtkGeometryFilter()
    geometry_filter.SetInputData(extract_selection.GetOutput())
    geometry_filter.Update()

    clean_polydata = vtk.vtkCleanPolyData()
    clean_polydata.SetInputData(geometry_filter.GetOutput())
    clean_polydata.Update()

    return clean_polydata.GetOutput()
示例#22
0
文件: Labels.py 项目: sldion/DNACC
    def __init__ (self, mod_m, module=None, n_points=25, vis_points=0):
        """Input arguments:

        mod_m -- Module manager that manages this module.

        module -- Module to label.  Can be given a module name (the
        same name as listed in the Modules GUI) or an index of the
        module (starting from 0) in the current module manager.  If
        the value is -1, then the filtered data from the module
        manager is used.  The value defaults to None where the user is
        asked to specify the module to label.

        n_points -- Number of points to label.  Defaults to 25.

        vis_points -- If 1 turns on the vtkSelectVisiblePoints filter.
        Defaults to 0.    
        """
        debug ("In Labels::__init__ ()")
        Base.Objects.Module.__init__ (self, mod_m)

        self.act = None
        self.input = None
        self.mod_num = -1
        if module is not None:
            self._set_input(module)
        if not self.input:
            res = self._get_input_gui()
            self._set_input(res)
        
        if not self.input:
            msg = "Sorry, you need to choose a valid module in order to "\
                  "use this module."
            raise Base.Objects.ModuleException, msg
        input = self.input
        
        Common.state.busy ()
        self.n_points = n_points
        self.vis_points = vis_points
        self.mask = vtk.vtkMaskPoints ()
        n = input.GetNumberOfPoints ()
        self.mask.SetInput (input)
        self.mask.SetOnRatio (max(n/n_points, 1))
        self.mask.GenerateVerticesOn()
        self.mask.RandomModeOn ()
        self.vis_pnts = vtk.vtkSelectVisiblePoints ()
        self.vis_pnts.SetRenderer(self.renwin.get_renderer())
        self.mapper = self.map = vtk.vtkLabeledDataMapper ()
        self.mapper.SetLabelModeToLabelScalars()
        self.tprop = None
        if hasattr(self.mapper, "GetLabelTextProperty"):
            self.tprop = self.mapper.GetLabelTextProperty()
            self.tprop.SetColor (*Common.config.fg_color)
            self.tprop.SetOpacity(1.0)

        if vis_points:
            self.vis_pnts.SetInput (self.mask.GetOutput ())
            self.mapper.SetInput (self.vis_pnts.GetOutput ())
        else:
            self.mapper.SetInput (self.mask.GetOutput ())
            
        self.actor = self.act = vtk.vtkActor2D ()
        self.actor.SetMapper (self.mapper)
        self.vis_pnt_gui = None
        self.act.GetProperty ().SetColor (*Common.config.fg_color)
        self.renwin.add_actors (self.act)
        # used for the pipeline browser
        self.pipe_objs = self.act
        self.renwin.Render ()
        Common.state.idle ()
示例#23
0
        surfaceMapper.SetInput(surface)
    surfaceMapper.SetScalarRange(0, 24)
    surfaceMapper.SetLookupTable(lut)
    #surfaceMapper.ScalarVisibilityOff()
    surfaceActor = vtk.vtkActor()
    surfaceActor.SetMapper(surfaceMapper)
    #surfaceActor.GetProperty().SetOpacity(0.7)
    ren.AddActor(surfaceActor)

    if label_faces:
        kq_cell_centers = vtk.vtkCellCenters()
        if vtk.vtkVersion.GetVTKMajorVersion() >= 6:
            kq_cell_centers.SetInputData(surface)
        else:
            kq_cell_centers.SetInput(surface)
        kq_visible_only = vtk.vtkSelectVisiblePoints()
        kq_visible_only.SetRenderer(ren)
        kq_visible_only.SetInputConnection(kq_cell_centers.GetOutputPort())
        kq_labels = vtk.vtkLabeledDataMapper()
        kq_labels.SetInputConnection(kq_visible_only.GetOutputPort())
        kq_labels.SetLabelModeToLabelScalars()
        kq_labels.SetLabelFormat("%.0f")
        kq_labels.GetLabelTextProperty().SetJustificationToCentered()
        kq_labels.GetLabelTextProperty().SetVerticalJustificationToCentered()
        kq_labels_actor = vtk.vtkActor2D()
        kq_labels_actor.SetMapper(kq_labels)
        ren.AddActor(kq_labels_actor)

draw_edges = True
if draw_edges:
    lines = vtk.vtkExtractEdges()
示例#24
0
iso.Update()
numPts = iso.GetOutput().GetNumberOfPoints()
isoMapper = vtk.vtkPolyDataMapper()
isoMapper.SetInputConnection(iso.GetOutputPort())
isoMapper.ScalarVisibilityOn()
isoMapper.SetScalarRange(iso.GetOutput().GetScalarRange())
isoActor = vtk.vtkActor()
isoActor.SetMapper(isoMapper)
# Subsample the points and label them
mask = vtk.vtkMaskPoints()
mask.SetInputConnection(iso.GetOutputPort())
mask.SetOnRatio(expr.expr(globals(), locals(),["numPts","/","50"]))
mask.SetMaximumNumberOfPoints(50)
mask.RandomModeOn()
# Create labels for points - only show visible points
visPts = vtk.vtkSelectVisiblePoints()
visPts.SetInputConnection(mask.GetOutputPort())
visPts.SetRenderer(ren1)
ldm = vtk.vtkLabeledDataMapper()
ldm.SetInputConnection(mask.GetOutputPort())
#    ldm SetLabelFormat "%g"
ldm.SetLabelModeToLabelScalars()
tprop = ldm.GetLabelTextProperty()
tprop.SetFontFamilyToArial()
tprop.SetFontSize(10)
tprop.SetColor(1,0,0)
contourLabels = vtk.vtkActor2D()
contourLabels.SetMapper(ldm)
# Add the actors to the renderer, set the background and size
#
ren1.AddActor2D(isoActor)
示例#25
0
 def display_annot(self, images,  image_pos_pat, image_ori_pat, annots_dict_list, interact):
     '''Display list of annotations, put markers according to notes and color code according to sequence order'''
     # define image based on subtraction of postS -preS          
     image = images[4]            
          
     # Proceed to build reference frame for display objects based on DICOM coords   
     [self.transformed_image, transform_cube] = self.dicomTransform(image, image_pos_pat, image_ori_pat)
     
     # supports 56 annotations
     color_list = [ [0,0,0], [1,0,0], [0,0,1], [0,1,1], [1,1,0], [1,0,1], [1,1,1], [0.5,0.5,0.5], [0.5,0.5,0],    [1,0.2,0], [1,1,0], [0,1,1],[0,1,0.6], [0,1,1], [1,0.4,0], [0.6,0,0.2], [1,1,0], [0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0],[0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0], 
                     [0,0,0], [1,0,0], [0,0,1], [0,1,1], [1,1,0], [1,0,1], [1,1,1], [0.5,0.5,0.5], [0.5,0.5,0],    [1,0.2,0], [1,1,0], [0,1,1],[0,1,0.6], [0,1,1], [1,0.4,0], [0.6,0,0.2], [1,1,0], [0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0],[0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0] ]
     a_count = 1
     annot_pts_lbl = vtk.vtkPoints()
     for annots_dict in annots_dict_list:
         try:
             float(annots_dict['SliceLocation'])
             print '\n=========#'+str(a_count)
             print annots_dict            
             ######################
             ## Display in graphics
             ######################
             im_pt = [0,0,0]
             ijk = [0,0,0]
             pco = [0,0,0]
             pi_2display=[0,0,0]
             pf_2display=[0,0,0]
             
             # extract Slice locaton
             pixId_sliceloc = self.transformed_image.FindPoint(self.origin[0], self.origin[1], float(annots_dict['SliceLocation']))
             self.transformed_image.GetPoint(pixId_sliceloc, im_pt) 
             io = self.transformed_image.ComputeStructuredCoordinates( im_pt, ijk, pco)
             
             # mark initial
             print "Point init"
             ijk[0] = int(annots_dict['xi'])
             ijk[1] = int(annots_dict['yi'])
             print ijk
             annots_dict['pi_ijk']=ijk
             pixId = self.transformed_image.ComputePointId(ijk)
             pi_2display = self.transformed_image.GetPoint(pixId)
             annots_dict['pi_2display']=pi_2display
             print pi_2display
             
             # mark final
             print "Point final"
             ijk[0] = int(annots_dict['xf'])
             ijk[1] = int(annots_dict['yf'])
             print ijk
             annots_dict['pf_ijk']=ijk
             pixId = self.transformed_image.ComputePointId(ijk)
             pf_2display = self.transformed_image.GetPoint(pixId)
             annots_dict['pf_2display']=pf_2display
             print pf_2display
             
             # Create a graphial line between the two points
             annot_pts = vtk.vtkPoints()
             annot_pts.InsertNextPoint(pi_2display)
             annot_pts.InsertNextPoint(pf_2display)
   
             annot_ln = vtk.vtkLine()
             annot_ln.GetPointIds().SetId(0,0)
             annot_ln.GetPointIds().SetId(1,1)
             note_lines = vtk.vtkCellArray()
             note_lines.InsertNextCell(annot_ln)
             
             annot_poly = vtk.vtkPolyData()
             annot_poly.SetPoints(annot_pts)
             annot_poly.SetLines(note_lines)
             annot_poly.Update()
 
             # Create mappers and actors
             annot_mapper_mesh = vtk.vtkPolyDataMapper()
             annot_mapper_mesh.SetInput( annot_poly )
                         
             self.annot_actor = vtk.vtkActor()
             self.annot_actor.SetMapper(annot_mapper_mesh)
             self.annot_actor.GetProperty().SetColor(color_list[a_count])
             self.annot_actor.GetProperty().SetLineWidth(3)
             self.annot_actor.GetProperty().SetOpacity(0.6)
             self.annot_actor.GetProperty().SetPointSize(7.0)
             self.annot_actor.GetProperty().SetRepresentationToWireframe()
             
             ############
             # Generate data arrays containing label ids
             annot_pts_lbl.InsertPoint(a_count, pi_2display)
                                
             # add annotation to scene
             print annots_dict
             self.renderer1.AddActor(self.annot_actor)
                     
             # Initizalize
             self.renWin1.Render()
             self.renderer1.Render()
             a_count +=1
         
         except ValueError:
             a_count +=1
             pass
         
     ############
     print annot_pts_lbl.GetNumberOfPoints()
     annot_lbl_poly = vtk.vtkPolyData()
     annot_lbl_poly.SetPoints(annot_pts_lbl)
     annot_lbl_poly.Update()
             
     # Generate data arrays containing label ids                
     ids = vtk.vtkIdFilter()
     ids.SetInput(annot_lbl_poly)
     ids.PointIdsOn()
     ids.CellIdsOff()
     
     # Create labels for points
     visPts = vtk.vtkSelectVisiblePoints()
     visPts.SetInput(ids.GetOutput())
     visPts.SetRenderer(self.renderer1)
     visPts.SelectionWindowOff()
     
     # Create the mapper to display the point ids.  Specify the format to
     # use for the labels.  Also create the associated actor.
     ldm = vtk.vtkLabeledDataMapper()
     ldm.SetInput(visPts.GetOutput())
     ldm.SetLabelModeToLabelFieldData()
     pointLabels = vtk.vtkActor2D()
     pointLabels.SetMapper(ldm)
                     
     # initialize 
     self.renderer1.AddActor2D(pointLabels)
     
     print "\n====== Color codes:\n "
     print '\033[1;31m 1) Red '
     print '\033[1;34m 2) Blue '
     print '\033[1;36m 3) Cyan '
     print '\033[1;33m 4) Yellow '
     print '\033[1;35m 5) Fushia '
     print '\033[1;37m 6) White '
     print '\033[1;30m 7) Gray '
     print '\033[1;0m'
     
     ############                
     if(interact==True):
         interactor = self.renWin1.GetInteractor()
         interactor.Start()
         
     return
示例#26
0
 def display_annot(self, images,  image_pos_pat, image_ori_pat, annots_dict_list, interact):
     '''Display list of annotations, put markers according to notes and color code according to sequence order'''
     # define image based on subtraction of postS -preS          
     image = images[4]            
          
     # Proceed to build reference frame for display objects based on DICOM coords   
     [self.transformed_image, transform_cube] = self.dicomTransform(image, image_pos_pat, image_ori_pat)
     
     # supports 56 annotations
     color_list = [ [0,0,0], [1,0,0], [0,0,1], [0,1,1], [1,1,0], [1,0,1], [1,1,1], [0.5,0.5,0.5], [0.5,0.5,0],    [1,0.2,0], [1,1,0], [0,1,1],[0,1,0.6], [0,1,1], [1,0.4,0], [0.6,0,0.2], [1,1,0], [0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0],[0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0], 
                     [0,0,0], [1,0,0], [0,0,1], [0,1,1], [1,1,0], [1,0,1], [1,1,1], [0.5,0.5,0.5], [0.5,0.5,0],    [1,0.2,0], [1,1,0], [0,1,1],[0,1,0.6], [0,1,1], [1,0.4,0], [0.6,0,0.2], [1,1,0], [0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0],[0,1,1],[0,1,0], [0,1,1], [1,0,0.1], [1,0.4,0] ]
     a_count = 1
     annot_pts_lbl = vtk.vtkPoints()
     for annots_dict in annots_dict_list:
         try:
             float(annots_dict['SliceLocation'])
             print '\n=========#'+str(a_count)
             print annots_dict            
             ######################
             ## Display in graphics
             ######################
             im_pt = [0,0,0]
             ijk = [0,0,0]
             pco = [0,0,0]
             pi_2display=[0,0,0]
             pf_2display=[0,0,0]
             
             # extract Slice locaton
             pixId_sliceloc = self.transformed_image.FindPoint(self.origin[0], self.origin[1], float(annots_dict['SliceLocation']))
             self.transformed_image.GetPoint(pixId_sliceloc, im_pt) 
             io = self.transformed_image.ComputeStructuredCoordinates( im_pt, ijk, pco)
             
             # mark initial
             print "Point init"
             ijk[0] = int(annots_dict['xi'])
             ijk[1] = int(annots_dict['yi'])
             print ijk
             annots_dict['pi_ijk']=ijk
             pixId = self.transformed_image.ComputePointId(ijk)
             pi_2display = self.transformed_image.GetPoint(pixId)
             annots_dict['pi_2display']=pi_2display
             print pi_2display
             
             # mark final
             print "Point final"
             ijk[0] = int(annots_dict['xf'])
             ijk[1] = int(annots_dict['yf'])
             print ijk
             annots_dict['pf_ijk']=ijk
             pixId = self.transformed_image.ComputePointId(ijk)
             pf_2display = self.transformed_image.GetPoint(pixId)
             annots_dict['pf_2display']=pf_2display
             print pf_2display
             
             # Create a graphial line between the two points
             annot_pts = vtk.vtkPoints()
             annot_pts.InsertNextPoint(pi_2display)
             annot_pts.InsertNextPoint(pf_2display)
   
             annot_ln = vtk.vtkLine()
             annot_ln.GetPointIds().SetId(0,0)
             annot_ln.GetPointIds().SetId(1,1)
             note_lines = vtk.vtkCellArray()
             note_lines.InsertNextCell(annot_ln)
             
             annot_poly = vtk.vtkPolyData()
             annot_poly.SetPoints(annot_pts)
             annot_poly.SetLines(note_lines)
             annot_poly.Update()
 
             # Create mappers and actors
             annot_mapper_mesh = vtk.vtkPolyDataMapper()
             annot_mapper_mesh.SetInputData( annot_poly )
                         
             self.annot_actor = vtk.vtkActor()
             self.annot_actor.SetMapper(annot_mapper_mesh)
             self.annot_actor.GetProperty().SetColor(color_list[a_count])
             self.annot_actor.GetProperty().SetLineWidth(3)
             self.annot_actor.GetProperty().SetOpacity(0.6)
             self.annot_actor.GetProperty().SetPointSize(7.0)
             self.annot_actor.GetProperty().SetRepresentationToWireframe()
             
             ############
             # Generate data arrays containing label ids
             annot_pts_lbl.InsertPoint(a_count, pi_2display)
                                
             # add annotation to scene
             print annots_dict
             self.renderer1.AddActor(self.annot_actor)
                     
             # Initizalize
             self.renWin1.Render()
             self.renderer1.Render()
             a_count +=1
         
         except ValueError:
             a_count +=1
             pass
         
     ############
     print annot_pts_lbl.GetNumberOfPoints()
     annot_lbl_poly = vtk.vtkPolyData()
     annot_lbl_poly.SetPoints(annot_pts_lbl)
     annot_lbl_poly.Update()
             
     # Generate data arrays containing label ids                
     ids = vtk.vtkIdFilter()
     ids.SetInput(annot_lbl_poly)
     ids.PointIdsOn()
     ids.CellIdsOff()
     
     # Create labels for points
     visPts = vtk.vtkSelectVisiblePoints()
     visPts.SetInput(ids.GetOutput())
     visPts.SetRenderer(self.renderer1)
     visPts.SelectionWindowOff()
     
     # Create the mapper to display the point ids.  Specify the format to
     # use for the labels.  Also create the associated actor.
     ldm = vtk.vtkLabeledDataMapper()
     ldm.SetInput(visPts.GetOutput())
     ldm.SetLabelModeToLabelFieldData()
     pointLabels = vtk.vtkActor2D()
     pointLabels.SetMapper(ldm)
                     
     # initialize 
     self.renderer1.AddActor2D(pointLabels)
     
     print "\n====== Color codes:\n "
     print '\033[1;31m 1) Red '
     print '\033[1;34m 2) Blue '
     print '\033[1;36m 3) Cyan '
     print '\033[1;33m 4) Yellow '
     print '\033[1;35m 5) Fushia '
     print '\033[1;37m 6) White '
     print '\033[1;30m 7) Gray '
     print '\033[1;0m'
     
     ############                
     if(interact==True):
         interactor = self.renWin1.GetInteractor()
         interactor.Start()
         
     return
示例#27
0
def show_solid(solid, wireframe=False, show_vertex_ids=False):
    if wireframe:
        points, cells = solid.as_wireframe()
    else:
        points, cells = solid.as_polydata()

    pd = vtk.vtkPolyData()

    ps = vtk.vtkPoints()
    for i, p in enumerate(points):
        idx = ps.InsertNextPoint(p)
        assert idx == i
    pd.SetPoints(ps)

    ca = vtk.vtkCellArray()
    for c in cells:
        ca.InsertNextCell(len(c))
        for id in c:
            ca.InsertCellPoint(id)
            #print id,
        #print

    if wireframe:
        pd.SetLines(ca)
    else:
        pd.SetPolys(ca)

    tri = vtk.vtkTriangleFilter()
    tri.SetInput(pd)

    map = vtk.vtkPolyDataMapper()
    map.SetInput(tri.GetOutput())

    act = vtk.vtkActor()
    act.SetMapper(map)

    ren = vtk.vtkRenderer()
    ren.AddActor(act)
    ren.SetBackground(0.5, 0.5, 0.5)

    ids = vtk.vtkIdFilter()
    ids.SetInput(pd)
    ids.PointIdsOn()

    visPts = vtk.vtkSelectVisiblePoints()
    visPts.SetInputConnection(ids.GetOutputPort())
    visPts.SetRenderer(ren)

    ldm = vtk.vtkLabeledDataMapper()
    ldm.SetLabelModeToLabelIds()
    #ldm.SetLabelModeToLabelFieldData()
    ldm.SetInputConnection(visPts.GetOutputPort())

    pointLabels = vtk.vtkActor2D()
    pointLabels.SetMapper(ldm)

    if show_vertex_ids:
        ren.AddActor2D(pointLabels)

    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(ren)

    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renwin)
    iren.Initialize()
    iren.Start()
示例#28
0
def displayPolyAndDataLabels(poly, title = 'Polydata'):
    """
    display a poly and 3 planes
    """
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInput(poly)

    actor1 = vtk.vtkActor()
    actor1.SetMapper(mapper)
    actor1.GetProperty().SetColor(1,0,0) #RED
    actor1.GetProperty().SetOpacity(1.0)

    mapper2 = vtk.vtkPolyDataMapper()
    mapper2.SetResolveCoincidentTopologyToPolygonOffset()
    mapper2.ScalarVisibilityOff()
    mapper2.SetInput(poly)
        
    actor2 = vtk.vtkActor()
    actor2.SetMapper(mapper2)
    actor2.GetProperty().SetRepresentationToWireframe()
    actor2.GetProperty().SetColor(1,1,1)
    actor2.GetProperty().SetAmbient(1.0)
    actor2.GetProperty().SetDiffuse(0.0)
    actor2.GetProperty().SetSpecular(0.0)

    ids = vtk.vtkIdFilter()
    ids.SetInput(poly)
    ids.PointIdsOn()
    ids.CellIdsOn()
    ids.FieldDataOn()

    ren= vtk.vtkRenderer()
    ren.AddActor(actor1)
    ren.AddActor(actor2)
    ren.SetBackground(1,1,1)
    
    # Create labels for points
    visPts = vtk.vtkSelectVisiblePoints()
    visPts.SetInputConnection(ids.GetOutputPort())
    visPts.SetRenderer(ren)
    
    # Create the mapper to display the point ids.  Specify the format to
    # use for the labels.  Also create the associated actor.
    ldm = vtk.vtkLabeledDataMapper()
    ldm.GetLabelTextProperty().ShadowOff()
    ldm.GetLabelTextProperty().SetColor(0,0,0)
    # ldm.SetLabelFormat("%g")
    ldm.SetInputConnection(visPts.GetOutputPort())
    ldm.SetLabelModeToLabelFieldData()
    pointLabels = vtk.vtkActor2D()
    pointLabels.SetMapper(ldm)
    ren.AddActor2D(pointLabels)

    renwin = vtk.vtkRenderWindow()
    renwin.AddRenderer(ren)
    renwin.SetSize( 700, 700 )
    renwin.SetWindowName(title)
    
    iren = vtk.vtkRenderWindowInteractor()
    iren.SetRenderWindow(renwin)
    style = vtk.vtkInteractorStyleTrackballCamera()
    iren.SetInteractorStyle(style)
    
    ren.ResetCamera()
    cam1 = ren.GetActiveCamera()
    cam1.Elevation(-90)
    cam1.SetViewUp(0, 0, 1)
    cam1.Azimuth(45)
    ren.ResetCameraClippingRange()
        
    iren.Initialize()
    renwin.Render()
    iren.Start()