Exemple #1
0
def BlenderToPolyData(me, uvlayer=None):

	pcoords = vtk.vtkFloatArray()
	pcoords.SetNumberOfComponents(3)
	pcoords.SetNumberOfTuples(len(me.verts))
	for i in range(len(me.verts)):
		p0 = me.verts[i].co[0]
		p1 = me.verts[i].co[1]
		p2 = me.verts[i].co[2]
		pcoords.SetTuple3(i, p0, p1, p2)

	points = vtk.vtkPoints()
	points.SetData(pcoords)

	polys = vtk.vtkCellArray()
	lines = vtk.vtkCellArray()
	for face in me.faces:
		if len(face.v) == 4:
			polys.InsertNextCell(4)
			polys.InsertCellPoint(face.v[0].index)
			polys.InsertCellPoint(face.v[1].index)
			polys.InsertCellPoint(face.v[2].index)
			polys.InsertCellPoint(face.v[3].index)
		elif len(face.v) == 3:
			polys.InsertNextCell(3)
			polys.InsertCellPoint(face.v[0].index)
			polys.InsertCellPoint(face.v[1].index)
			polys.InsertCellPoint(face.v[2].index)
		elif len(face.v) == 2:
			lines.InsertNextCell(2)
			lines.InsertCellPoint(face.v[0].index)
			lines.InsertCellPoint(face.v[1].index)

	for edge in me.edges:
		lines.InsertNextCell(2)
		lines.InsertCellPoint(edge.v1.index)
		lines.InsertCellPoint(edge.v2.index)

	pdata =vtk.vtkPolyData()
	pdata.SetPoints(points)
	pdata.SetPolys(polys)
	pdata.SetLines(lines)

	if me.faceUV:
		if uvlayer:
			uvnames = me.getUVLayerNames()
			if uvlayer in uvnames:
				me.activeUVLayer = uvlayer
		tcoords = vtk.vtkFloatArray()
		tcoords.SetNumberOfComponents(2)
		tcoords.SetNumberOfTuples(len(me.verts))
		for face in me.faces:
			for i in range(len(face.verts)):
				uv = face.uv[i]
				tcoords.SetTuple2(face.v[i].index, uv[0], uv[1])
		pdata.GetPointData().SetTCoords(tcoords);

	pdata.Update()

	return pdata
def generatePolyData(orientation,fillWith,factor):
   """
   Generate poly-data and point-scalars
   """
   poly = vtk.vtkPolyData()
   pts = vtk.vtkPoints()
   coords=[ (0,0,0),(1,0,0),(1,1,0),(0,1,0)]
   for coord in coords:
      pts.InsertNextPoint(coord[0],coord[1],coord[2])
   poly.SetPoints(pts)

   # Vertices at all corners
   # two 1-point vertices and 1 2-point poly-vertex
   vertices = [[0],[1],[2,3]]
   verts = vtk.vtkCellArray()
   for vertex in vertices:
      InsertCell(verts,vertex,orientation)
   poly.SetVerts(verts)

   # Lines at all sides of the quad
   # two 2-point lines and 1 3-point line
   edges = [ (0,1),(1,2),(2,3,0) ]
   lines = vtk.vtkCellArray()
   for edge in edges:
      InsertCell(lines,edge,orientation)
   poly.SetLines(lines)

   # Fill with one quad, two triangles or a triangle-strip
   if fillWith=='quad':
      quad = (0,1,2,3)
      polys = vtk.vtkCellArray()
      InsertCell(polys,quad,orientation)
      poly.SetPolys(polys)
   elif fillWith=='triangles':
      triangles=[(0,1,3),(3,1,2)]
      strips = vtk.vtkCellArray()
      for triangle in triangles:
         InsertCell(strips,triangle,orientation)
      poly.SetStrips(strips)
   elif fillWith=='strip':
      strip=(0,1,3,2)
      strips = vtk.vtkCellArray()
      InsertCell(strips,strip,orientation)
      poly.SetStrips(strips)

   # Scalars for contouring
   values = [ 0.0, 0.5, 1.5, 1.0 ]
   array=vtk.vtkDoubleArray()
   for v in values:
      array.InsertNextValue(factor*v)
   poly.GetPointData().SetScalars(array)

   return poly
Exemple #3
0
def draw_lines(nodes, color):
    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)
    colors.SetName("Colors")
    cnt = 0
    noderange = 100
    mod = 1
    edges = nodes[0].getedges()
    points = vtk.vtkPoints()
    lines = vtk.vtkCellArray()
    nodecnt = 0

    while cnt < len(nodes):
        node = nodes[cnt]
        cnt += 1
        edges = node.getedges()
        for edge in edges:
            x0,y0,z0 = edge[0]
            x1,y1,z1 = edge[1]

            points.InsertNextPoint(edge[0])
            points.InsertNextPoint(edge[1])

            line = vtk.vtkLine()
            line.GetPointIds().SetId(0,nodecnt)
            line.GetPointIds().SetId(1,nodecnt+1)
            lines.InsertNextCell(line)
            nodecnt += 2
            colors.InsertNextTupleValue(color)

        if cnt % mod == 0:
            print "noderange", noderange, "cnt", cnt, "mod",mod
            # Create a polydata to store everything in
            linesPolyData = vtk.vtkPolyData()
            # Add the points to the dataset
            linesPolyData.SetPoints(points)
            # Add the lines to the dataset
            linesPolyData.SetLines(lines)
            linesPolyData.GetCellData().SetScalars(colors)

            mapper = vtk.vtkPolyDataMapper()
            mapper.SetInput(linesPolyData)
            actor = vtk.vtkActor()
            actor.SetMapper(mapper)
            renderer.AddActor(actor)
            points = vtk.vtkPoints()
            lines = vtk.vtkCellArray()
            nodecnt = 0    
            renderWindow.Render()
            camera = renderer.GetActiveCamera()
            camera.Azimuth(0.1)

    print "done!"
Exemple #4
0
def BlenderToPolyData(me):

	pcoords = vtk.vtkFloatArray()
	pcoords.SetNumberOfComponents(3)
	pcoords.SetNumberOfTuples(len(me.verts))
	for i in range(len(me.verts)):
		p0 = me.verts[i][0]
		p1 = me.verts[i][1]
		p2 = me.verts[i][2]
		pcoords.SetTuple3(i, p0, p1, p2)

	points = vtk.vtkPoints()
	points.SetData(pcoords)

	polys = vtk.vtkCellArray()
	lines = vtk.vtkCellArray()
	for face in me.faces:
		if len(face.v) == 4:
			polys.InsertNextCell(4)
			polys.InsertCellPoint(face.v[0].index)
			polys.InsertCellPoint(face.v[1].index)
			polys.InsertCellPoint(face.v[2].index)
			polys.InsertCellPoint(face.v[3].index)
		elif len(face.v) == 3:
			polys.InsertNextCell(3)
			polys.InsertCellPoint(face.v[0].index)
			polys.InsertCellPoint(face.v[1].index)
			polys.InsertCellPoint(face.v[2].index)
		elif len(face.v) == 2:
			lines.InsertNextCell(2)
			lines.InsertCellPoint(face.v[0].index)
			lines.InsertCellPoint(face.v[1].index)

	pdata =vtk.vtkPolyData()
	pdata.SetPoints(points)
	pdata.SetPolys(polys)
	pdata.SetLines(lines)

#------------------------------------------------------------------
# CODIGO INTRODUCIDO PARA PERMITIR LA INCLUSION DE LA             #
# INFORMACION DE LA TEXTURA EN EL POLYDATA GENERADO               #

	if me.hasFaceUV():
		pdata.GetPointData().SetTCoords(calc_coords(me))	# Se insertan las coordenadas en el polydata
#------------------------------------------------------------------

	pdata.Update()

	return pdata
Exemple #5
0
  def add_lines(self, points, lines, colors=(255, 0, 0)):
    line_collection = vtk.vtkCellArray()
    line_collection.Allocate(len(lines))
    for line in lines:
      line_collection.InsertNextCell(len(line), line)

    poly_data = vtk.vtkPolyData()
    poly_data.SetPoints(self._convert_points_array(points))
    poly_data.SetLines(line_collection)

    actor = self._actor_from_poly_data(poly_data)

    colors = np.asarray(colors)
    if colors.size == 3: # only one color given
      colors = colors.ravel()
      actor.GetProperty().SetColor(colors[0], colors[1], colors[2])
    elif colors.shape[0] == len(lines): # array of line colors
      colors = np.ascontiguousarray(
        colors.astype(np.uint8, subok=True, copy=False))
      colors_array = numpy_to_vtk(colors)
      colors_array.SetName("Colors")

      # to avoid the colors array going out of scope
      setattr(colors_array, '_np_color_array', colors)

      poly_data.GetCellData().SetScalars(colors_array)
    else: # array of vertex colors
      self._add_color_to_actor(actor, colors)

    return self._add_mesh_actor(actor)
def createPolyData(faces, vtList, verts, tcoords):

    points = vtk.vtkPoints()
    points.SetDataTypeToDouble()
    points.SetNumberOfPoints(len(vtList))

    tcoordArray = vtk.vtkDoubleArray()
    tcoordArray.SetName('tcoords')
    tcoordArray.SetNumberOfComponents(2)
    tcoordArray.SetNumberOfTuples(len(vtList))

    for i, vt in enumerate(vtList):
        vi, ti = vt
        xyz = verts[vi]
        uv = tcoords[ti]

        points.SetPoint(i, xyz)
        tcoordArray.SetTuple2(i, uv[0], uv[1])

    cells = vtk.vtkCellArray()

    for i, face in enumerate(faces):
        tri = vtk.vtkTriangle()
        tri.GetPointIds().SetId(0, face[0])
        tri.GetPointIds().SetId(1, face[1])
        tri.GetPointIds().SetId(2, face[2])
        cells.InsertNextCell(tri)

    polyData = vtk.vtkPolyData()
    polyData.SetPoints(points)
    polyData.SetPolys(cells)
    polyData.GetPointData().SetTCoords(tcoordArray)
    return polyData
Exemple #7
0
def vertices(indices):
    """
    Maps a numpy ndarray of shape (n,) to an vtkCellArray of vertex indices

    Args:
        indices (numpy.ndarray<int>): A numpy.ndarray of shape (n,) of indices that defines the n vertices

    Returns:
        vtk_vertices (vtk.vtkCellArray): VTK representation of the vertices
    """
    if not isinstance(indices, numpy.ndarray):
        raise Numpy2VtkFormatException(
            'vertices needs numpy array as input'
        )
    if len(indices.shape) != 1:
        raise Numpy2VtkFormatException(
            'vertices needs a one dimensional array as input, was {}-dimensional'.format(len(indices.shape))
        )
    if indices.dtype != numpy.int:
        raise Numpy2VtkFormatException(
            'vertices need to be numpy array of type numpy.int'
        )

    vtk_vertices = vtk.vtkCellArray()
    for v in indices:
        vtk_vertices.InsertNextCell(1)
        vtk_vertices.InsertCellPoint(v)
    return vtk_vertices
Exemple #8
0
def make_cylinderActor (r, x0, x1, rgb, opacity):
    points = vtk.vtkPoints()
    lines  = vtk.vtkCellArray()
    lines.InsertNextCell(2)
    # point 0
    points.InsertNextPoint(x0[0], x0[1], x0[2])
    lines.InsertCellPoint(0)
    # point 1
    points.InsertNextPoint(x1[0], x1[1], x1[2])
    lines.InsertCellPoint(1)

    cData = vtk.vtkPolyData()
    cData.SetPoints(points)
    cData.SetLines(lines)

    c = vtk.vtkTubeFilter()
    c.SetNumberOfSides(8)
    c.SetInput(cData)
    c.SetRadius(r)

    cMapper = vtk.vtkPolyDataMapper()
    cMapper.SetInput(c.GetOutput())

    cActor = vtk.vtkActor()
    cActor.SetMapper(cMapper)
    cActor.GetProperty().SetColor(rgb[0], rgb[1], rgb[2])
    cActor.GetProperty().SetOpacity(opacity)

    return cActor
Exemple #9
0
  def copyFirstNLines(self, sourcePolyData, lineCount):
    """make a polydata with only the first N polylines"""

    polyData = vtk.vtkPolyData()
    points = vtk.vtkPoints()
    polyData.SetPoints(points)

    lines = vtk.vtkCellArray()
    polyData.SetLines(lines)

    sourcePoints = sourcePolyData.GetPoints()
    sourceLines = sourcePolyData.GetLines()
    sourceIdList = vtk.vtkIdList()
    sourceLines.InitTraversal()
    while sourceLines.GetNextCell(sourceIdList):
        pointCount = sourceIdList.GetNumberOfIds()
        idList = vtk.vtkIdList()
        for idIndex in range(pointCount):
            sourceId = sourceIdList.GetId(idIndex)
            point = sourcePoints.GetPoint(sourceId)
            id = points.InsertNextPoint(point)
            idList.InsertNextId(id)
        lines.InsertNextCell(idList)
        if lines.GetNumberOfCells() > lineCount:
            break

    return polyData
Exemple #10
0
    def _update_vtk_objects(self):
        """When n is changed the thus the number of coordinates this function is needed
        to update the vtk objects with the new number of points."""
        # self._vtk_points.SetNumberOfPoints(len(self._points))
        # for i, c in enumerate(self._points):
        #     self._vtk_points.InsertPoint(i, c[0], c[1], c[2])
        self._vtk_points = _vtk.vtkPoints()
        for coordinates in self._points:
            self._vtk_points.InsertNextPoint(coordinates[0], coordinates[1], coordinates[2])

        self._vtk_polygons = _vtk.vtkCellArray()
        for polygon in self._polygons:
            vtk_polygon = _vtk.vtkPolygon()
            vtk_polygon.GetPointIds().SetNumberOfIds(3)
            for local_index, global_index in enumerate(polygon):
                vtk_polygon.GetPointIds().SetId(local_index, global_index)
            self._vtk_polygons.InsertNextCell(vtk_polygon)

        self._vtk_poly_data.SetPoints(self._vtk_points)
        self._vtk_poly_data.SetPolys(self._vtk_polygons)

        self._vtk_scalars = _vtk.vtkFloatArray()
        self._vtk_scalars.SetNumberOfValues(self._vtk_poly_data.GetPoints().GetNumberOfPoints())
        for i in range(self._vtk_scalars.GetNumberOfTuples()):
            self._vtk_scalars.SetValue(i, 0.)

        self._vtk_poly_data.GetPointData().SetScalars(self._vtk_scalars)
        self._vtk_poly_data.Modified()
 def createCurtain( self, **args ):
     trajectory_points = self.getTrajectoryPoints( **args )
     extent =  self.input().GetExtent() 
     spacing =  self.input().GetSpacing() 
     nStrips = extent[5] - extent[4] 
     zmax = spacing[2] * nStrips
     z_inc = zmax / nStrips
     polydata = vtk.vtkPolyData()
     stripArray = vtk.vtkCellArray()
     stripData = [ vtk.vtkIdList() for ix in range(nStrips) ] 
     points = vtk.vtkPoints() 
     for iPt in range( trajectory_points.GetNumberOfPoints() ):
         pt_coords = trajectory_points.GetPoint( iPt )
         z = 0.0
         for iLevel in range( nStrips ):
             vtkId = points.InsertNextPoint( pt_coords[0], pt_coords[1], z )
             sd = stripData[ iLevel ]
             sd.InsertNextId( vtkId )               
             sd.InsertNextId( vtkId+1 )
             z = z + z_inc 
         points.InsertNextPoint( pt_coords[0], pt_coords[1], z )
                    
     for strip in stripData:
         stripArray.InsertNextCell(strip)
         
     polydata.SetPoints( points )
     polydata.SetStrips( stripArray )
     return polydata
Exemple #12
0
def draw_lines(nodes, color):
    points = vtk.vtkPoints()
    lines = vtk.vtkCellArray()
    nodecnt = 0
    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)
    colors.SetName("Colors")
    
    for node in nodes: 
        edges = node.getedges()
       
        for edge in edges:
            x0,y0,z0 = edge[0]
            x1,y1,z1 = edge[1]

            points.InsertNextPoint(edge[0])
            points.InsertNextPoint(edge[1])

            line = vtk.vtkLine()
            line.GetPointIds().SetId(0,nodecnt)
            line.GetPointIds().SetId(1,nodecnt+1)
            lines.InsertNextCell(line)
            nodecnt += 2
            colors.InsertNextTupleValue(color)
            
    # Create a polydata to store everything in
    linesPolyData = vtk.vtkPolyData()
    # Add the points to the dataset
    linesPolyData.SetPoints(points)
    # Add the lines to the dataset
    linesPolyData.SetLines(lines)
    linesPolyData.GetCellData().SetScalars(colors)
    return linesPolyData
Exemple #13
0
def latitude_create(
                arg_lat,
		arg_projection):

	if arg_projection == 'linear' :
		n_polypoints=2
        	polygonpoints=vtk.vtkPoints()
        	polygonpoints.SetNumberOfPoints(n_polypoints)
		polygonpoints.InsertPoint(0,-180,arg_lat,0)
		polygonpoints.InsertPoint(1,540,arg_lat,0)
	else:
        	n_polypoints=360
        	polygonpoints=vtk.vtkPoints()
        	polygonpoints.SetNumberOfPoints(n_polypoints)
        	deg2rad=numpy.pi/180.
        	for n in range(n_polypoints) :
                	theta=2*numpy.pi*n/(n_polypoints-1)
                	x=numpy.cos(arg_lat*deg2rad)*numpy.cos(theta)
                	y=numpy.cos(arg_lat*deg2rad)*numpy.sin(theta)
                	z=numpy.sin(arg_lat*deg2rad)
                	polygonpoints.InsertPoint(n,x,y,z)

        polygonlines=vtk.vtkCellArray()
        polygonlines.InsertNextCell(n_polypoints)
        for n in range(n_polypoints) :
                polygonlines.InsertCellPoint(n)
        latpolydata=vtk.vtkPolyData()
        latpolydata.SetPoints(polygonpoints)
        latpolydata.SetLines(polygonlines)

        return latpolydata
 def setEdgesPolydata(self, vd):
     self.edges = []
     self.edges = vd.getEdgesGenerators()
     self.epts = vtk.vtkPoints()
     nid = 0
     lines=vtk.vtkCellArray()
     for e in self.edges:
         p1 = self.scale*e[0]
         p2 = self.scale*e[1] 
         self.epts.InsertNextPoint( p1.x, p1.y, p1.z)
         self.epts.InsertNextPoint( p2.x, p2.y, p2.z)
         line = vtk.vtkLine()
         line.GetPointIds().SetId(0,nid)
         line.GetPointIds().SetId(1,nid+1)
         nid = nid+2
         lines.InsertNextCell(line)
     
     linePolyData = vtk.vtkPolyData()
     linePolyData.SetPoints(self.epts)
     linePolyData.SetLines(lines)
     
     mapper = vtk.vtkPolyDataMapper()
     mapper.SetInput(linePolyData)
     
     self.edge_actor = vtk.vtkActor()
     self.edge_actor.SetMapper(mapper)
     self.edge_actor.GetProperty().SetColor( camvtk.cyan )
     myscreen.addActor( self.edge_actor )
     myscreen.render() 
Exemple #15
0
def CreatePolyData( pts, faces ):
    """
    Creates vtkPolyData from vertices and faces
    
    pts numpy.array: Nx3 array of vertices
    faces numpy.array: Mx3 array of faces

    Return vtkPolyData
    """
    (nv,mv) = pts.shape
    (nf,mf) = faces.shape
    cells = vtk.vtkCellArray()
    for j in range(nf):
        cell = vtk.vtkTriangle()
        cell.GetPointIds().SetNumberOfIds(3)
        cell.GetPointIds().SetId( 0, faces[j,0] )
        cell.GetPointIds().SetId( 1, faces[j,1] )
        cell.GetPointIds().SetId( 2, faces[j,2] )
        cells.InsertNextCell( cell )
    
    
    points = vtk.vtkPoints()
    points.SetNumberOfPoints(nv)
    for j in range(nv):
        points.SetPoint( j, pts[j,0], pts[j,1], pts[j,2] )
        
    new_mesh = vtk.vtkPolyData()
    new_mesh.SetPoints( points )
    new_mesh.SetPolys( cells )
    new_mesh.BuildCells()	
    
    return new_mesh
Exemple #16
0
def VTKPoints2PolyData( pts ):
    """
    Transforms numpy point array into  vtkPolyData
    
    pts numpy.array: Nx3 array of vertices

    Return vtkPolyData
    """
    (nv,mv) = pts.shape
    
    
    vertices = vtk.vtkCellArray()
    points = vtk.vtkPoints()
    points.SetNumberOfPoints(nv)
    for j in range(nv):
        points.SetPoint( j, pts[j,0], pts[j,1], pts[j,2] )
        vertices.InsertNextCell(1)
        vertices.InsertCellPoint(j)    
 
    # Create a polydata object
    mesh = vtk.vtkPolyData()
 
    # Set the points and vertices we created as the geometry and topology of the polydata
    mesh.SetPoints(points)
    mesh.SetVerts(vertices)

    mesh.BuildCells()	
    
    return mesh
Exemple #17
0
    def __init__(self, pointlist=[]):
        points = vtk.vtkPoints()
        cellArr = vtk.vtkCellArray()
        Colors = vtk.vtkUnsignedCharArray()
        Colors.SetNumberOfComponents(3)
        Colors.SetName("Colors")
        
        n=0
        for p in pointlist:
            vert = vtk.vtkVertex()
            points.InsertNextPoint(p.x, p.y, p.z)
            vert.GetPointIds().SetId(0,n)
            cellArr.InsertNextCell( vert )
            col = clColor(p.cc())
            Colors.InsertNextTuple3( float(255)*col[0], float(255)*col[1], float(255)*col[2] )
            n=n+1
            
        polydata= vtk.vtkPolyData()
        polydata.SetPoints(points)
        polydata.SetVerts( cellArr )
        polydata.GetPointData().SetScalars(Colors)

        polydata.Modified()
        polydata.Update()
        self.src=polydata
        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInput(self.src)
        self.SetMapper(self.mapper)
Exemple #18
0
 def get_cell(self, name):
     try:
         return getattr(self, 'cell_'+name)
     except AttributeError:
         cellarray = vtk.vtkCellArray()
         setattr(self, 'cell_'+name, cellarray)
         return cellarray
Exemple #19
0
    def asVtkUnstructuredGrid(self):
        '''
        Return object as a vtk.vtkUnstructuredMesh instance.

        .. note:: This method uses the compiled vtk module (which is a wrapper atop the c++ VTK library) -- in contrast to :obj:`UnstructuredMesh.getVTKRepresentation`, which uses the pyvtk module (python-only implementation of VTK i/o supporting only VTK File Format version 2).
        '''
        import vtk
        # vertices
        pts=vtk.vtkPoints()
        for ip in range(self.getNumberOfVertices()): pts.InsertNextPoint(self.getVertex(ip).getCoordinates())
        # cells
        cells,cellTypes=vtk.vtkCellArray(),[]
        for ic in range(self.getNumberOfCells()):
            c=self.getCell(ic)
            cgt=c.getGeometryType()
            cellGeomTypeMap={
                CellGeometryType.CGT_TRIANGLE_1: (vtk.vtkTriangle,vtk.VTK_TRIANGLE),
                CellGeometryType.CGT_QUAD:       (vtk.vtkQuad,vtk.VTK_QUAD),
                CellGeometryType.CGT_TETRA:      (vtk.vtkTetra,vtk.VTK_TETRA),
                CellGeometryType.CGT_HEXAHEDRON: (vtk.vtkHexahedron,vtk.VTK_HEXAHEDRON),
                CellGeometryType.CGT_TRIANGLE_2: (vtk.vtkQuadraticTriangle,vtk.VTK_QUADRATIC_TRIANGLE)
            }
            c2klass,c2type=cellGeomTypeMap[cgt] # instantiate the VTK cell with the correct type
            c2=c2klass()
            verts=c.getVertices() # those should be all instances of Vertex...? Hopefully so.
            for i,v in enumerate(verts): c2.GetPointIds().SetId(i,v.getNumber())
            cells.InsertNextCell(c2)
            cellTypes.append(c2type)
        ret=vtk.vtkUnstructuredGrid()
        ret.SetPoints(pts)
        ret.SetCells(cellTypes,cells)
        return ret
Exemple #20
0
    def __init__(self,center=(0,0,0) , radius=1, color=(0,1,1), resolution=50 ):   
        """ create circle """
        lines =vtk.vtkCellArray()
        id = 0
        points = vtk.vtkPoints()
        for n in xrange(0,resolution):
            line = vtk.vtkLine()
            angle1 = (float(n)/(float(resolution)))*2*math.pi
            angle2 = (float(n+1)/(float(resolution)))*2*math.pi
            p1 = (center[0]+radius*math.cos(angle1), center[1]+radius*math.sin(angle1), center[2])
            p2 = (center[0]+radius*math.cos(angle2), center[1]+radius*math.sin(angle2), center[2])
            points.InsertNextPoint(p1)
            points.InsertNextPoint(p2)
            line.GetPointIds().SetId(0,id)
            id=id+1
            line.GetPointIds().SetId(1,id)
            id=id+1
            lines.InsertNextCell(line)
            

        self.pdata = vtk.vtkPolyData()
        self.pdata.SetPoints(points)
        self.pdata.SetLines(lines)
        
        self.mapper = vtk.vtkPolyDataMapper()
        self.mapper.SetInput(self.pdata)
        self.SetMapper(self.mapper)
        self.SetColor(color)
Exemple #21
0
def skippoints(polydata,nskippoints):
    """Generate a single cell line from points in idlist."""

    # derive number of nodes
    numberofnodes = polydata.GetNumberOfPoints() - nskippoints

    # define points and line
    points = vtk.vtkPoints()
    polyline = vtk.vtkPolyLine()
    polyline.GetPointIds().SetNumberOfIds(numberofnodes)

    # assign id and x,y,z coordinates
    for i in range(nskippoints,polydata.GetNumberOfPoints()):
        pointid = i - nskippoints
        polyline.GetPointIds().SetId(pointid,pointid)
        point = polydata.GetPoint(i)
        points.InsertNextPoint(point)


    # define cell
    cells = vtk.vtkCellArray()
    cells.InsertNextCell(polyline)

    # add to polydata
    polyout = vtk.vtkPolyData()
    polyout.SetPoints(points)
    polyout.SetLines(cells)

    return polyout
    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.ren.SetBackground(0.1, 0.2, 0.4)
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()
 
        # Create source
        # Create five points. 
        origin = [0.0, 0.0, 0.0]
        p0 = [1.0, 0.0, 0.0]
        p1 = [0.0, 1.0, 0.0]
        p2 = [0.0, 1.0, 2.0]
        p3 = [1.0, 2.0, 3.0]
        p4 = [1.0, 2.0, 8.0]
         
        # Create a vtkPoints object and store the points in it
        points = vtk.vtkPoints()
        points.InsertNextPoint(origin)
        points.InsertNextPoint(p0)
        points.InsertNextPoint(p1)
        points.InsertNextPoint(p2)
        points.InsertNextPoint(p3)
        points.InsertNextPoint(p4)
         
        # Create a cell array to store the lines in and add the lines to it
        lines = vtk.vtkCellArray()
         
        for i in range(4):
          line = vtk.vtkLine()
          line.GetPointIds().SetId(0,i)
          line.GetPointIds().SetId(1,i+1)
          lines.InsertNextCell(line)
         
        # Create a polydata to store everything in
        linesPolyData = vtk.vtkPolyData()
         
        # Add the points to the dataset
        linesPolyData.SetPoints(points)
         
        # Add the lines to the dataset
        linesPolyData.SetLines(lines)
         
        # Setup actor and mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInput(linesPolyData)
         
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)
 
        self.ren.AddActor(actor)
        self.ren.ResetCamera()

        self._initialized = False
    def __init__(self, dataShape, interactor):
        self.dataShape = dataShape
        self.planes = []
        self.coordinate = [0,0,0]
        self.lastChangedAxis = -1
        for i in range(3):
            p = vtkImplicitPlaneRepresentation()
            p.SetPlaceFactor(1.0)
            p.OutsideBoundsOn()
            p.ScaleEnabledOff()
            p.SetOrigin(0.25,0.25,0.25)
            p.PlaceWidget([0.1,dataShape[0],0.1,dataShape[1],0.1,dataShape[2]])

            args = [0, 0, 0]
            args[i] = 1
            p.SetNormal(*args)
            p.GetSelectedPlaneProperty().SetColor(*args)
            p.GetEdgesProperty().SetColor(*args) #bug in VTK

            p.GetPlaneProperty().SetOpacity(0.001)
            #do not draw outline
            p.GetOutlineProperty().SetColor(0,0,0)
            p.GetOutlineProperty().SetOpacity(0.0)
            #do not draw normal
            p.GetSelectedNormalProperty().SetOpacity(0.0)
            p.GetNormalProperty().SetOpacity(0.0)
            p.OutlineTranslationOff()
            p.TubingOff()
            
            self.cross = vtkPolyData()
            points = vtkPoints()
            polys = vtkCellArray()
            points.SetNumberOfPoints(6)
            for i in range(3):
                polys.InsertNextCell(2)
                polys.InsertCellPoint(2*i); polys.InsertCellPoint(2*i+1)
            self.cross.SetPoints(points)
            self.cross.SetLines(polys)
            
            pw = vtkImplicitPlaneWidget2()
            pw.SetRepresentation(p)
            pw.SetInteractor(interactor)
            pw.AddObserver("InteractionEvent", self.__PlanePositionCallback)
            
            self.planes.append(pw)
            
        tubes = vtkTubeFilter()
        tubes.SetNumberOfSides(16)
        tubes.SetInput(self.cross)
        tubes.SetRadius(1.0)
        
        crossMapper = vtkPolyDataMapper()
        crossMapper.SetInput(self.cross)
        crossActor = vtkActor()
        crossActor.SetMapper(crossMapper)
        crossActor.GetProperty().SetColor(0,0,0)
        self.AddPart(crossActor)
        
        #initially invoke the event!
        self.InvokeEvent("CoordinatesEvent")
def ExtractSingleLine(centerlines,id):
   cell = vtk.vtkGenericCell()
   centerlines.GetCell(id,cell) 

   line = vtk.vtkPolyData()
   points = vtk.vtkPoints()
   cellArray = vtk.vtkCellArray()
   cellArray.InsertNextCell(cell.GetNumberOfPoints())

   radiusArray = vtk.vtkDoubleArray()
   radiusArray.SetName(radiusArrayName)
   radiusArray.SetNumberOfComponents(1)
   radiusArray.SetNumberOfTuples(cell.GetNumberOfPoints())
   radiusArray.FillComponent(0,0.0)

   for i in range(cell.GetNumberOfPoints()):
      point = [0.0,0.0,0.0]
      point = cell.GetPoints().GetPoint(i)

      points.InsertNextPoint(point)
      cellArray.InsertCellPoint(i)
      radius = centerlines.GetPointData().GetArray(radiusArrayName).GetTuple1(cell.GetPointId(i))
      radiusArray.SetTuple1(i,radius)

   line.SetPoints(points)   
   line.SetLines(cellArray)
   line.GetPointData().AddArray(radiusArray)

   return line 
Exemple #25
0
	def makeEdgeVTKObject(mesh,model):
		"""
		Make and return a edge based VTK object for a simpeg mesh and model.

		Input:
		:param mesh, SimPEG TensorMesh object - mesh to be transfer to VTK
		:param model, dictionary of numpy.array - Name('s) and array('s).
			Property array must be order hstack(Ex,Ey,Ez)

		Output:
        :rtype: vtkUnstructuredGrid object
        :return: vtkObj
		"""

		## Convert simpeg mesh to VTK properties
		# Convert mesh nodes to vtkPoints
		vtkPts = vtk.vtkPoints()
		vtkPts.SetData(npsup.numpy_to_vtk(mesh.gridN,deep=1))

		# Define the face "cells"
		# Using VTK_QUAD cell for faces (see VTK file format)
		nodeMat = mesh.r(np.arange(mesh.nN,dtype='int64'),'N','N','M')
		def edgeR(mat,length):
			return mat.T.reshape((length,1))
		# First direction
		nTEx = np.prod(mesh.nEx)
		ExCellBlock = np.hstack([ 2*np.ones((nTEx,1),dtype='int64'),edgeR(nodeMat[:-1,:,:],nTEx),edgeR(nodeMat[1:,:,:],nTEx)])
		# Second direction
		if mesh.dim >= 2:
			nTEy = np.prod(mesh.nEy)
			EyCellBlock = np.hstack([ 2*np.ones((nTEy,1),dtype='int64'),edgeR(nodeMat[:,:-1,:],nTEy),edgeR(nodeMat[:,1:,:],nTEy)])
		# Third direction
		if mesh.dim == 3:
			nTEz = np.prod(mesh.nEz)
			EzCellBlock = np.hstack([ 2*np.ones((nTEz,1),dtype='int64'),edgeR(nodeMat[:,:,:-1],nTEz),edgeR(nodeMat[:,:,1:],nTEz)])
		# Cells -cell array
		ECellArr = vtk.vtkCellArray()
		ECellArr.SetNumberOfCells(mesh.nE)
		ECellArr.SetCells(mesh.nE,npsup.numpy_to_vtkIdTypeArray(np.vstack([ExCellBlock,EyCellBlock,EzCellBlock]),deep=1))
		# Cell type
		ECellType = npsup.numpy_to_vtk(vtk.VTK_LINE*np.ones(mesh.nE,dtype='uint8'),deep=1)
		# Cell location
		ECellLoc = npsup.numpy_to_vtkIdTypeArray(np.arange(0,mesh.nE*3,3,dtype='int64'),deep=1)

		## Make the object
		vtkObj = vtk.vtkUnstructuredGrid()
		# Set the objects properties
		vtkObj.SetPoints(vtkPts)
		vtkObj.SetCells(ECellType,ECellLoc,ECellArr)

		# Assign the model('s) to the object
		for item in model.iteritems():
			# Convert numpy array
			vtkDoubleArr = npsup.numpy_to_vtk(item[1],deep=1)
			vtkDoubleArr.SetName(item[0])
			vtkObj.GetCellData().AddArray(vtkDoubleArr)

		vtkObj.GetCellData().SetActiveScalars(model.keys()[0])
		vtkObj.Update()
		return vtkObj
Exemple #26
0
def polygons(indices):
    """
    Maps a numpy ndarray to an vtkCellArray of vtkPolygons

    Args:
        indices (numpy.ndarray<int>): A numpy.ndarray of shape (n,m) of indices that define n polygons with m points each

    Returns:
        vtk_polygons (vtk.vtkCellArray): VTK representation of the polygons
    """
    if not isinstance(indices, numpy.ndarray):
        raise Numpy2VtkFormatException(
            'polygons needs numpy array as input'
        )
    if len(indices.shape) != 2:
        raise Numpy2VtkFormatException(
            'polygons needs a nxm ndarray as input'
        )
    if indices.dtype != numpy.int:
        raise Numpy2VtkFormatException(
            'polygons needs to be numpy array of type numpy.int'
        )

    number_of_polygons = indices.shape[0]
    poly_shape = indices.shape[1]
    vtk_polygons = vtk.vtkCellArray()
    for j in range(0, number_of_polygons):
        polygon = vtk.vtkPolygon()
        polygon.GetPointIds().SetNumberOfIds(poly_shape)
        for i in range(0, poly_shape):
            polygon.GetPointIds().SetId(i, indices[j, i])
        vtk_polygons.InsertNextCell(polygon)
    return vtk_polygons
def SaveParentArtery(centerlines):
   numberOfCells = centerlines.GetNumberOfCells()

   cell0 = centerlines.GetCell(0)
   numberOfArteryPoints = centerlines.GetNumberOfPoints()-cell0.GetNumberOfPoints()
  
   artery = vtk.vtkPolyData()
   arteryPoints = vtk.vtkPoints()
   arteryCellArray = vtk.vtkCellArray()

   radiusArray = vtk.vtkDoubleArray()
   radiusArray.SetName(radiusArrayName)
   radiusArray.SetNumberOfComponents(1)
   radiusArray.SetNumberOfTuples(numberOfArteryPoints)
   radiusArray.FillComponent(0,0.0)

   count = 0
   for i in range(1,numberOfCells): # cell0 is the one that goes to the aneurysm dome
      cell = vtk.vtkGenericCell()
      centerlines.GetCell(i,cell)
   
      arteryCellArray.InsertNextCell(cell.GetNumberOfPoints())
   
      for j in range(cell.GetNumberOfPoints()):
         arteryPoints.InsertNextPoint(cell.GetPoints().GetPoint(j))
         radiusArray.SetTuple1(count,centerlines.GetPointData().GetArray(radiusArrayName).GetTuple1(cell.GetPointId(j)))
         arteryCellArray.InsertCellPoint(count)
         count+=1
         
   artery.SetPoints(arteryPoints)
   artery.SetLines(arteryCellArray)
   artery.GetPointData().AddArray(radiusArray)
   return artery 
def displayClickPoints(clickPoints):
	
	points = vtk.vtkPoints()
	lines = vtk.vtkCellArray()
	polygon = vtk.vtkPolyData()
	polygonMapper = vtk.vtkPolyDataMapper()
	polygonActor = vtk.vtkActor()
		
	points.SetNumberOfPoints(4)
	points.SetPoint(0, 0.0, -1.0, 0.0)
	points.SetPoint(1, -0.7, -0.5, 0.0)
	points.SetPoint(2,   0.7,  0.5, 0.0)
	points.SetPoint(3, 0.0,  -1.0, 0.0)

		
	lines.InsertNextCell(4)
	lines.InsertCellPoint(0)
	lines.InsertCellPoint(1)
	lines.InsertCellPoint(2)
	lines.InsertCellPoint(3)
		
	polygon.SetPoints(points)
	polygon.SetLines(lines)
		
	polygonMapper.SetInputConnection(polygon.GetProducerPort())
	polygonActor.SetMapper(polygonMapper)	
	
	mpv_renderer[1].ResetCamera()
	mpv_renderer[1].AddActor(polygonActor)
	rw.Render()
Exemple #29
0
def edges(indices):
    """
    Maps a numpy ndarray to an vtkCellArray of vtkLines

    Args:
        indices (numpy.ndarray<int>): A numpy.ndarray of shape (n,2) of indices that define n edges

    Returns:
        vtk_lines (vtk.vtkCellArray): VTK representation of the edges
    """
    if not isinstance(indices, numpy.ndarray):
        raise Numpy2VtkFormatException(
            'lines needs numpy array as input'
        )
    if len(indices.shape) != 2 or indices.shape[1] != 2:
        raise Numpy2VtkFormatException(
            'lines needs a nx2 ndarray as input'
        )
    if indices.dtype != numpy.int:
        raise Numpy2VtkFormatException(
            'lines needs to be numpy array of type numpy.int'
        )
    vtk_lines = vtk.vtkCellArray()
    for e in indices:
        line = vtk.vtkLine()
        line.GetPointIds().SetId(0, e[0])
        line.GetPointIds().SetId(1, e[1])
        vtk_lines.InsertNextCell(line)
    return vtk_lines
def findPointsInCell(points,
                     cell,
                     verbose=1):

    ugrid_cell = vtk.vtkUnstructuredGrid()
    ugrid_cell.SetPoints(cell.GetPoints())
    cell = vtk.vtkHexahedron()
    for k_point in xrange(8): cell.GetPointIds().SetId(k_point, k_point)
    cell_array_cell = vtk.vtkCellArray()
    cell_array_cell.InsertNextCell(cell)
    ugrid_cell.SetCells(vtk.VTK_HEXAHEDRON, cell_array_cell)

    geometry_filter = vtk.vtkGeometryFilter()
    geometry_filter.SetInputData(ugrid_cell)
    geometry_filter.Update()
    cell_boundary = geometry_filter.GetOutput()

    pdata_points = vtk.vtkPolyData()
    pdata_points.SetPoints(points)

    enclosed_points_filter = vtk.vtkSelectEnclosedPoints()
    enclosed_points_filter.SetSurfaceData(cell_boundary)
    enclosed_points_filter.SetInputData(pdata_points)
    enclosed_points_filter.Update()

    points_in_cell = [k_point for k_point in xrange(points.GetNumberOfPoints()) if enclosed_points_filter.GetOutput().GetPointData().GetArray('SelectedPoints').GetTuple(k_point)[0]]
    return points_in_cell
Exemple #31
0
def CreateOutline9076(color = (255, 99, 71), depth = 80.0, resolution=10):
  """
  Create outline for the 9076 probe. The outline is contained in the XZ-plane
  """

  # Avoid multiple generations
  if CreateOutline9076.output is not None and  CreateOutline9076.depth == depth:
    print("reused outline")
    return CreateOutline9076.output

  nElements = 144
  pitch = 0.2101
  roc = 50.006
  height = 5.0

  azR = roc
  azArcLength = pitch * (nElements - 1.0)
  azSegment = azArcLength / azR
  dAz = azSegment / (nElements - 1.0)

  az = dAz * (np.r_[0:nElements] - 0.5*(nElements - 1.0))

  az0 = az[0] - 0.5*dAz
  azN = az[nElements-1] + 0.5*dAz

  # Create first arc
  arc0 = vtk.vtkArcSource()
  arc0.SetCenter(0, 0, -azR)
  arc0.SetPoint1(azR*np.sin(az0), 0, azR*np.cos(az0) - azR)
  arc0.SetPoint2(azR*np.sin(azN), 0, azR*np.cos(azN) - azR)
  arc0.SetResolution( resolution )
  arc0.Update()

  arcData0 = arc0.GetOutput()

  # Create second arc
  arc1 = vtk.vtkArcSource()
  arc1.SetCenter(0, 0, -azR)
  arc1.SetPoint1((azR+depth)*np.sin(azN), 0, (azR+depth)*np.cos(azN) - azR)
  arc1.SetPoint2((azR+depth)*np.sin(az0), 0, (azR+depth)*np.cos(az0) - azR)
  arc1.SetResolution( resolution )
  arc1.Update()

  arcData1 = arc1.GetOutput()

  # Resulting poly data
  linesPolyData = vtk.vtkPolyData()
  lines = vtk.vtkCellArray()
  points = vtk.vtkPoints()

  # Iterate through points and and create new lines
  arcData0.GetLines().InitTraversal()
  idList = vtk.vtkIdList()
  while arcData0.GetLines().GetNextCell(idList):
    pointId = idList.GetId(0)
    points.InsertNextPoint(arcData0.GetPoint(pointId))
    for i in range(1, idList.GetNumberOfIds()):
      pointId = idList.GetId(i)
      points.InsertNextPoint(arcData0.GetPoint(pointId))
      line = vtk.vtkLine()
      line.GetPointIds().SetId(0,i-1)
      line.GetPointIds().SetId(1,i) # last i value is 10=resolution
      lines.InsertNextCell(line)

  # i = resolution
  arcData1.GetLines().InitTraversal()
  idList = vtk.vtkIdList()
  while arcData1.GetLines().GetNextCell(idList):
    pointId = idList.GetId(0)
    points.InsertNextPoint(arcData1.GetPoint(pointId))
    # Line from 1st arc to second arc
    line = vtk.vtkLine()
    line.GetPointIds().SetId(0,i)
    j = 0
    line.GetPointIds().SetId(1, i+1+j)
    lines.InsertNextCell(line)
    for j in range(1, idList.GetNumberOfIds()):
      pointId = idList.GetId(j)
      points.InsertNextPoint(arcData1.GetPoint(pointId))
      line = vtk.vtkLine()
      line.GetPointIds().SetId(0,i+j-1+1)
      line.GetPointIds().SetId(1,i+j+1)
      lines.InsertNextCell(line)

  # Insert one extra line joining the two arcs
  line = vtk.vtkLine()
  line.GetPointIds().SetId(0,i+j)
  line.GetPointIds().SetId(1,0)
  lines.InsertNextCell(line)

  linesPolyData.SetPoints(points)
  linesPolyData.SetLines(lines)

  # Create polyline(s) from line segments. There will be
  # two due to the the ordering
  cutStrips = vtk.vtkStripper()
  cutStrips.SetInputData(linesPolyData)
  cutStrips.Update()

  # Transform points forward such arcs have center in (0,0,0)
  transform = vtk.vtkTransform()
  transform.Translate(0.0, 0.0, roc)
  transform.Update()

  transformPolyDataFilter = vtk.vtkTransformPolyDataFilter()
  transformPolyDataFilter.SetInputConnection(cutStrips.GetOutputPort())
  transformPolyDataFilter.SetTransform(transform)
  transformPolyDataFilter.Update()
  outline = transformPolyDataFilter.GetOutput()

  # Color the lines
  colors = vtk.vtkUnsignedCharArray()
  colors.SetNumberOfComponents(3)
  for i in range(outline.GetNumberOfCells()):
    colors.InsertNextTypedTuple(color)

  outline.GetCellData().SetScalars(colors)
  CreateOutline9076.depth = depth
  CreateOutline9076.output = outline
  return CreateOutline9076.output
Exemple #32
0
    def _read_rays(self, hplfile):
        '''
        ASSUMPTION - _read_header() has been called and the file handle is pointing
        to the correct spot in the file.
        Read the sequences of LiDAR beam data. These always start after the header on
        line 18.
        There are 'No. of rays in file' sections. 
        These have 1 initial line with:
        <time> <azimuth> <elevation> <pitch> <roll>
        Followed by 'Number of gates' lines of
        <gate ID> <doppler> <intensity> <beta>
        '''
        # a first pass would be to just grab the <azimuth> <elevation> and calculate
        # an x,y,z triple with
        # r = gate_ID * 'Range gate length (m)'
        # x = r*sin(elevation)*cos(azimuth)
        # y = r*sin(elevation)*sin(azimuth)
        # z = r*cos(elevation)

        gate_length = self.header['Range gate length (m)']
        num_gates = self.header['Number of gates']

        # these are locals because they get added to self.scan
        pts = vtk.vtkPoints()
        vts = vtk.vtkCellArray()

        dopplerScalars = vtk.vtkFloatArray()
        dopplerScalars.SetName('doppler')
        dopplerScalars.SetNumberOfComponents(1)

        intensityScalars = vtk.vtkFloatArray()
        intensityScalars.SetName('intensity')
        intensityScalars.SetNumberOfComponents(1)

        betaScalars = vtk.vtkFloatArray()
        betaScalars.SetName('beta')
        betaScalars.SetNumberOfComponents(1)

        gateIDScalars = vtk.vtkIntArray()
        gateIDScalars.SetName('gateID')
        gateIDScalars.SetNumberOfComponents(1)

        beamIDScalars = vtk.vtkIntArray()
        beamIDScalars.SetName('beamID')
        beamIDScalars.SetNumberOfComponents(1)

        azimuthScalars = vtk.vtkFloatArray()
        azimuthScalars.SetName('azimuth')
        azimuthScalars.SetNumberOfComponents(1)

        elevationScalars = vtk.vtkFloatArray()
        elevationScalars.SetName('elevation')
        elevationScalars.SetNumberOfComponents(1)

        if self.pitchAndRoll:
            pitchScalars = vtk.vtkFloatArray()
            pitchScalars.SetName('pitch')
            pitchScalars.SetNumberOfComponents(1)

            rollScalars = vtk.vtkFloatArray()
            rollScalars.SetName('roll')
            rollScalars.SetNumberOfComponents(1)

        beamID = 0

        # outer while is each beam
        while True:
            beam = hplfile.readline().strip()
            if not beam: break

            # beam header line
            time, azimuth, elevation, pitch, roll = [
                float(x) for x in beam.split()
            ]
            razimuth, relevation = radians(azimuth), radians(elevation)
            rpitch, rroll = radians(pitch), radians(roll)

            # convert elevation to inclination
            inclination = pi / 2 - relevation
            # gates along ray
            for g in range(num_gates):
                gate_ID, doppler, intensity, beta = hplfile.readline().strip(
                ).split()

                gateIDScalars.InsertNextValue(int(gate_ID))
                dopplerScalars.InsertNextValue(float(doppler))
                intensityScalars.InsertNextValue(float(intensity))
                betaScalars.InsertNextValue(float(beta))
                beamIDScalars.InsertNextValue(beamID)
                azimuthScalars.InsertNextValue(azimuth)
                elevationScalars.InsertNextValue(elevation)
                if self.pitchAndRoll:
                    pitchScalars.InsertNextValue(pitch)
                    rollScalars.InsertNextValue(roll)
                # this behaves as:
                # azimuth 0 is N and increases CW
                # elevation 0 is vertically straight up and increases towards ground
                # but what I want is
                # elevation 0 is horizontally and increases to 90 being straight up.
                # IIUC wikipedia says this is the "horizontal" or "topocentric" coordinate
                # system in the family of celestial coordiantes.

                r = (int(gate_ID) + 1) * gate_length
                y = r * sin(inclination) * cos(razimuth)
                x = r * sin(inclination) * sin(razimuth)
                z = r * cos(inclination)

                if self.pitchAndRoll:
                    # blech, hand-transforms
                    pitchedy = y * cos(rpitch) - z * sin(rpitch)
                    pitchedz = y * sin(rpitch) + z * cos(rpitch)
                    y = pitchedy
                    z = pitchedz

                    rolledx = x * cos(rroll) + z * sin(rroll)
                    rolledz = -x * sin(rroll) + z * cos(rroll)
                    x = rolledx
                    z = rolledz

                pts.InsertNextPoint([x, y, z])

            beamID += 1
            # could apply pitch and roll here, since they are beam-wise.
            # pitch is absolute pitch around East-West axis (X)
            # > 0 means N tilted above S, so azimuth (-90,90) tilt up
            #   and azimuth(90, -90) tilt down
            # roll is absolute pitch around N-S axis (Y)
            # >0 means west tilted above E, so azimuth (180,0) tilt up
            #    and azimuth (0,180) tilt down.

            # for the life of me, not sure how to do this through VTK
            # VTK transforms are meant to act as pipeline filters, but
            # this is in the modeling stage...
            # hand distributing the matrix multiplication gives

        self.scan.SetPoints(pts)
        self.scan.GetPointData().AddArray(gateIDScalars)
        self.scan.GetPointData().AddArray(dopplerScalars)
        self.scan.GetPointData().AddArray(intensityScalars)
        self.scan.GetPointData().AddArray(betaScalars)
        self.scan.GetPointData().AddArray(beamIDScalars)
        self.scan.GetPointData().AddArray(azimuthScalars)
        self.scan.GetPointData().AddArray(elevationScalars)

        if self.pitchAndRoll:
            self.scan.GetPointData().AddArray(pitchScalars)
            self.scan.GetPointData().AddArray(rollScalars)

        # This creates separate vertex cells

        print("MVM: {}".format(pts.GetNumberOfPoints()))
        vts.InsertNextCell(pts.GetNumberOfPoints())
        for i in range(pts.GetNumberOfPoints()):
            vts.InsertCellPoint(i)

        if self.geomType == 'sweep':
            if self.scanType == 'RHI' or self.scanType == 'VAD':
                self.scan.SetDimensions([
                    self.header['Number of gates'],
                    self.header['No. of rays in file'], 1
                ])
            elif self.scanType == 'User1':
                self.scan.SetDimensions(
                    [self.header['Number of gates'], beamID, 1])
            else:
                self.scan.SetDimensions(
                    [self.header['Number of gates'], beamID, 1])

        if self.geomType == 'gates':
            self.scan.SetVerts(vts)
        elif self.geomType == 'rays':
            # when I do it this way, I get one cell of multiple lines
            # I'd rather have multiple cells, I think
            # which means... either inserting after
            self.scan.SetLines(vts)
Exemple #33
0
 def register(self, fixedData, movingData, index = -1, discard = False, delta = 0, fov = 9999999.0,
         down_fix = 1, down_mov = 1, occ = 9999999.0, op = False, useMask = False, isTime = False, MaxRate = 0.2,
         aug = False, distance_fix = 0.3, distance_mov = 0.1, w_wrong = 1.5, truth_mov = None):
     time1 = time.time()
     if index == -1:
         index = self.gui.getDataIndex({'Contour': 0, 'Centerline': 1}, 'Select the object')
     if index is None:
         return None, None, None
     if index == 0:
         fixed_points = fixedData.getPointSet('Contour').copy()
         moving_points = movingData.getPointSet('Contour').copy()
     else:
         fixed_points = fixedData.getPointSet('Centerline').copy()
         moving_points = movingData.getPointSet('Centerline').copy()
     if truth_mov is None:
         truth_mov = moving_points.copy()
     
     fixed_bif = db.getBifurcation(fixed_points)
     moving_bif = db.getBifurcation(moving_points)
     
     if useMask:
         mask_points = movingData.getPointSet('Mask')
         for point in mask_points:
             moving_points = npy.delete(moving_points, npy.where((npy.abs(moving_points[:, 2] - point[2]) < 0.0001) & (npy.round(moving_points[:, -1]) == point[3])), axis = 0)
         
     fixed_res = fixedData.getResolution().tolist()
     moving_res = movingData.getResolution().tolist()
     fixed_points = fixed_points[npy.where(fixed_points[:, 0] >= 0)]
     moving_points = moving_points[npy.where(moving_points[:, 0] >= 0)]
     
     # Use the bifurcation as the initial position
     if (fixed_bif < 0) or (moving_bif < 0):
         fixed_min = 0
     
     # Augmentation of pointset
     fixed = fixed_points.copy()
     moving = moving_points.copy()
     
     if index == 1 and aug:
         fixed = util.augmentCenterline(fixed, 1, 10)
         moving = util.augmentCenterline(moving, 1, 10)
         fix_dis = util.getAxisSin(fixed, 3 / fixed_res[2]) * distance_fix
         mov_dis = util.getAxisSin(moving, 3 / moving_res[2]) * distance_mov
         fixed = util.resampleCenterline(fixed, fix_dis / fixed_res[2])
         moving = util.resampleCenterline(moving, mov_dis / moving_res[2])
     
     fixed = fixed[npy.cast[npy.int32](npy.abs(fixed[:, 2] - fixed_bif)) % down_fix == 0]
     moving = moving[npy.cast[npy.int32](npy.abs(moving[:, 2] - moving_bif)) % down_mov == 0]
     
     fixed[:, :3] *= fixed_res[:3]
     moving[:, :3] *= moving_res[:3]
     
     new_trans_points = truth_mov
     result_center_points = movingData.getPointSet('Centerline').copy()
     new_trans_points = new_trans_points[new_trans_points[:, 3] >= 0]
     result_center_points = result_center_points[result_center_points[:, 3] >= 0]
     new_trans_points[:, :3] *= moving_res[:3]
     result_center_points[:, :3] *= moving_res[:3]
     
     if (fixed_bif >= 0) and (moving_bif >= 0):
         fixed[:, 2] -= (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta)
     
     # Prepare for ICP
     
     MaxIterNum = 50
     #MaxNum = 600
     MaxNum = int(MaxRate * moving.shape[0] + 0.5)
     
     targetPoints = [vtk.vtkPoints(), vtk.vtkPoints(), vtk.vtkPoints()]
     targetVertices = [vtk.vtkCellArray(), vtk.vtkCellArray(), vtk.vtkCellArray()]
     target = [vtk.vtkPolyData(), vtk.vtkPolyData(), vtk.vtkPolyData()]
     Locator = [vtk.vtkCellLocator(), vtk.vtkCellLocator(), vtk.vtkCellLocator()]
     
     for i in range(3):
         for x in fixed[npy.round(fixed[:, 3]) == i]:
             id = targetPoints[i].InsertNextPoint(x[0], x[1], x[2])
             targetVertices[i].InsertNextCell(1)
             targetVertices[i].InsertCellPoint(id)
         target[i].SetPoints(targetPoints[i])
         target[i].SetVerts(targetVertices[i])
         
         Locator[i].SetDataSet(target[i])
         Locator[i].SetNumberOfCellsPerBucket(1)
         Locator[i].BuildLocator()
     
     step = 1
     if moving.shape[0] > MaxNum:
         ind = moving[:, 2].argsort()
         moving = moving[ind, :]
         step = moving.shape[0] / MaxNum
     nb_points = moving.shape[0] / step
     
     points1 = vtk.vtkPoints()
     points1.SetNumberOfPoints(nb_points)
     
     label = npy.zeros([MaxNum * 2], dtype = npy.int8)
     
     j = 0
     for i in range(nb_points):
         points1.SetPoint(i, moving[j][0], moving[j][1], moving[j][2])
         label[i] = moving[j][3]
         j += step
     
     closestp = vtk.vtkPoints()
     closestp.SetNumberOfPoints(nb_points)
     points2 = vtk.vtkPoints()
     points2.SetNumberOfPoints(nb_points)
     
     id1 = id2 = vtk.mutable(0)
     dist = vtk.mutable(0.0)
     outPoint = [0.0, 0.0, 0.0]
     p1 = [0.0, 0.0, 0.0]
     p2 = [0.0, 0.0, 0.0]
     iternum = 0
     a = points1
     b = points2
     if (op and index == 0) or (not op and index == 1):
         w_mat = [[1, w_wrong, w_wrong], [w_wrong, 1, 99999999], [w_wrong, 99999999, 1]]
     else:
         w_mat = [[1, 1, 1], [1, 1, 1], [1, 1, 1]]
     
     accumulate = vtk.vtkTransform()
     accumulate.PostMultiply()
     LandmarkTransform = vtk.vtkLandmarkTransform()
     LandmarkTransform.SetModeToRigidBody()
     
     while True:
         for i in range(nb_points):
             min_dist = 99999999
             min_outPoint = [0.0, 0.0, 0.0]
             for j in range(3):
                 Locator[j].FindClosestPoint(a.GetPoint(i), outPoint, id1, id2, dist)
                 dis = npy.sqrt(npy.sum((npy.array(outPoint) - a.GetPoint(i)) ** 2))
                 if dis * w_mat[label[i]][j] < min_dist:
                     min_dist = dis * w_mat[label[i]][j]
                     min_outPoint = copy.deepcopy(outPoint)
                 
             closestp.SetPoint(i, min_outPoint)
             
         LandmarkTransform.SetSourceLandmarks(a)
         LandmarkTransform.SetTargetLandmarks(closestp)
         LandmarkTransform.Update()
         accumulate.Concatenate(LandmarkTransform.GetMatrix())
             
         iternum += 1
         
         for i in range(nb_points):
             a.GetPoint(i, p1)
             LandmarkTransform.InternalTransformPoint(p1, p2)
             b.SetPoint(i, p2)
         b, a = a, b
         
         if iternum >= MaxIterNum:
             break
     
     matrix = accumulate.GetMatrix()
     
     T = ml.mat([matrix.GetElement(0, 3), matrix.GetElement(1, 3), matrix.GetElement(2, 3)]).T
     R = ml.mat([[matrix.GetElement(0, 0), matrix.GetElement(0, 1), matrix.GetElement(0, 2)], 
                 [matrix.GetElement(1, 0), matrix.GetElement(1, 1), matrix.GetElement(1, 2)], 
                 [matrix.GetElement(2, 0), matrix.GetElement(2, 1), matrix.GetElement(2, 2)]]).I
     result_center_points[:, :3] = util.applyTransformForPoints(result_center_points[:, :3], npy.array([1.0, 1, 1]), npy.array([1.0, 1, 1]), R, T, ml.zeros([3, 1], dtype = npy.float32))
     new_trans_points[:, :3] = util.applyTransformForPoints(new_trans_points[:, :3], npy.array([1.0, 1, 1]), npy.array([1.0, 1, 1]), R, T, ml.zeros([3, 1], dtype = npy.float32))
     
     LandmarkTransform = vtk.vtkThinPlateSplineTransform()
     LandmarkTransform.SetBasisToR()
     iternum = 0
     # Non-rigid
     while True:
         for i in range(nb_points):
             min_dist = 99999999
             min_outPoint = [0.0, 0.0, 0.0]
             for j in range(3):
                 Locator[j].FindClosestPoint(a.GetPoint(i), outPoint, id1, id2, dist)
                 dis = npy.sqrt(npy.sum((npy.array(outPoint) - a.GetPoint(i)) ** 2))
                 if dis * w_mat[label[i]][j] < min_dist:
                     min_dist = dis * w_mat[label[i]][j]
                     min_outPoint = copy.deepcopy(outPoint)
                 
             closestp.SetPoint(i, min_outPoint)
             
         LandmarkTransform.SetSourceLandmarks(a)
         LandmarkTransform.SetTargetLandmarks(closestp)
         LandmarkTransform.Update()
         
         '''
         for i in range(result_center_points.shape[0]):
             LandmarkTransform.InternalTransformPoint([result_center_points[i, 0], result_center_points[i, 1], result_center_points[i, 2]], p2)
             result_center_points[i, :3] = p2
         '''
         for i in range(new_trans_points.shape[0]):
             LandmarkTransform.InternalTransformPoint([new_trans_points[i, 0], new_trans_points[i, 1], new_trans_points[i, 2]], p2)
             new_trans_points[i, :3] = p2
             
         iternum += 1
         if iternum >= 1:
             break
         
         for i in range(nb_points):
             a.GetPoint(i, p1)
             LandmarkTransform.InternalTransformPoint(p1, p2)
             b.SetPoint(i, p2)
         b, a = a, b
     
     time2 = time.time()
     
     if (fixed_bif >= 0) and (moving_bif >= 0):
         new_trans_points[:, 2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta)
         result_center_points[:, 2] += (fixed_bif * fixed_res[2] - moving_bif * moving_res[2] + delta)
     new_trans_points[:, :3] /= fixed_res[:3]
     result_center_points[:, :3] /= fixed_res[:3]
     resultImage = movingData.getData().copy()
     
     sa = SurfaceErrorAnalysis(None)
     dataset = db.BasicData(npy.array([[[0]]]), fixedData.getInfo(), {'Contour': new_trans_points, 'Centerline': result_center_points})
     mean_dis, mean_whole, max_dis, max_whole = sa.analysis(dataset, point_data_fix = fixedData.getPointSet('Contour').copy(), useResult = True)
     del dataset
     print mean_dis
     print mean_whole
     
     if isTime:
         return resultImage, {'Contour': new_trans_points, 'Centerline': result_center_points}, [mean_dis, mean_whole], time2 - time1
     return resultImage, {'Contour': new_trans_points, 'Centerline': result_center_points}, [mean_dis, mean_whole]
Exemple #34
0
# create planes
# Create the RenderWindow, Renderer
#
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)

iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

# Custom polydata to test intersections. Loop are ordered in
# reverse directions.
polysData = vtk.vtkPolyData()
polysPts = vtk.vtkPoints()
polysPolys = vtk.vtkCellArray()
polysData.SetPoints(polysPts)
polysData.SetPolys(polysPolys)

polysPts.SetNumberOfPoints(8)
polysPts.SetPoint(0, 0.0, 0.0, 0.0)
polysPts.SetPoint(1, 2.0, 0.0, 0.0)
polysPts.SetPoint(2, 2.0, 2.0, 0.0)
polysPts.SetPoint(3, 0.0, 2.0, 0.0)
polysPts.SetPoint(4, -2.0, -2.0, 0.0)
polysPts.SetPoint(5, 0.0, -2.0, 0.0)
polysPts.SetPoint(6, 0.0, 0.0, 0.0)
polysPts.SetPoint(7, -2.0, 0.0, 0.0)

polysPolys.InsertNextCell(4)
polysPolys.InsertCellPoint(0)
Exemple #35
0
# Add the actors to the renderer, set the background and size
ren.AddActor(ia)
ren.SetBackground(0.1, 0.2, 0.4)
renWin.SetSize(400, 400)

renWin.Render()

cam1 = ren.GetActiveCamera()

ren.ResetCameraClippingRange()
renWin.Render()

### Supporting data for callbacks
pts = vtk.vtkPoints()
pts.SetNumberOfPoints(4)
lines = vtk.vtkCellArray()
lines.InsertNextCell(5)
lines.InsertCellPoint(0)
lines.InsertCellPoint(1)
lines.InsertCellPoint(2)
lines.InsertCellPoint(3)
lines.InsertCellPoint(0)
pd = vtk.vtkPolyData()
pd.SetPoints(pts)
pd.SetLines(lines)
bboxMapper = vtk.vtkPolyDataMapper2D()
bboxMapper.SetInputData(pd)
bboxActor = vtk.vtkActor2D()
bboxActor.SetMapper(bboxMapper)
bboxActor.GetProperty().SetColor(1, 0, 0)
ren.AddViewProp(bboxActor)
def drawOffsets2(myscreen, ofs):
    # draw loops
    nloop = 0
    lineColor = ovdvtk.lgreen
    arcColor = ovdvtk.green  # grass
    ofs_points = []
    for lop in ofs:
        points = []
        n = 0
        N = len(lop)
        first_point = []
        previous = []
        for p in lop:
            # p[0] is the Point
            # p[1] is -1 for lines, and r for arcs
            if n == 0:  # don't draw anything on the first iteration
                previous = p[0]
                # first_point = p[0]
            else:
                cw = p[3]  # cw/ccw flag
                cen = p[2]  # center
                r = p[1]  # radius
                p = p[0]  # target point
                if r == -1:  # r=-1 means line-segment
                    points.extend([previous, p])  # drawLine(myscreen, previous, p, lineColor)
                else:  # otherwise we have an arc
                    points.extend(arc_pts(previous, p, r, cen, cw))

                previous = p
            n = n + 1
        ofs_points.append(points)
        # print "rendered loop ",nloop, " with ", len(lop), " points"
        nloop = nloop + 1

    # now draw each loop with polydata
    oPoints = vtk.vtkPoints()
    lineCells = vtk.vtkCellArray()
    # self.colorLUT = vtk.vtkLookupTable()
    print "offset2vtk.drawOffsets2(): ", len(ofs_points), " loops to render:"
    idx = 0
    last_idx = 0

    for of in ofs_points:
        epts = of
        segs = []
        first = 1
        print " loop with ", len(epts), " points"
        for p in epts:
            oPoints.InsertNextPoint(p.x, p.y, 0)
            if first == 0:
                seg = [last_idx, idx]
                segs.append(seg)
            first = 0
            last_idx = idx
            idx = idx + 1

        # create line and cells
        for seg in segs:
            line = vtk.vtkLine()
            line.GetPointIds().SetId(0, seg[0])
            line.GetPointIds().SetId(1, seg[1])
            # print " indexes: ", seg[0]," to ",seg[1]
            lineCells.InsertNextCell(line)

    linePolyData = vtk.vtkPolyData()
    linePolyData.SetPoints(oPoints)
    linePolyData.SetLines(lineCells)
    linePolyData.Modified()
    # linePolyData.Update()
    mapper = vtk.vtkPolyDataMapper()
    mapper.SetInputData(linePolyData)
    edge_actor = vtk.vtkActor()
    edge_actor.SetMapper(mapper)
    edge_actor.GetProperty().SetColor(ovdvtk.lgreen)
    myscreen.addActor(edge_actor)
Exemple #37
0
 def __init__(self):
     self.points = vtk.vtkPoints()
     self.vertices = vtk.vtkCellArray()
Exemple #38
0
    return node_num_order


node_ordered = nodeReorder(node_list)

#VTK insert points
points = vtk.vtkPoints()
print("adding nodes now.")
for node in node_list:
    points.InsertNextPoint(node.X, node.Y, node.Z)

#vtk generate mesh
mesh = vtk.vtkUnstructuredGrid()
tetra = vtk.vtkTetra()
cellarray = vtk.vtkCellArray()
for tet in tet4_list:
    tetra.GetPointIds().SetId(0, node_ordered[tet.node1])
    tetra.GetPointIds().SetId(1, node_ordered[tet.node2])
    tetra.GetPointIds().SetId(2, node_ordered[tet.node3])
    tetra.GetPointIds().SetId(3, node_ordered[tet.node4])
    cellarray.InsertNextCell(tetra)

mesh.SetPoints(points)
mesh.SetCells(vtk.VTK_TETRA, cellarray)

#extract surface
surface_filter = vtk.vtkDataSetSurfaceFilter()
surface_filter.SetInputData(mesh)
surface_filter.Update()
polydata = vtk.vtkPolyData()
# Outline around the entire dataset
outline = vtk.vtkOutlineFilter()
outline.SetInputConnection(mandel.GetOutputPort())

outlineMapper = vtk.vtkPolyDataMapper()
outlineMapper.SetInputConnection(outline.GetOutputPort())

outlineActor = vtk.vtkActor()
outlineActor.SetMapper(outlineMapper)

# Intersect the clipped output with a ray
ray = vtk.vtkPolyData()
rayPts = vtk.vtkPoints()
rayPts.InsertPoint(0, -7.5, -5, -5)
rayPts.InsertPoint(1, 2.5, 2, 2.5)
rayLine = vtk.vtkCellArray()
rayLine.InsertNextCell(2)
rayLine.InsertCellPoint(0)
rayLine.InsertCellPoint(1)
ray.SetPoints(rayPts)
ray.SetLines(rayLine)

rayMapper = vtk.vtkPolyDataMapper()
rayMapper.SetInputData(ray)

rayActor = vtk.vtkActor()
rayActor.SetMapper(rayMapper)
rayActor.GetProperty().SetColor(0, 1, 0)

# Produce intersection point
hit = locator.IntersectWithLine(rayPts.GetPoint(0), rayPts.GetPoint(1), 0.001,
Exemple #40
0
for iface in faces:
    print("face=", iface)
    proj = projector[iface]
    #project faces

    for i in range(N):
        for j in range(N):
            ipix = coord2pix(iface, i, j)
            #print("pix",(iface,i,j),ipix)
            p = array(proj(x[i, j], y[i, j]))
            if doNorm:
                p = normalize(p)
            pts.InsertPoint(ipix, p)

#cells
polys = vtk.vtkCellArray()
colors = vtk.vtkFloatArray()

for iface in faces:
    for i in range(N - 1):
        for j in range(N - 1):
            cid = polys.InsertNextCell(4)

            ip = coord2pix(iface, i, j)
            polys.InsertCellPoint(ip)

            ip1 = coord2pix(iface, i + 1, j)
            polys.InsertCellPoint(ip1)

            ip2 = coord2pix(iface, i + 1, j + 1)
            polys.InsertCellPoint(ip2)
Exemple #41
0
def CreateOutline9076(color=(255, 99, 71), depth=80.0):
    """
  Create outline for the 9076 probe. The outline is contained in the XZ-plane
  """
    # Default color for the outline is "Tomato"
    nElements = 144
    pitch = 0.2101
    roc = 50.006
    height = 5.0

    azR = roc
    azArcLength = pitch * (nElements - 1.0)
    azSegment = azArcLength / azR
    dAz = azSegment / (nElements - 1.0)

    az = dAz * (np.r_[0:nElements] - 0.5 * (nElements - 1.0))

    az0 = az[0] - 0.5 * dAz
    azN = az[nElements - 1] + 0.5 * dAz

    appendFilter = vtk.vtkAppendPolyData()

    # Create first arc
    arc0 = vtk.vtkArcSource()
    arc0.SetCenter(0, 0, -azR)
    arc0.SetPoint1(azR * np.sin(az0), 0, azR * np.cos(az0) - azR)
    arc0.SetPoint2(azR * np.sin(azN), 0, azR * np.cos(azN) - azR)
    arc0.SetResolution(10)
    arc0.Update()

    appendFilter.AddInputData(arc0.GetOutput())
    appendFilter.Update()

    arc1 = vtk.vtkArcSource()
    arc1.SetCenter(0, 0, -azR)
    arc1.SetPoint1((azR + depth) * np.sin(az0), 0,
                   (azR + depth) * np.cos(az0) - azR)
    arc1.SetPoint2((azR + depth) * np.sin(azN), 0,
                   (azR + depth) * np.cos(azN) - azR)
    arc1.SetResolution(10)
    arc1.Update()

    appendFilter.AddInputData(arc1.GetOutput())
    appendFilter.Update()

    # Create lines
    linesPolyData = vtk.vtkPolyData()

    pts = vtk.vtkPoints()
    pts.InsertNextPoint((azR * np.sin(az0), 0, azR * np.cos(az0) - azR))
    pts.InsertNextPoint(
        ((azR + depth) * np.sin(az0), 0, (azR + depth) * np.cos(az0) - azR))
    pts.InsertNextPoint((azR * np.sin(azN), 0, azR * np.cos(azN) - azR))
    pts.InsertNextPoint(
        ((azR + depth) * np.sin(azN), 0, (azR + depth) * np.cos(azN) - azR))

    linesPolyData.SetPoints(pts)

    line0 = vtk.vtkLine()
    line0.GetPointIds().SetId(0, 0)
    line0.GetPointIds().SetId(1, 1)

    line1 = vtk.vtkLine()
    line1.GetPointIds().SetId(0, 2)
    line1.GetPointIds().SetId(1, 3)

    # Create a vtkCellArray container and store the lines in it
    lines = vtk.vtkCellArray()
    lines.InsertNextCell(line0)
    lines.InsertNextCell(line1)

    linesPolyData.SetLines(lines)

    appendFilter.AddInputData(linesPolyData)
    appendFilter.Update()

    outline = appendFilter.GetOutput()

    colors = vtk.vtkUnsignedCharArray()
    colors.SetNumberOfComponents(3)
    for i in range(outline.GetNumberOfCells()):
        colors.InsertNextTypedTuple(color)

    outline.GetCellData().SetScalars(colors)
    return outline
Exemple #42
0
def DrawTrajectory():
    
    nbrPoints = 1000
    w0 = array([0.0, 1.0, 0.0])
    time = linspace(0.0, 40.0, nbrPoints) 
    trajectory = integrate.odeint(Lorenz, w0, time,args=())
     
    
     
    # Total number of points.
    numberOfInputPoints = nbrPoints
     
    # One spline for each direction.
    aSplineX = vtk.vtkCardinalSpline()
    aSplineY = vtk.vtkCardinalSpline()
    aSplineZ = vtk.vtkCardinalSpline()
     
    inputPoints = vtk.vtkPoints()
    for i in range(0, numberOfInputPoints):
        x = trajectory[i,0]
        y = trajectory[i,1]
        z = trajectory[i,2]
        aSplineX.AddPoint(i, trajectory[i,0])
        aSplineY.AddPoint(i, trajectory[i,1])
        aSplineZ.AddPoint(i, trajectory[i,2])
        inputPoints.InsertPoint(i, x, y, z)
     
    # The following section will create glyphs for the pivot points
    # in order to make the effect of the spline more clear.
     
    # Create a polydata to be glyphed.
    inputData = vtk.vtkPolyData()
    inputData.SetPoints(inputPoints)
     
    # Use sphere as glyph source.
    balls = vtk.vtkSphereSource()
    balls.SetRadius(.01)
    balls.SetPhiResolution(10)
    balls.SetThetaResolution(10)
     
    glyphPoints = vtk.vtkGlyph3D()
    glyphPoints.SetInputData(inputData)
    glyphPoints.SetSourceConnection(balls.GetOutputPort())
     
    glyphMapper = vtk.vtkPolyDataMapper()
    glyphMapper.SetInputConnection(glyphPoints.GetOutputPort())
     
    glyph = vtk.vtkActor()
    glyph.SetMapper(glyphMapper)
    glyph.GetProperty().SetDiffuseColor(tomato)
    glyph.GetProperty().SetSpecular(.3)
    glyph.GetProperty().SetSpecularPower(30)
     
    # Generate the polyline for the spline.
    points = vtk.vtkPoints()
    profileData = vtk.vtkPolyData()
     
    # Number of points on the spline
    numberOfOutputPoints = nbrPoints*10
     
    # Interpolate x, y and z by using the three spline filters and
    # create new points
    for i in range(0, numberOfOutputPoints):
        t = (numberOfInputPoints-1.0)/(numberOfOutputPoints-1.0)*i
        points.InsertPoint(i, aSplineX.Evaluate(t), aSplineY.Evaluate(t),
                           aSplineZ.Evaluate(t))
     
    # Create the polyline.
    lines = vtk.vtkCellArray()
    lines.InsertNextCell(numberOfOutputPoints)
    for i in range(0, numberOfOutputPoints):
        lines.InsertCellPoint(i)
     
    profileData.SetPoints(points)
    profileData.SetLines(lines)
     
    # Add thickness to the resulting line.
    profileTubes = vtk.vtkTubeFilter()
    profileTubes.SetNumberOfSides(8)
    profileTubes.SetInputData(profileData)
    profileTubes.SetRadius(.05)
     
    profileMapper = vtk.vtkPolyDataMapper()
    profileMapper.SetInputConnection(profileTubes.GetOutputPort())
     
    profile = vtk.vtkActor()
    profile.SetMapper(profileMapper)
    profile.GetProperty().SetDiffuseColor(gold)
    profile.GetProperty().SetSpecular(.3)
    profile.GetProperty().SetSpecularPower(30)
    
    return glyph, profile
Exemple #43
0
 def ReadTecplotMeshFile(self):
     self.PrintLog('Reading Tecplot surface file.')
     if self.InputFileName[-3:] == '.gz':
         import gzip
         f = gzip.open(self.InputFileName, 'r')
     else:
         f = open(self.InputFileName, 'r')
     line = f.readline()
     if line.split()[0] == 'TITLE':
         line = f.readline()
     if (line.split()[0] == 'VARIABLES') | (line.split('=')[0]
                                            == 'VARIABLES'):
         arrayNames = line.split('=')[1].strip().split(',')
         arrayNames[0:3] = []
         self.PrintLog("ArrayNames" + str(arrayNames))
         line = f.readline()
     if line.split()[0] == 'ZONE':
         lineNid = line.find('N=')
         lineN = line[lineNid:lineNid +
                      line[lineNid:].find(',')].split('=')[1]
         numberOfNodes = int(lineN)
         lineEid = line.find('E=')
         lineE = line[lineEid:lineEid +
                      line[lineEid:].find(',')].split('=')[1]
         numberOfElements = int(lineE)
     self.PrintLog("Reading " + str(numberOfNodes) + " nodes.")
     points = vtk.vtkPoints()
     cells = vtk.vtkCellArray()
     points.SetNumberOfPoints(numberOfNodes)
     self.Mesh = vtk.vtkUnstructuredGrid()
     self.Mesh.SetPoints(points)
     for arrayName in arrayNames:
         array = vtk.vtkDoubleArray()
         array.SetName(arrayName)
         array.SetNumberOfTuples(numberOfNodes)
         self.Mesh.GetPointData().AddArray(array)
     data = f.read().split()
     dataCounter = 0
     for i in range(numberOfNodes):
         point = [
             float(data[dataCounter]),
             float(data[dataCounter + 1]),
             float(data[dataCounter + 2])
         ]
         dataCounter += 3
         points.SetPoint(i, point)
         for j in range(len(arrayNames)):
             self.Mesh.GetPointData().GetArray(arrayNames[j]).SetComponent(
                 i, 0, float(data[dataCounter]))
             dataCounter += 1
     self.PrintLog("Reading " + str(numberOfElements) + " elements.")
     cellIds = vtk.vtkIdList()
     for i in range(numberOfElements):
         cellIds.Initialize()
         cellIds.InsertNextId(int(data[dataCounter]) - 1)
         dataCounter += 1
         cellIds.InsertNextId(int(data[dataCounter]) - 1)
         dataCounter += 1
         cellIds.InsertNextId(int(data[dataCounter]) - 1)
         dataCounter += 1
         cellIds.InsertNextId(int(data[dataCounter]) - 1)
         dataCounter += 1
         legal = 1
         for j in range(cellIds.GetNumberOfIds()):
             if cellIds.GetId(j) < 0:
                 legal = 0
                 break
         if not legal:
             continue
         cells.InsertNextCell(cellIds)
     self.Mesh.SetCells(10, cells)
     self.Mesh.Update()
from vtk.util.misc import vtkGetDataRoot

VTK_DATA_ROOT = vtkGetDataRoot()

# create two boxes and interpolate between them
#
pts = vtk.vtkPoints()
pts.InsertNextPoint(-1, -1, -1)
pts.InsertNextPoint(1, -1, -1)
pts.InsertNextPoint(1, 1, -1)
pts.InsertNextPoint(-1, 1, -1)
pts.InsertNextPoint(-1, -1, 1)
pts.InsertNextPoint(1, -1, 1)
pts.InsertNextPoint(1, 1, 1)
pts.InsertNextPoint(-1, 1, 1)
faces = vtk.vtkCellArray()
faces.InsertNextCell(4)
faces.InsertCellPoint(0)
faces.InsertCellPoint(3)
faces.InsertCellPoint(2)
faces.InsertCellPoint(1)
faces.InsertNextCell(4)
faces.InsertCellPoint(4)
faces.InsertCellPoint(5)
faces.InsertCellPoint(6)
faces.InsertCellPoint(7)
faces.InsertNextCell(4)
faces.InsertCellPoint(0)
faces.InsertCellPoint(1)
faces.InsertCellPoint(5)
faces.InsertCellPoint(4)
Exemple #45
0
	for t in range( nLineTimePt ):
		time_pt = ( t1 - t0 ) * t / nLineTimePt + t0

		v_t = manifolds.sphere_tVec( nDimManifold )
		v_t.SetTangentVector( [ ( gamma0_tilde.tVector[ 0 ] + gamma1_tilde.tVector[ 0 ] * c_pt ) * time_pt, ( gamma0_tilde.tVector[ 1 ] + gamma1_tilde.tVector[ 1 ] * c_pt ) * time_pt, ( gamma0_tilde.tVector[ 2 ] + gamma1_tilde.tVector[ 2 ] * c_pt ) * time_pt ] )

		p_t = p0_c.ExponentialMap( v_t )
		group_geodesic_pt_list.append( p_t )

	group_geodesic_vtk = vtk.vtkPolyData()
	group_geodesic_pts = vtk.vtkPoints()

	for t in range( len( group_geodesic_pt_list ) ):
		group_geodesic_pts.InsertNextPoint( group_geodesic_pt_list[ t ].pt[ 0 ], group_geodesic_pt_list[ t ].pt[ 1 ], group_geodesic_pt_list[ t ].pt[ 2 ] )

	group_geodesic_line = vtk.vtkCellArray()
	for t in range( len( group_geodesic_pt_list ) - 1 ):
		line_i = vtk.vtkLine()
		line_i.GetPointIds().SetId( 0, t )
		line_i.GetPointIds().SetId( 1, t + 1 )
		group_geodesic_line.InsertNextCell( line_i )

	group_geodesic_vtk.SetPoints( group_geodesic_pts )
	group_geodesic_vtk.SetLines( group_geodesic_line )

	group_vtk_list_s1.append( group_geodesic_vtk )

# Point List with Covariates
pt_list = []
t_list = []
    def make__uGrid(self):

        # ------------------------------------------------- #
        # --- [1] element IDs & offset = define cells   --- #
        # ------------------------------------------------- #
        #  -- [1-1] offset & elemIDs                    --  #
        nVertArray = np.sum(np.ones_like(self.elems), axis=1)
        offset = np.cumsum(np.insert(nVertArray, 0, 0.0))
        offset = npv.numpy_to_vtkIdTypeArray(
            (offset[:-1]).astype(self.ID_TYPE))

        #  -- [1-2] cell type                           --  #
        if (self.elementType is not None):
            cellType = np.full((self.nElem, ), self.elementType)
        if (self.nVert == 4):
            cellType = np.full((self.nElem, ), vtk.VTK_TETRA)
        if (self.nVert == 8):
            cellType = np.full((self.nElem, ), vtk.VTK_HEXAHEDRON)
        cellType = cellType.astype(np.uint8)
        cellType = npv.numpy_to_vtk(cellType)

        #  -- [1-3] cell array                          --  #
        elemIDs      = np.concatenate( [ np.reshape( nVertArray, ( self.nElem,1) ), \
                                         self.elems ], axis=1 )
        elemIDs = npv.numpy_to_vtkIdTypeArray(np.ravel(elemIDs))
        cellArray = vtk.vtkCellArray()
        cellArray.SetCells(self.nElem, elemIDs)
        # -- elemID Data Structure -- #
        # [ [ N, e1, e2, e3, ...., eN ], [ N, e1, e2, e3, ...., eN ], .... ]
        # --

        # ------------------------------------------------- #
        # --- [2] node definition                       --- #
        # ------------------------------------------------- #
        vtkPoints = vtk.vtkPoints()
        vtkPoints.SetData(npv.numpy_to_vtk(self.nodes))

        # ------------------------------------------------- #
        # --- [3] Define unstructured Grid              --- #
        # ------------------------------------------------- #
        self.ugrid = vtk.vtkUnstructuredGrid()
        self.ugrid.SetPoints(vtkPoints)
        self.ugrid.SetCells(cellType, offset, cellArray)

        # ------------------------------------------------- #
        # --- [4] cellData & pointData                  --- #
        # ------------------------------------------------- #
        #  -- [4-1] cellData                            --  #
        if (self.cellData is not None):
            self.cellDataDict = { key: npv.numpy_to_vtk( self.cellData[:,ik], deep=True ) \
                                  for ik,key in enumerate( self.cellDataName ) }
            for key in self.cellDataName:
                self.cellDataDict[key].SetName(key)
                self.ugrid.GetCellData().AddArray(self.cellDataDict[key])

        #  -- [4-2] pointData                           --  #
        if (self.pointData is not None):
            self.pointDataDict = { key: npv.numpy_to_vtk( self.pointData[:,ik], deep=True ) \
                                  for ik,key in enumerate( self.pointDataName ) }
            for key in self.pointDataName:
                self.pointDataDict[key].SetName(key)
                self.ugrid.GetPointData().AddArray(self.pointDataDict[key])
Exemple #47
0
def array2vtkCellArray(num_array, vtk_array=None):
    """Given a nested Python list or a numpy array, this method
    creates a vtkCellArray instance and returns it.

    A variety of input arguments are supported as described in the
    Parameter documentation.  If numpy arrays are given, this method
    is highly efficient.  This function is most efficient if the
    passed numpy arrays have a typecode `ID_TYPE_CODE`.  Otherwise a
    typecast is necessary and this involves an extra copy.  This
    method *always copies* the input data.

    An alternative and more efficient way to build the connectivity
    list is to create a vtkIdTypeArray having data of the form
    (npts,p0,p1,...p(npts-1), repeated for each cell) and then call
    <vtkCellArray_instance>.SetCells(n_cell, id_list).

    Parameters
    ----------

    - num_array : numpy array or Python list/tuple

      Valid values are:

        1. A Python list of 1D lists.  Each 1D list can contain one
           cell connectivity list.  This is very slow and is to be
           used only when efficiency is of no consequence.

        2. A 2D numpy array with the cell connectivity list.

        3. A Python list of 2D numpy arrays.  Each numeric array can
           have a different shape.  This makes it easy to generate a
           cell array having cells of different kinds.

    - vtk_array : `vtkCellArray` (default: `None`)

      If an optional `vtkCellArray` instance, is passed as an argument
      then a new array is not created and returned.  The passed array
      is itself modified and returned.

    Example
    -------

       >>> a = [[0], [1, 2], [3, 4, 5], [6, 7, 8, 9]]
       >>> cells = array_handler.array2vtkCellArray(a)
       >>> a = numpy.array([[0,1,2], [3,4,5], [6,7,8]], 'l')
       >>> cells = array_handler.array2vtkCellArray(a)
       >>> l_a = [a[:,:1], a[:2,:2], a]
       >>> cells = array_handler.array2vtkCellArray(l_a)

    """
    if vtk_array:
        cells = vtk_array
    else:
        cells = vtk.vtkCellArray()
    assert cells.GetClassName() == 'vtkCellArray', \
           'Second argument must be a `vtkCellArray` instance.'

    if len(num_array) == 0:
        return cells

    ########################################
    # Internal functions.
    def _slow_array2cells(z, cells):
        cells.Reset()
        vtk_ids = vtk.vtkIdList()
        for i in z:
            vtk_ids.Reset()
            for j in i:
                vtk_ids.InsertNextId(j)
            cells.InsertNextCell(vtk_ids)

    def _get_tmp_array(arr):
        try:
            tmp_arr = numpy.asarray(arr, ID_TYPE_CODE)
        except TypeError:
            tmp_arr = arr.astype(ID_TYPE_CODE)
        return tmp_arr

    def _set_cells(cells, n_cells, id_typ_arr):
        vtk_arr = vtk.vtkIdTypeArray()
        array2vtk(id_typ_arr, vtk_arr)
        cells.SetCells(n_cells, vtk_arr)
    ########################################

    msg = "Invalid argument.  Valid types are a Python list of lists,"\
          " a Python list of numpy arrays, or a numpy array."

    if issubclass(type(num_array), (types.ListType, types.TupleType)):
        assert len(num_array[0]) > 0, "Input array must be 2D."
        tp = type(num_array[0])
        if issubclass(tp, types.ListType): # Pure Python list.
            _slow_array2cells(num_array, cells)
            return cells
        elif issubclass(tp, numpy.ndarray):  # List of arrays.
            # Check shape of array and find total size.
            tot_size = 0
            n_cells = 0
            for arr in num_array:
                assert len(arr.shape) == 2, "Each array must be 2D"
                shp = arr.shape
                tot_size += shp[0]*(shp[1] + 1)
                n_cells += shp[0]
            # Create an empty array.
            id_typ_arr = numpy.empty((tot_size,), ID_TYPE_CODE)
            # Now populate it with the ids.
            count = 0
            for arr in num_array:
                tmp_arr = _get_tmp_array(arr)
                shp = arr.shape
                sz = shp[0]*(shp[1] + 1)
                set_id_type_array(tmp_arr, id_typ_arr[count:count+sz])
                count += sz
            # Now set them cells.
            _set_cells(cells, n_cells, id_typ_arr)
            return cells
        else:
            raise TypeError, msg
    elif issubclass(type(num_array), numpy.ndarray):
        assert len(num_array.shape) == 2, "Input array must be 2D."
        tmp_arr = _get_tmp_array(num_array)
        shp = tmp_arr.shape
        id_typ_arr = numpy.empty((shp[0]*(shp[1] + 1),), ID_TYPE_CODE)
        set_id_type_array(tmp_arr, id_typ_arr)
        _set_cells(cells, shp[0], id_typ_arr)
        return cells
    else:
        raise TypeError, msg
Exemple #48
0
    def straightenVolume(self,
                         outputStraightenedVolume,
                         curveNode,
                         volumeNode,
                         sliceSizeMm,
                         outputSpacingMm,
                         rotationAngleDeg=0.0):
        """
    Compute straightened volume (useful for example for visualization of curved vessels)
    """
        originalCurvePoints = curveNode.GetCurvePointsWorld()
        sampledPoints = vtk.vtkPoints()
        if not slicer.vtkMRMLMarkupsCurveNode.ResamplePoints(
                originalCurvePoints, sampledPoints, outputSpacingMm[2], False):
            return False

        sliceExtent = [
            int(sliceSizeMm[0] / outputSpacingMm[0]),
            int(sliceSizeMm[1] / outputSpacingMm[1])
        ]
        inputSpacing = volumeNode.GetSpacing()

        lines = vtk.vtkCellArray()
        lines.InsertNextCell(sampledPoints.GetNumberOfPoints())
        for pointIndex in range(sampledPoints.GetNumberOfPoints()):
            lines.InsertCellPoint(pointIndex)
        sampledCurvePoly = vtk.vtkPolyData()
        sampledCurvePoly.SetPoints(sampledPoints)
        sampledCurvePoly.SetLines(lines)

        # Get physical coordinates from voxel coordinates
        volumeRasToIjkTransformMatrix = vtk.vtkMatrix4x4()
        volumeNode.GetRASToIJKMatrix(volumeRasToIjkTransformMatrix)

        transformWorldToVolumeRas = vtk.vtkMatrix4x4()
        slicer.vtkMRMLTransformNode.GetMatrixTransformBetweenNodes(
            None, volumeNode.GetParentTransformNode(),
            transformWorldToVolumeRas)

        transformWorldToIjk = vtk.vtkTransform()
        transformWorldToIjk.Concatenate(transformWorldToVolumeRas)
        transformWorldToIjk.Scale(inputSpacing)
        transformWorldToIjk.Concatenate(volumeRasToIjkTransformMatrix)

        transformPolydataWorldToIjk = vtk.vtkTransformPolyDataFilter()
        transformPolydataWorldToIjk.SetInputData(sampledCurvePoly)
        transformPolydataWorldToIjk.SetTransform(transformWorldToIjk)

        reslicer = vtk.vtkSplineDrivenImageSlicer()
        append = vtk.vtkImageAppend()

        scaledImageData = vtk.vtkImageData()
        scaledImageData.ShallowCopy(volumeNode.GetImageData())
        scaledImageData.SetSpacing(inputSpacing)

        reslicer.SetInputData(scaledImageData)
        reslicer.SetPathConnection(transformPolydataWorldToIjk.GetOutputPort())
        reslicer.SetSliceExtent(*sliceExtent)
        reslicer.SetSliceSpacing(outputSpacingMm[0], outputSpacingMm[1])
        reslicer.SetIncidence(vtk.vtkMath.RadiansFromDegrees(rotationAngleDeg))

        nbPoints = sampledPoints.GetNumberOfPoints()
        for ptId in reversed(range(nbPoints)):
            reslicer.SetOffsetPoint(ptId)
            reslicer.Update()
            tempSlice = vtk.vtkImageData()
            tempSlice.DeepCopy(reslicer.GetOutput(0))
            append.AddInputData(tempSlice)

        append.SetAppendAxis(2)
        append.Update()
        straightenedVolumeImageData = append.GetOutput()
        straightenedVolumeImageData.SetOrigin(0, 0, 0)
        straightenedVolumeImageData.SetSpacing(1.0, 1.0, 1.0)

        dims = straightenedVolumeImageData.GetDimensions()
        ijkToRas = vtk.vtkMatrix4x4()
        ijkToRas.SetElement(0, 0, 0.0)
        ijkToRas.SetElement(1, 0, 0.0)
        ijkToRas.SetElement(2, 0, -outputSpacingMm[0])

        ijkToRas.SetElement(0, 1, 0.0)
        ijkToRas.SetElement(1, 1, outputSpacingMm[1])
        ijkToRas.SetElement(2, 1, 0.0)

        ijkToRas.SetElement(0, 2, outputSpacingMm[2])
        ijkToRas.SetElement(1, 2, 0.0)
        ijkToRas.SetElement(2, 2, 0.0)

        outputStraightenedVolume.SetIJKToRASMatrix(ijkToRas)
        outputStraightenedVolume.SetAndObserveImageData(
            straightenedVolumeImageData)
        outputStraightenedVolume.CreateDefaultDisplayNodes()

        return True
Exemple #49
0
# Create a selection window.  We will display the point and cell ids
# that lie within this window.
xmin = 200
xLength = 100
xmax = xmin + xLength
ymin = 200
yLength = 100
ymax = ymin + yLength

pts = vtk.vtkPoints()
pts.InsertPoint(0, xmin, ymin, 0)
pts.InsertPoint(1, xmax, ymin, 0)
pts.InsertPoint(2, xmax, ymax, 0)
pts.InsertPoint(3, xmin, ymax, 0)
rect = vtk.vtkCellArray()
rect.InsertNextCell(5)
rect.InsertCellPoint(0)
rect.InsertCellPoint(1)
rect.InsertCellPoint(2)
rect.InsertCellPoint(3)
rect.InsertCellPoint(0)
selectRect = vtk.vtkPolyData()
selectRect.SetPoints(pts)
selectRect.SetLines(rect)
rectMapper = vtk.vtkPolyDataMapper2D()
rectMapper.SetInputData(selectRect)
rectActor = vtk.vtkActor2D()
rectActor.SetMapper(rectMapper)

# Create a sphere and its associated mapper and actor.
    def CreateFromArray(self, pc):
        """Create a point cloud visualization object from a given NumPy array
        
        The NumPy array should have dimension Nxd where d >= 3
        
        If d>3, the points will be colored according to the last column
        in the supplied array (values should be between 0 and 1, where 
        0 is black and 1 is white)
        """

        nCoords = pc.shape[0]
        nElem = pc.shape[1]

        if nElem < 3:
            raise Exception(
                "Number of elements must be greater than or equal to 3")

        self.verts = vtk.vtkPoints()
        self.cells = vtk.vtkCellArray()
        self.scalars = None
        self.pd = vtk.vtkPolyData()

        # Optimized version of creating the vertices array
        # - We need to be sure to keep the supplied NumPy array,
        #   because the numpy_support function creates a pointer into it
        # - We need to take a copy to be sure the array is contigous
        self.points_npy = pc[:, :3].copy()
        self.verts.SetData(numpy_support.numpy_to_vtk(self.points_npy))

        # Optimized version of creating the cell ID array
        # - We need to be sure to keep the supplied NumPy array,
        #   because the numpy_support function creates a pointer into it
        # - Note that the cell array looks like this: [1 vtx0 1 vtx1 1 vtx2 1 vtx3 ... ]
        #   because it consists of vertices with one primitive per cell
        self.cells_npy = np.vstack([
            np.ones(nCoords, dtype=np.int64),
            np.arange(nCoords, dtype=np.int64)
        ]).T.flatten()

        self.cells.SetCells(
            nCoords, numpy_support.numpy_to_vtkIdTypeArray(self.cells_npy))

        self.pd.SetPoints(self.verts)
        self.pd.SetVerts(self.cells)

        # Optimized version of creating the scalars array
        # - We need to be sure to keep the NumPy array,
        #   because the numpy_support function creates a pointer into it
        # - We need to take a copy to be sure the array is contigous
        if nElem > 3:
            self.scalars_npy = pc[:, -1].copy()
            self.scalars = numpy_support.numpy_to_vtk(self.scalars_npy)

            # Color the scalar data in gray values
            self.LUT = vtk.vtkLookupTable()
            self.LUT.SetNumberOfColors(255)
            self.LUT.SetSaturationRange(0, 0)
            self.LUT.SetHueRange(0, 0)
            self.LUT.SetValueRange(0, 1)
            self.LUT.Build()
            self.scalars.SetLookupTable(self.LUT)
            self.pd.GetPointData().SetScalars(self.scalars)

        self.SetupPipelineCloud()
Exemple #51
0
 def add_faces(self, faces, color, opacity=0.35):
     for face in faces:
         if len(face) == 3:
             points = vtk.vtkPoints()
             triangle = vtk.vtkTriangle()
             for ii in range(3):
                 points.InsertNextPoint(face[ii][0], face[ii][1], face[ii][2])
                 triangle.GetPointIds().SetId(ii, ii)
             triangles = vtk.vtkCellArray()
             triangles.InsertNextCell(triangle)
             trianglePolyData = vtk.vtkPolyData()
             trianglePolyData.SetPoints(points)
             trianglePolyData.SetPolys(triangles)
             mapper = vtk.vtkPolyDataMapper()
             if vtk.VTK_MAJOR_VERSION <= 5:
                 mapper.SetInputConnection(trianglePolyData.GetProducerPort())
             else:
                 mapper.SetInputData(trianglePolyData)
             # mapper.SetInput(trianglePolyData)
             ac = vtk.vtkActor()
             ac.SetMapper(mapper)
             ac.GetProperty().SetOpacity(opacity)
             ac.GetProperty().SetColor(color)
             self.ren.AddActor(ac)
         elif False and len(face) == 4:
             points = vtk.vtkPoints()
             for ii in range(4):
                 points.InsertNextPoint(face[ii][0], face[ii][1], face[ii][2])
             line1 = vtk.vtkLine()
             line1.GetPointIds().SetId(0, 0)
             line1.GetPointIds().SetId(1, 2)
             line2 = vtk.vtkLine()
             line2.GetPointIds().SetId(0, 3)
             line2.GetPointIds().SetId(1, 1)
             lines = vtk.vtkCellArray()
             lines.InsertNextCell(line1)
             lines.InsertNextCell(line2)
             polydata = vtk.vtkPolyData()
             polydata.SetPoints(points)
             polydata.SetLines(lines)
             ruledSurfaceFilter = vtk.vtkRuledSurfaceFilter()
             ruledSurfaceFilter.SetInput(polydata)
             ruledSurfaceFilter.SetResolution(15, 15)
             ruledSurfaceFilter.SetRuledModeToResample()
             mapper = vtk.vtkPolyDataMapper()
             mapper.SetInput(ruledSurfaceFilter.GetOutput())
             ac = vtk.vtkActor()
             ac.SetMapper(mapper)
             ac.GetProperty().SetOpacity(opacity)
             ac.GetProperty().SetColor(color)
             self.ren.AddActor(ac)
         elif len(face) > 3:
             center = np.zeros(3, np.float)
             for site in face:
                 center += site
             center /= np.float(len(face))
             for ii in range(len(face)):
                 points = vtk.vtkPoints()
                 triangle = vtk.vtkTriangle()
                 points.InsertNextPoint(face[ii][0], face[ii][1], face[ii][2])
                 ii2 = np.mod(ii+1, len(face))
                 points.InsertNextPoint(face[ii2][0], face[ii2][1], face[ii2][2])
                 points.InsertNextPoint(center[0], center[1], center[2])
                 for ii in range(3):
                     triangle.GetPointIds().SetId(ii, ii)
                 triangles = vtk.vtkCellArray()
                 triangles.InsertNextCell(triangle)
                 trianglePolyData = vtk.vtkPolyData()
                 trianglePolyData.SetPoints(points)
                 trianglePolyData.SetPolys(triangles)
                 mapper = vtk.vtkPolyDataMapper()
                 if vtk.VTK_MAJOR_VERSION <= 5:
                     mapper.SetInputConnection(trianglePolyData.GetProducerPort())
                 else:
                     mapper.SetInputData(trianglePolyData)
                 # mapper.SetInput(trianglePolyData)
                 ac = vtk.vtkActor()
                 ac.SetMapper(mapper)
                 ac.GetProperty().SetOpacity(opacity)
                 ac.GetProperty().SetColor(color)
                 self.ren.AddActor(ac)
         else:
             raise ValueError("Number of points for a face should be >= 3")
Exemple #52
0
    def build_actors(self):
        M = self.data_xyz.shape[0]
        log.info('Plotting '+str(M)+' peaks.')        
        
        # Calculate points
        max_rad = np.max(np.linalg.norm(self.data_ijk, axis=-1))
        r = self.rad_scale/max_rad
        starts = self.data_xyz - r*self.data_ijk
        ends = self.data_xyz + r*self.data_ijk

        # Interleave starts and ends
        points_array = np.empty((2*M, 3))
        points_array[0::2] = starts
        points_array[1::2] = ends

        # Calculate line connections
        lines_array = []
        for i in range(M):
            lines_array += [2, 2*i, 2*i+1] # length, index0, index1
        lines_array = np.array(lines_array)

        # Set Points to vtk array format
        vtk_points = vtk.vtkPoints()
        vtk_points.SetData(ns.numpy_to_vtk(points_array, deep=True))

        # Set Lines to vtk array format
        vtk_lines = vtk.vtkCellArray()
        vtk_lines.GetData().DeepCopy(ns.numpy_to_vtk(lines_array))
        vtk_lines.SetNumberOfCells(M)

        # Set poly_data
        poly_data = vtk.vtkPolyData()
        poly_data.SetPoints(vtk_points)
        poly_data.SetLines(vtk_lines)

        # Set tube radius
        tube_filter = vtk.vtkTubeFilter()
        tube_filter.SetInputData(poly_data)
        tube_filter.SetNumberOfSides(50)
        tube_filter.SetRadius(0.5/np.min(self.shape))
        tube_filter.CappingOn()
        tube_filter.Update()

        # Original
        poly_mapper = vtk.vtkPolyDataMapper()
        poly_mapper.SetInputConnection(tube_filter.GetOutputPort())
        poly_mapper.ScalarVisibilityOn()
        poly_mapper.SetScalarModeToUsePointFieldData()
        poly_mapper.SelectColorArray("Colors")
        poly_mapper.Update()

        # Color
        cols = np.zeros_like(points_array)
        dirs = self.data_ijk/np.linalg.norm(self.data_ijk, axis=-1)[:,np.newaxis]
        cols[0::2] = 255*np.abs(dirs)
        cols[1::2] = 255*np.abs(dirs)
        vtk_colors = ns.numpy_to_vtk(cols, deep=True, array_type=vtk.VTK_UNSIGNED_CHAR)
        vtk_colors.SetName("Colors")
        poly_data.GetPointData().SetScalars(vtk_colors)

        # Set actor
        actor = vtk.vtkActor()
        actor.SetMapper(poly_mapper)
        # actor.GetProperty().SetLineWidth(2)
        # actor.GetProperty().SetLighting(0)
        actor.GetProperty().SetAmbient(0.5)
        self.ren.AddActor(actor)

        # Draw extras
        utilvtk.draw_origin_dot(self.ren)        
        utilvtk.draw_outer_box(self.ren, *self.shape)
        utilvtk.draw_axes(self.ren, *self.shape)
        
        # Set cameras
        dist = 1.15*np.linalg.norm(self.shape)
        self.ren.GetActiveCamera().SetPosition(np.array([1,-1,1])*dist)
        self.ren.GetActiveCamera().SetViewUp([0,0,1])
    def update(self):
        if len(self.points) != len(self.stiffness):
            return
        points = self.points
        scalars = self.stiffness
        if np.all(self.points == self.oldPoints):
            return

        self.getNewPoints()
        # Project points into UV space
        texCoords = self.converter.toUVSpace(points)[:, 0:2]
        # Flip y coordinates to match image space
        texCoords[:, 1] *= -1
        texCoords[:, 1] += 1

        resolution = 100
        grid = generateGrid(0, 1, 0, 1, resolution)
        stiffMap = scipy.interpolate.griddata(texCoords,
                                              scalars,
                                              grid,
                                              method="linear",
                                              fill_value=-1)
        stiffMap = stiffMap.reshape(resolution, resolution)
        stiffMap[stiffMap == -1] = np.min(stiffMap[stiffMap != -1])
        # print(np.min(stiffMap), np.max(stiffMap), np.min(stiffMat), np.max(stiffMat))
        # Normalize
        # stiffMap[stiffMap < np.mean(stiffMap)] = np.mean(stiffMap)
        stiffMap -= np.min(stiffMap)
        stiffMap /= np.max(stiffMap)
        scale = 255 * 0.3
        r = np.clip(stiffMap * 3, 0, 1) * scale
        g = np.clip(stiffMap * 3 - 1, 0, 1) * scale
        b = np.clip(stiffMap * 3 - 2, 0, 1) * scale
        stiffImg = np.dstack((b, g, r)).astype(np.uint8)
        shape = self.texture.shape
        stiffImg = cv2.resize(stiffImg, (shape[1], shape[0]))
        img = self.texture.copy()
        img = np.subtract(img, stiffImg.astype(int))
        img = np.clip(img, 0, 255).astype(np.uint8)
        self.oldPoints = self.points

        if self.visualize:
            self.polyData.Reset()
            vtkPoints = vtk.vtkPoints()
            vtkCells = vtk.vtkCellArray()
            # colors = vtk.vtkUnsignedCharArray()
            # colors.SetNumberOfComponents(3)
            # colors.SetName("Colors")
            # minZ = np.min(scalars)
            # maxZ = np.max(scalars)
            # stiffness = (scalars - minZ) / (maxZ - minZ)
            # r = np.clip(stiffness * 3, 0, 1) * 255
            # g = np.clip(stiffness * 3 - 1, 0, 1) * 255
            # b = np.clip(stiffness * 3 - 2, 0, 1) * 255
            # for i, point in enumerate(np.hstack((points, r, g, b))):
            for i, point in enumerate(points):
                pointId = vtkPoints.InsertNextPoint(point)
                vtkCells.InsertNextCell(1)
                vtkCells.InsertCellPoint(pointId)
            self.polyData.SetPoints(vtkPoints)
            self.polyData.SetVerts(vtkCells)
            self.polyData.Modified()
            # self.polyData.GetPointData().SetScalars(colors)

            self.actor_organ.setTexture(img)
Exemple #54
0
print "made indexed image"

imageBounds = indexedImage.GetExtent()
dirs = (iPoint(-1, 0, 0), iPoint(1, 0, 0), iPoint(0, -1, 0), iPoint(0, 1, 0),
        iPoint(0, 0, -1), iPoint(0, 0, 1))

poly = {
    0: vtk.vtkPolyData(),
    1: vtk.vtkPolyData(),
    3: vtk.vtkPolyData(),
    5: vtk.vtkPolyData(),
    7: vtk.vtkPolyData()
}

faces = {
    0: vtk.vtkCellArray(),
    1: vtk.vtkCellArray(),
    3: vtk.vtkCellArray(),
    5: vtk.vtkCellArray(),
    7: vtk.vtkCellArray()
}

imageGeoFilter = vtk.vtkImageDataGeometryFilter()
imageGeoFilter.SetInput(indexedImage)
imageGeoFilter.SetExtent(imageBounds)
imagePoints = imageGeoFilter.GetOutput()
imagePoints.Update()

# loop over voxels and add faces that border different pixel groups to polydata
for i in xrange(indexedImage.GetNumberOfCells()):
    voxel = indexedImage.GetCell(i)
Exemple #55
0
def convert(polydata, config=None, verbose=True, coords_only=False):
    '''
  Takes a vtk polydata and converts it to TKO.
  '''

    # remove degenerate (single point) lines
    # see https://github.com/bostongfx/TRAKO/issues/8
    cleaner = vtk.vtkCleanPolyData()
    cleaner.PointMergingOff()
    cleaner.SetInputData(polydata)
    cleaner.Update()
    polydata = cleaner.GetOutputDataObject(0)
    polydata.SetVerts(vtk.vtkCellArray())

    points = numpy_support.vtk_to_numpy(polydata.GetPoints().GetData())
    lines = numpy_support.vtk_to_numpy(polydata.GetLines().GetData())
    number_of_streamlines = polydata.GetLines().GetNumberOfCells()

    #
    # scalars are per point
    #
    pointdata = polydata.GetPointData()
    number_of_scalars = pointdata.GetNumberOfArrays()
    scalars = []
    scalar_types = []
    scalar_names = []

    if not coords_only:

        for i in range(number_of_scalars):
            arr_name = pointdata.GetArrayName(i)
            scalar_names.append(str(arr_name))
            arr = pointdata.GetArray(i)

            # arr.ComputeScalarRange()

            # print(arr)

            number_of_components = arr.GetNumberOfComponents()
            data_type = arr.GetDataType()

            scalar_types.append((data_type, number_of_components))

            if verbose:
                print('Loading scalar', arr_name)
            scalars.append(numpy_support.vtk_to_numpy(arr))

    #
    # properties are per streamline
    #
    celldata = polydata.GetCellData()
    number_of_properties = celldata.GetNumberOfArrays()
    properties = []
    property_types = []
    property_names = []

    if not coords_only:

        for i in range(number_of_properties):
            arr_name = celldata.GetArrayName(i)
            property_names.append(str(arr_name))
            arr = celldata.GetArray(i)

            # print(i, arr)

            number_of_components = arr.GetNumberOfComponents()
            data_type = arr.GetDataType()

            property_types.append((data_type, number_of_components))

            if verbose:
                print('Loading property', arr_name)
            properties.append(numpy_support.vtk_to_numpy(arr))

    #
    # convert to streamlines
    #
    ordered_indices = []
    ordered_scalars = []
    i = 0
    current_fiber_id = 0
    line_length = 0
    # sanity check
    if len(lines) > 0:
        line_length = lines[i]
    line_index = 0

    lines_just_length = []

    while (line_index < number_of_streamlines):

        lines_just_length.append(line_length)

        i += line_length
        line_index += 1
        if line_index < number_of_streamlines:
            line_length = lines[i + line_index]

    #
    # now, create fiber cluster data structure
    #
    fibercluster = {
        'number_of_streamlines': number_of_streamlines,
        'per_vertex_data': collections.OrderedDict(),
        'indices': lines_just_length,  #ordered_indices
        'per_streamline_data': collections.OrderedDict()
    }

    fibercluster['per_vertex_data']['POSITION'] = {
        'componentType':
        vtkDataType_to_gltfComponentType[polydata.GetPoints().GetDataType()],
        'type':
        vtkNumberOfComponents_to_gltfType[
            polydata.GetPoints().GetData().GetNumberOfComponents()],
        'data':
        points  #ordered_vertices
    }

    for i, s in enumerate(scalar_names):

        vtkdatatype = scalar_types[i][0]
        vtknumberofcomponents = scalar_types[i][1]

        thisdata = scalars[i]  #[]

        if vtknumberofcomponents in vtkNumberOfComponents_to_gltfType:
            gltfType = vtkNumberOfComponents_to_gltfType[vtknumberofcomponents]
        else:
            # for now, we will just pass it through
            gltfType = vtknumberofcomponents

        fibercluster['per_vertex_data'][s] = {
            'componentType': vtkDataType_to_gltfComponentType[vtkdatatype],
            'type': gltfType,
            'data': thisdata
        }

    for i, p in enumerate(property_names):

        vtkdatatype = property_types[i][0]
        vtknumberofcomponents = property_types[i][1]

        thisdata = properties[i]  #[]

        if vtknumberofcomponents in vtkNumberOfComponents_to_gltfType:
            gltfType = vtkNumberOfComponents_to_gltfType[vtknumberofcomponents]
        else:
            # for now, we will just pass it through
            gltfType = vtknumberofcomponents

        fibercluster['per_streamline_data'][p] = {
            'componentType': vtkDataType_to_gltfComponentType[vtkdatatype],
            'type': gltfType,
            'data': thisdata
        }

    return fibercluster
import numpy

# Make a 32 x 32 grid
size = 32

# Define z values for the topography (random height)
topography = numpy.zeros([size, size])
for i in range(size):
    for j in range(size):
        topography[i][j] = random.randrange(0, 5)

# Define points, triangles and colors
colors = vtk.vtkUnsignedCharArray()
colors.SetNumberOfComponents(3)
points = vtk.vtkPoints()
triangles = vtk.vtkCellArray()

# Build the meshgrid manually
count = 0
for i in range(size - 1):
    for j in range(size - 1):

        z1 = topography[i][j]
        z2 = topography[i][j + 1]
        z3 = topography[i + 1][j]

        # Triangle 1
        points.InsertNextPoint(i, j, z1)
        points.InsertNextPoint(i, (j + 1), z2)
        points.InsertNextPoint((i + 1), j, z3)
Exemple #57
0

Vessel = vtkReader(sys.argv[2])

numberOfBranches = 0

f = open(sys.argv[1])
ar = f.read().split('\n')
polyData_Container = []
for i in range(0, len(ar)):
    v = ar[i].split(' ')
    if (v[0]):
        points = vtk.vtkPoints()
        polyLine = vtk.vtkPolyLine()
        polyLine.GetPointIds().SetNumberOfIds(int(v[0]))
        cells = vtk.vtkCellArray()
        polyData = vtk.vtkPolyData()
        vtkFloatArray = vtk.vtkFloatArray()
        vtkFloatArray.SetName("BranchIds")
        vtkFloatArray.SetNumberOfTuples(int(v[0]))

        for j in range(0, int(v[0])):
            vtkFloatArray.SetTuple1(j, numberOfBranches)

        for j in range(0, int(v[0])):
            points.InsertNextPoint(float(v[j * 3 + 1]), float(v[j * 3 + 2]),
                                   float(v[j * 3 + 3]))

        for j in range(0, int(v[0])):
            polyLine.GetPointIds().SetId(j, j)
Exemple #58
0
def clean(pdata):  # clean vtkPolyData

    geoFilter = vtk.vtkGeometryFilter(
    )  # transform any entry in conform vtk (vertex, line, triangle and tetra)
    geoFilter.SetInputData(pdata)
    geoFilter.Update()
    pdata.DeepCopy(geoFilter.GetOutput())

    numCells = pdata.GetNumberOfCells()  # store number of cells

    vert = vtk.vtkCellArray()  # see D1.py for explanation
    line = vtk.vtkCellArray()
    tri = vtk.vtkCellArray()
    tetra = vtk.vtkCellArray()

    for i in np.arange(numCells):
        cell = pdata.GetCell(i)
        if cell.GetCellType() == 1:  # cell is a vertex (VTK_VERTEX = 1)
            vert.InsertNextCell(cell)
        elif cell.GetCellType() == 3:  # cell is a line (VTK_LINE = 3)
            line.InsertNextCell(cell)
        elif cell.GetCellType() == 5:  # cell is a triangle (VTK_TRIANGLE = 5)
            tri.InsertNextCell(cell)
        elif cell.GetCellType() == 10:  # cell is a tetra (VTK_TETRA = 10)
            tetra.InsertNextCell(cell)

    numVertex = vert.GetNumberOfCells()
    numLines = line.GetNumberOfCells()
    numTri = tri.GetNumberOfCells()
    numTetra = tetra.GetNumberOfCells()

    if numTetra != 0:  # if there is tetra, delete vertex, line and triangle
        list = np.array([1, 3, 5])
    elif numTri != 0:  # elif there is triangle, delete vertex and line
        list = np.array([1, 3])
    elif numLines != 0:  # elif there is line, delete vertex
        list = np.array([1])
    else:  # elif there is only vertex, delete nothing
        list = np.array([])

    ids = vtk.vtkIdTypeArray()  # array to store cell id to remove
    ids.SetNumberOfComponents(1)  # array with 1 2nd-size

    it = pdata.NewCellIterator()  # new cell iterator
    it.InitTraversal()

    while not it.IsDoneWithTraversal():
        type = it.GetCellType()
        for i in np.arange(list.shape[0]):
            if list[i] == type:  # the type of cell is in the the vector of type to delete
                ids.InsertNextValue(it.GetCellId())

        it.GoToNextCell()

    selectionNode = vtk.vtkSelectionNode()  # object to select things
    selectionNode.SetFieldType(
        vtk.vtkSelectionNode.CELL)  # select things by cell
    selectionNode.SetContentType(
        vtk.vtkSelectionNode.INDICES)  # select things through indices
    selectionNode.SetSelectionList(ids)  # select things by reference from ids

    selection = vtk.vtkSelection()  # object to select things
    selection.AddNode(selectionNode)  # select things through selectionNode

    extractSelection = vtk.vtkExtractSelection()  # extract wich are selected
    extractSelection.SetInputData(0, pdata)  # input data (base is pdata)
    extractSelection.SetInputData(
        1, selection)  # input data to extract from base (selection)
    selectionNode.GetProperties().Set(
        vtk.vtkSelectionNode.INVERSE(),
        1)  # inverse selection (we want to keep wich are not selected)
    extractSelection.Update()  # update the extract selection

    geoFilter.SetInputData(
        extractSelection.GetOutput())  # convert any entry in vtkPolyData
    geoFilter.Update()
    pdata.DeepCopy(
        geoFilter.GetOutput())  # replace pdata with the new vtkPolyData

    return pdata
Exemple #59
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import vtk
import sys

# Test bounds computation for mixed cells in polydata.
# Create some points that are unused by any cell as well.
polyData = vtk.vtkPolyData()
pts = vtk.vtkPoints()
verts = vtk.vtkCellArray()
lines = vtk.vtkCellArray()
polys = vtk.vtkCellArray()
strips = vtk.vtkCellArray()

pts.SetNumberOfPoints(13)
pts.SetPoint(0, 0,0,0)
pts.SetPoint(1, 1,0,0)
pts.SetPoint(2, 2,0,0)
pts.SetPoint(3, 3,0,0)
pts.SetPoint(4, 4,0,0)
pts.SetPoint(5, 3,1,0)
pts.SetPoint(6, 4,1,0)
pts.SetPoint(7, 5,0,0)
pts.SetPoint(8, 6,0,0)
pts.SetPoint(9, 5,1,0)
pts.SetPoint(10, 6,1,0)
pts.SetPoint(11, 7,0,0)
pts.SetPoint(12, 8,0,0)

verts.InsertNextCell(1)
Exemple #60
0
    def testGlyphs(self):
        """Test if texturing of the glyphs works correctly."""
        # The Glyph
        cs = vtk.vtkCubeSource()
        cs.SetXLength(2.0)
        cs.SetYLength(1.0)
        cs.SetZLength(0.5)

        # Create input point data.
        pts = vtk.vtkPoints()
        pts.InsertPoint(0, (1, 1, 1))
        pts.InsertPoint(1, (0, 0, 0))
        pts.InsertPoint(2, (-1, -1, -1))
        polys = vtk.vtkCellArray()
        polys.InsertNextCell(1)
        polys.InsertCellPoint(0)
        polys.InsertNextCell(1)
        polys.InsertCellPoint(1)
        polys.InsertNextCell(1)
        polys.InsertCellPoint(2)
        pd = vtk.vtkPolyData()
        pd.SetPoints(pts)
        pd.SetPolys(polys)

        # Orient the glyphs as per vectors.
        vec = vtk.vtkFloatArray()
        vec.SetNumberOfComponents(3)
        vec.InsertTuple3(0, 1, 0, 0)
        vec.InsertTuple3(1, 0, 1, 0)
        vec.InsertTuple3(2, 0, 0, 1)
        pd.GetPointData().SetVectors(vec)

        # The glyph filter.
        g = vtk.vtkGlyph3D()
        g.SetScaleModeToDataScalingOff()
        g.SetVectorModeToUseVector()
        g.SetInputData(pd)
        g.SetSourceConnection(cs.GetOutputPort())

        m = vtk.vtkPolyDataMapper()
        m.SetInputConnection(g.GetOutputPort())
        a = vtk.vtkActor()
        a.SetMapper(m)

        # The texture.
        img_file = os.path.join(VTK_DATA_ROOT, "Data", "masonry.bmp")
        img_r = vtk.vtkBMPReader()
        img_r.SetFileName(img_file)
        t = vtk.vtkTexture()
        t.SetInputConnection(img_r.GetOutputPort())
        t.InterpolateOn()
        a.SetTexture(t)

        # Renderer, RenderWindow etc.
        ren = vtk.vtkRenderer()
        ren.SetBackground(0.5, 0.5, 0.5)
        ren.AddActor(a)

        ren.ResetCamera()
        cam = ren.GetActiveCamera()
        cam.Azimuth(-90)
        cam.Zoom(1.4)

        renWin = vtk.vtkRenderWindow()
        renWin.AddRenderer(ren)
        rwi = vtk.vtkRenderWindowInteractor()
        rwi.SetRenderWindow(renWin)
        rwi.Initialize()
        rwi.Render()