def Gen_uGrid(new_pt, new_fc): """ Generates a vtk unstructured grid given points and triangular faces""" ints = np.ones(len(new_fc), 'int')*3 cells = np.hstack((ints.reshape(-1, 1), np.vstack(new_fc))) # Generate vtk mesh # Convert points to vtkfloat object points = np.vstack(new_pt) vtkArray = VN.numpy_to_vtk(np.ascontiguousarray(points), deep=True)#, deep=True) points = vtk.vtkPoints() points.SetData(vtkArray) # Convert to vtk arrays tritype = vtk.vtkTriangle().GetCellType()*np.ones(len(new_fc), 'int') cell_type = np.ascontiguousarray(tritype).astype('uint8') cell_type = VN.numpy_to_vtk(cell_type, deep=True) offset = np.cumsum(np.hstack(ints + 1)) offset = np.ascontiguousarray(np.delete(np.insert(offset, 0, 0), -1)).astype('int64') # shift offset = VN.numpy_to_vtkIdTypeArray(offset, deep=True) cells = np.ascontiguousarray(np.hstack(cells).astype('int64')) vtkcells = vtk.vtkCellArray() vtkcells.SetCells(cells.shape[0], VN.numpy_to_vtkIdTypeArray(cells, deep=True)) # Create unstructured grid uGrid = vtk.vtkUnstructuredGrid() uGrid.SetPoints(points) uGrid.SetCells(cell_type, offset, vtkcells) return uGrid
def Gen_uGrid(new_pt, new_fc): """ Generates a vtk unstructured grid given points and triangular faces""" ints = np.ones(len(new_fc), 'int') * 3 cells = np.hstack((ints.reshape(-1, 1), np.vstack(new_fc))) # Generate vtk mesh # Convert points to vtkfloat object points = np.vstack(new_pt) vtkArray = VN.numpy_to_vtk(np.ascontiguousarray(points), deep=True) #, deep=True) points = vtk.vtkPoints() points.SetData(vtkArray) # Convert to vtk arrays tritype = vtk.vtkTriangle().GetCellType() * np.ones(len(new_fc), 'int') cell_type = np.ascontiguousarray(tritype).astype('uint8') cell_type = VN.numpy_to_vtk(cell_type, deep=True) offset = np.cumsum(np.hstack(ints + 1)) offset = np.ascontiguousarray(np.delete(np.insert(offset, 0, 0), -1)).astype('int64') # shift offset = VN.numpy_to_vtkIdTypeArray(offset, deep=True) cells = np.ascontiguousarray(np.hstack(cells).astype('int64')) vtkcells = vtk.vtkCellArray() vtkcells.SetCells(cells.shape[0], VN.numpy_to_vtkIdTypeArray(cells, deep=True)) # Create unstructured grid uGrid = vtk.vtkUnstructuredGrid() uGrid.SetPoints(points) uGrid.SetCells(cell_type, offset, vtkcells) return uGrid
def MakeuGrid(offset, cells, cell_type, nodes): """ Create VTK unstructured grid """ # Check inputs (necessary since offset and cells can int32) if offset.dtype != 'int64': offset = offset.astype(np.int64) if cells.dtype != 'int64': cells = cells.astype(np.int64) # Get number of cells ncells = len(cell_type) # Convert to vtk arrays cell_type = VN.numpy_to_vtk(cell_type, deep=True) offset = VN.numpy_to_vtkIdTypeArray(offset, deep=True) vtkcells = vtk.vtkCellArray() vtkcells.SetCells(ncells, VN.numpy_to_vtkIdTypeArray(cells, deep=True)) # Convert points to vtkfloat object vtkArray = VN.numpy_to_vtk(np.ascontiguousarray(nodes), deep=True) points = vtk.vtkPoints() points.SetData(vtkArray) # Create unstructured grid uGrid = vtk.vtkUnstructuredGrid() uGrid.SetPoints(points) uGrid.SetCells(cell_type, offset, vtkcells) return uGrid
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
def o3dp3dTovtkPCD(p3d): xyz = numpy.asarray(p3d.points) minH = xyz[:, 2].min() maxH = xyz[:, 2].max() #print("minh,maxh:",minH,maxH) count = len(xyz) #print(len(xyz.shape)) pcd = VtkPointCloud(minH, maxH, count) pcd.clearPoints() counter = numpy.size(xyz, 0) #print(counter) #test np to vtk array nCoords = xyz.shape[0] nElem = xyz.shape[1] #print("c,e",nCoords,nElem) #print("xyz",xyz) depth = xyz[:, 2] #print("depth",depth) #colors = numpy_support.numpy_to_vtk(rgb) vtkDepth = numpy_support.numpy_to_vtk(depth) cells_npy = numpy.vstack([ numpy.ones(nCoords, dtype=numpy.int64), numpy.arange(nCoords, dtype=numpy.int64) ]).T.flatten() #print("cells_npy",cells_npy) cells = vtk.vtkCellArray() cells.SetCells(nCoords, numpy_support.numpy_to_vtkIdTypeArray(cells_npy)) #print("cells",cells) vtkArray = numpy_support.numpy_to_vtk(xyz) verts = vtk.vtkPoints() verts.SetData(vtkArray) #print(vtkArray) pcd.setPoints(vtkArray, nCoords, numpy_support.numpy_to_vtkIdTypeArray(cells_npy), vtkDepth) return pcd
def selectImage(self): """Here just detect whether something was picked and pass the index (or empty list) to the output_link, then rely on the output_link callback to update the highlight actor and scroll the view to the correct index""" (x0,y0) = self.interactor.GetLastEventPosition() (x,y) = self.interactor.GetEventPosition() # DEBUG # print "start: ", x0,y0, " end: ", x,y picker = self.interactor.GetPicker() somethingPicked = picker.PickProp(x,y,self.renderer) if somethingPicked: pickedProp = picker.GetViewProp() index = self.assemblyList.index(pickedProp) else: index = -1 if index >= 0: scale_list = [self.scale_dict[index]] else: scale_list = [] print "scale picked in detail view: ", scale_list id_array = N.array(scale_list, dtype='int64') id_vtk = VN.numpy_to_vtkIdTypeArray(id_array, deep=True) self.output_link.GetCurrentSelection().GetNode(0).SetSelectionList(id_vtk) # This event should update selection highlight based on picked scale self.output_link.InvokeEvent("AnnotationChangedEvent")
def write_output(neuropil, verts, faces, vert_principal_curvatures, args): """save the surface mesh with pymesh Gaussian curvature and Gaussian curvature taken from my own second fundamental forms as a sanity check""" # construct polydata object with mesh verts and faces polydata = vtk.vtkPolyData() points = vtk.vtkPoints() points.SetData(numpy_to_vtk(verts)) polydata.SetPoints(points) insert_points = range(0, len(faces)*3, 3) faces_vtk_format = np.insert(faces.ravel(), insert_points, 3).astype(np.int) cells = vtk.vtkCellArray() cells.SetCells(faces.shape[0], numpy_to_vtkIdTypeArray(faces_vtk_format)) polydata.SetPolys(cells) # save pymesh and my gaussian curvatures, just as visual inspection my_gaussian_curv = np.prod(vert_principal_curvatures, axis=-1) polydata.GetPointData().AddArray(numpy_to_vtk(my_gaussian_curv)) neuropil.add_attribute("vertex_gaussian_curvature") pymesh_gaussian_curv = neuropil.get_attribute("vertex_gaussian_curvature") polydata.GetPointData().AddArray(numpy_to_vtk(pymesh_gaussian_curv)) # write output polydata.Modified() writer = vtk.vtkXMLPolyDataWriter() writer.SetFileName(args.mesh_output_path) writer.SetInputData(polydata) writer.Write()
def PointsToPolyData(points): """Create ``vtkPolyData`` from a numpy array of XYZ points Return: vtkPolyData : points with point-vertex cells """ __displayname__ = 'Points to PolyData' __type__ = 'filter' if points.ndim != 2: points = points.reshape((-1, 3)) npoints = points.shape[0] # Make VTK cells array cells = np.hstack((np.ones( (npoints, 1)), np.arange(npoints).reshape(-1, 1))) cells = np.ascontiguousarray(cells, dtype=np.int64) vtkcells = vtk.vtkCellArray() vtkcells.SetCells(npoints, nps.numpy_to_vtkIdTypeArray(cells, deep=True)) # Convert points to vtk object pts = vtk.vtkPoints() pts.SetData(nps.numpy_to_vtk(points)) # Create polydata pdata = vtk.vtkPolyData() pdata.SetPoints(pts) pdata.SetVerts(vtkcells) return pdata
def __init__(self, node, cell, celltype, celllocation=None, nodedata=None, celldata=None, meshdata=None, simulation=None): NN = node.shape[1] NC = cell.shape[0] points = vtk.vtkPoints() points.SetData(vnp.numpy_to_vtk(node)) cells = vtk.vtkCellArray() cells.SetCells(NC, vnp.numpy_to_vtkIdTypeArray(cell)) self.mesh = vtk.vtkUnstructuredGrid() self.mesh.SetPoints(points) self.mesh.SetCells(celltype, cells) self.queue = multiprocessing.Queue() self.process = multiprocessing.Process(None, simulation, args=(self.queue, ))
def readmesh(meshfile): ext = os.path.splitext(meshfile)[1] if ext == '.mim': # Just use points and polys, not normals etc origpd = meshutils.loadmesh(meshfile) points, polys = meshutils.polydata_to_points_polys(origpd, True) pdfl = meshutils.points_polys_to_polydata(points, polys) # Internal meshes use radiological coordinates xfm = vtk.vtkTransform() xfm.Scale(-1.0, 1.0, 1.0) xfm.Update() xfmf = vtk.vtkTransformPolyDataFilter() xfmf.SetTransform(xfm) xfmf.SetInputData(pdfl) xfmf.Update() pd = xfmf.GetOutput() elif ext == '.gii': mesh = gii.giftiio.read(meshfile) pd = vtk.vtkPolyData() pts = vtk.vtkPoints() pts.SetData(vtknp.numpy_to_vtk(mesh.darrays[0].data, deep=1)) pd.SetPoints(pts) polysarr = np.c_[ 3 * np.ones(mesh.darrays[1].data.shape[0], dtype='int')[:, None], np.array(mesh.darrays[1].data, dtype='int')] polys = vtk.vtkCellArray() polys.SetCells(mesh.darrays[1].data.shape[0], vtknp.numpy_to_vtkIdTypeArray(polysarr, deep=1)) pd.SetPolys(polys) else: raise Exception('Unrecognised extension ({0})'.format(ext)) return pd
def get_surface_by_id(surfaces, surface_map, surf_id): # create a mask for the surface ID and get vertices mask = (surface_map == surf_id) vertices = ns.vtk_to_numpy(surfaces.GetPoints().GetData())[mask] # find triangles with any vertex within the mask polydata = ns.vtk_to_numpy(surfaces.GetPolys().GetData()) triangles = np.vstack([polydata[1::4], polydata[2::4], polydata[3::4]]).T triangles = triangles[np.any(mask[triangles], axis=1)] triangles = triangles - np.min(triangles) # set all the vertices vtk_points = vtk.vtkPoints() vtk_points.SetData(ns.numpy_to_vtk(vertices, deep=True)) # set all the triangles vtk_triangles = np.hstack(np.c_[np.ones(len(triangles)).astype(np.int) * 3, triangles]) vtk_triangles = ns.numpy_to_vtkIdTypeArray(vtk_triangles, deep=True) vtk_cells = vtk.vtkCellArray() vtk_cells.SetCells(len(triangles), vtk_triangles) # create the surface polydata = vtk.vtkPolyData() polydata.SetPoints(vtk_points) polydata.SetPolys(vtk_cells) return polydata
def VertFacetoPoly(new_pt, new_fc): """ Creates a vtk polydata object given points and triangular faces """ # Convert points to vtkfloat object points = np.vstack(new_pt) vtkArray = VN.numpy_to_vtk(np.ascontiguousarray(points), deep=True) #, deep=True) points = vtk.vtkPoints() points.SetData(vtkArray) # Convert faces to vtk cells object ints = np.ones(len(new_fc), 'int') * 3 cells = np.hstack((ints.reshape(-1, 1), np.vstack(new_fc))) cells = np.ascontiguousarray(np.hstack(cells).astype('int64')) vtkcells = vtk.vtkCellArray() vtkcells.SetCells(cells.shape[0], VN.numpy_to_vtkIdTypeArray(cells, deep=True)) # Create polydata object pdata = vtk.vtkPolyData() pdata.SetPoints(points) pdata.SetPolys(vtkcells) # Remove duplicate verticies clean = vtk.vtkCleanPolyData() clean.ConvertPolysToLinesOff() clean.ConvertLinesToPointsOff() clean.ConvertStripsToPolysOff() if vtk.vtkVersion().GetVTKMajorVersion() > 5: clean.SetInputData(pdata) else: clean.SetInput(pdata) clean.Update() return clean.GetOutput()
def set_polydata_triangles(self, triangles): vtk_triangles = np.hstack( np.c_[np.ones(len(triangles)).astype(np.int) * 3, triangles]) vtk_triangles = ns.numpy_to_vtkIdTypeArray(vtk_triangles, deep=True) vtk_cells = vtk.vtkCellArray() vtk_cells.SetCells(len(triangles), vtk_triangles) self.get_polydata().SetPolys(vtk_cells)
def extractCellsByID(self, idlist, usePointIDs=False): """Return a new TetMesh composed of the specified subset of indices.""" selectionNode = vtk.vtkSelectionNode() if usePointIDs: selectionNode.SetFieldType(vtk.vtkSelectionNode.POINT) contcells = vtk.vtkSelectionNode.CONTAINING_CELLS() selectionNode.GetProperties().Set(contcells, 1) else: selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL) selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES) vidlist = numpy_to_vtkIdTypeArray(np.array(idlist).astype(np.int64)) selectionNode.SetSelectionList(vidlist) selection = vtk.vtkSelection() selection.AddNode(selectionNode) es = vtk.vtkExtractSelection() es.SetInputData(0, self._ugrid) es.SetInputData(1, selection) es.Update() tm_sel = TetMesh(es.GetOutput()) pr = vtk.vtkVolumeProperty() pr.DeepCopy(self.GetProperty()) tm_sel.SetProperty(pr) #assign the same transformation to the copy tm_sel.SetOrigin(self.GetOrigin()) tm_sel.SetScale(self.GetScale()) tm_sel.SetOrientation(self.GetOrientation()) tm_sel.SetPosition(self.GetPosition()) tm_sel._mapper.SetLookupTable(utils.ctf2lut(self)) return tm_sel
def VertFacetoPoly(new_pt, new_fc): """ Creates a vtk polydata object given points and triangular faces """ # Convert points to vtkfloat object points = np.vstack(new_pt) vtkArray = VN.numpy_to_vtk(np.ascontiguousarray(points), deep=True)#, deep=True) points = vtk.vtkPoints() points.SetData(vtkArray) # Convert faces to vtk cells object ints = np.ones(len(new_fc), 'int')*3 cells = np.hstack((ints.reshape(-1, 1), np.vstack(new_fc))) cells = np.ascontiguousarray(np.hstack(cells).astype('int64')) vtkcells = vtk.vtkCellArray() vtkcells.SetCells(cells.shape[0], VN.numpy_to_vtkIdTypeArray(cells, deep=True)) # Create polydata object pdata = vtk.vtkPolyData() pdata.SetPoints(points) pdata.SetPolys(vtkcells) # Remove duplicate verticies clean = vtk.vtkCleanPolyData() clean.ConvertPolysToLinesOff() clean.ConvertLinesToPointsOff() clean.ConvertStripsToPolysOff() if vtk.vtkVersion().GetVTKMajorVersion() > 5: clean.SetInputData(pdata) else: clean.SetInput(pdata) clean.Update() return clean.GetOutput()
def faces_to_vtkPolyData(coords, tri_elm, quad_elm): import numpy as np mesh = vtk.vtkPolyData() points = vtk.vtkPoints() points.SetData(numpy_to_vtk(coords.astype(np.float64), deep=1)) mesh.SetPoints(points) cells = vtk.vtkCellArray() ntri = tri_elm.shape[0] nqua = quad_elm.shape[0] ncells = ntri + nqua tris = np.c_[np.tile(3, ntri), tri_elm].flatten().astype(np.int64) quads = np.c_[np.tile(4, nqua), quad_elm].flatten().astype(np.int64) faces = np.concatenate((tris, quads)) faceIds = numpy_to_vtkIdTypeArray(faces, deep=1) cells.SetCells(ncells, faceIds) mesh.SetPolys(cells) return mesh
def __init__(self, nparray): super(VTKActorWrapper, self).__init__() self.nparray = nparray nCoords = nparray.shape[0] nElem = nparray.shape[1] self.verts = vtk.vtkPoints() self.cells = vtk.vtkCellArray() self.scalars = None self.pd = vtk.vtkPolyData() self.verts.SetData(vtk_np.numpy_to_vtk(nparray)) self.cells_npy = np.vstack([np.ones(nCoords,dtype=np.int64), np.arange(nCoords,dtype=np.int64)]).T.flatten() self.cells.SetCells(nCoords,vtk_np.numpy_to_vtkIdTypeArray(self.cells_npy)) self.pd.SetPoints(self.verts) self.pd.SetVerts(self.cells) self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputDataObject(self.pd) self.actor = vtk.vtkActor() self.actor.SetMapper(self.mapper) self.actor.GetProperty().SetRepresentationToPoints() self.actor.GetProperty().SetColor(0.0,1.0,0.0)
def initPolyData( self, np_points_data: Optional[np.ndarray] = None, **kwargs ): vtk_points = vtk.vtkPoints() self.polydata = vtk.vtkPolyData() self.polydata.SetPoints( vtk_points ) vertices = vtk.vtkCellArray() self.polydata.SetVerts(vertices) if np_points_data is not None: nPoints = int(np_points_data.size / 3) vtk_points_data = npsup.numpy_to_vtk( np_points_data.ravel(), deep=1 ) vtk_points_data.SetNumberOfComponents(3) vtk_points_data.SetNumberOfTuples(nPoints) vtk_points.SetData(vtk_points_data) np_index_seq = np.arange( 0, nPoints ) cell_sizes = np.ones_like( np_index_seq ) np_cell_data = np.dstack(( cell_sizes, np_index_seq) ) vtk_cell_data = npsup.numpy_to_vtkIdTypeArray( np_cell_data.ravel(), deep=1 ) vertices.SetCells( cell_sizes.size, vtk_cell_data ) self.set_point_colors( np.full( shape=[nPoints], fill_value= 0 ) ) self.polydata.Modified() self.points_modified = True if self.mapper is not None: self.mapper.SetInputData(self.polydata) self.mapper.Modified() if self.actor is not None: self.actor.Modified()
def cells_to_vtkUnstruct(coords, cell_elm): import numpy as np # import vtk # from vtk.util.numpy_support import numpy_to_vtk, numpy_to_vtkIdTypeArray # coords = fncConv.node_coords['stator'] # cell_elm = fncConv.cell_conn['stator'] mesh = vtk.vtkUnstructuredGrid() points = vtk.vtkPoints() points.SetData(numpy_to_vtk(coords.astype(np.float64), deep=1)) mesh.SetPoints(points) cells = vtk.vtkCellArray() ncells = cell_elm.shape[0] hexs = np.c_[np.tile(8, ncells), cell_elm].flatten().astype(np.int64) cell_type = vtk.vtkHexahedron().GetCellType() cell_types = np.tile(cell_type, (ncells, 1)) cellIds = numpy_to_vtkIdTypeArray(hexs, deep=1) cells.SetCells(ncells, cellIds) mesh.SetCells(cell_type, cells) return mesh
def ExtractSelectionPoints(self, ind): """ Returns a subset of an unstructured grid Parameters ---------- ind : np.ndarray Numpy array of point indices to be extracted. Returns ------- subgrid : vtki.UnstructuredGrid Subselected grid. """ # Convert to vtk indices if ind.dtype != np.int64: ind = ind.astype(np.int64) vtk_ind = numpy_to_vtkIdTypeArray(ind, deep=True) # Create selection objects selectionNode = vtk.vtkSelectionNode() selectionNode.SetFieldType(vtk.vtkSelectionNode.POINT) selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES) selectionNode.SetSelectionList(vtk_ind) selection = vtk.vtkSelection() selection.AddNode(selectionNode) # extract extractSelection = vtk.vtkExtractSelection() extractSelection.SetInputData(0, self) extractSelection.SetInputData(1, selection) extractSelection.Update() return UnstructuredGrid(extractSelection.GetOutput())
def get_vtkcellarray_from_vtkpoints(vtkpoints): """Creates the cells associated to each point taken individually :param vtkpoints: an object ``vtkPoints`` holding the set of points. :returns: the associated ``vtkCellArray`` The cells do not have any connectivity and are associated to unique points """ import vtk from vtk.util import numpy_support verts = vtk.vtkCellArray() if 0: # safe but slow way for index in range(vtkpoints.GetNumberOfPoints()): verts.InsertNextCell(1) verts.InsertCellPoint(index) else: # much faster # we have to create a list (1, id0, 1, id1, ....) where 1 indicates the number # of points in the cell, and idX is the id of the point array_cells = np.ones(vtkpoints.GetNumberOfPoints()) array_cells = np.vstack((array_cells, np.arange(vtkpoints.GetNumberOfPoints()))) array_cells = np.ascontiguousarray(array_cells.ravel(order='F'), dtype=np.int64) verts.SetCells(vtkpoints.GetNumberOfPoints(), numpy_support.numpy_to_vtkIdTypeArray(array_cells, deep=True)) return verts
def MeshfromVF(points, triangles_in, clean=True, deep_points=True): """ Generates mesh from points and triangles """ # Add face padding if necessary if triangles_in.shape[1] == 3: triangles = np.empty((triangles_in.shape[0], 4), dtype=np.int64) triangles[:, -3:] = triangles_in triangles[:, 0] = 3 else: triangles = triangles_in # Data checking if not points.flags['C_CONTIGUOUS']: points = np.ascontiguousarray(points) if not triangles.flags['C_CONTIGUOUS'] or triangles.dtype != 'int64': triangles = np.ascontiguousarray(triangles, 'int64') # Convert to vtk objects vtkpoints = MakevtkPoints(points, deep=deep_points) # Convert to a vtk array vtkcells = vtk.vtkCellArray() vtkcells.SetCells(triangles.shape[0], numpy_to_vtkIdTypeArray(triangles, deep=True)) mesh = vtkInterface.PolyData() mesh.SetPoints(vtkpoints) mesh.SetPolys(vtkcells) if clean: mesh.Clean() return mesh
def addPoints(self, nparray, color, opacity): self.nparray = nparray nCoords = nparray.shape[0] nElem = nparray.shape[1] self.verts = vtk.vtkPoints() self.cells = vtk.vtkCellArray() self.scalars = None self.pd = vtk.vtkPolyData() self.verts.SetData(vtk_np.numpy_to_vtk(nparray)) self.cells_npy = np.vstack([ np.ones(nCoords, dtype=np.int64), np.arange(nCoords, dtype=np.int64) ]).T.flatten() self.cells.SetCells(nCoords, vtk_np.numpy_to_vtkIdTypeArray(self.cells_npy)) self.pd.SetPoints(self.verts) self.pd.SetVerts(self.cells) self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputDataObject(self.pd) actor = vtk.vtkActor() actor.SetMapper(self.mapper) actor.GetProperty().SetRepresentationToPoints() actor.GetProperty().SetColor(color) actor.GetProperty().SetOpacity(opacity) self.actors.append(actor)
def MakePointMesh(points, deep=True): """ Convert numpy points to vtkPoints """ # Data checking if not points.flags['C_CONTIGUOUS']: points = np.ascontiguousarray(points) # Convert to vtk objects vtkpoints = vtk.vtkPoints() vtkpoints.SetData(numpy_to_vtk(points, deep=True)) npoints = points.shape[0] pcell = np.vstack((np.ones(npoints, dtype=np.int64), np.arange(npoints, dtype=np.int64))).ravel('F') # Convert to a vtk array vtkcells = vtk.vtkCellArray() vtkcells.SetCells(npoints, numpy_to_vtkIdTypeArray(pcell, deep=True)) # Create polydata object mesh = vtkInterface.PolyData() mesh.SetPoints(vtkpoints) mesh.SetPolys(vtkcells) # return cleaned mesh return mesh
def mesh_from_data(vertices, faces=empty([0, 0]), name=None, center_scale=False, deep=True): """Returns a VTK PolyData object from vertex and face ndarrays""" vertices = array(vertices, dtype=float) faces = array(faces, dtype='int64') polydata = vtkPolyData() # vertices points = vtkPoints() points.SetData(numpy_to_vtk(vertices, deep=deep)) polydata.SetPoints(points) # faces if isinstance(faces, ndarray) and faces.ndim == 2 and faces.shape[1] == 3: faces = concatenate((full([faces.shape[0], 1], 3), faces), axis=1) cells = vtkCellArray() nf = faces.shape[0] vtk_id_array = numpy_to_vtkIdTypeArray(faces.ravel(), deep=deep) cells.SetCells(nf, vtk_id_array) polydata.SetPolys(cells) return Mesh(vtk_mesh=polydata, center_scale=center_scale, name=name)
def numpy_to_vtk_cells(mat): """function to convert a numpy array of integers to a vtkCellArray Parameters ---------- mat : np.array MxN array to be converted Returns ------- vtk.vtkCellArray representing the numpy array, has the same shaped cell (N) at each of the M indices """ cells = vtk.vtkCellArray() # Seemingly, VTK may be compiled as 32 bit or 64 bit. # We need to make sure that we convert the trilist to the correct dtype # based on this. See numpy_to_vtkIdTypeArray() for details. isize = vtk.vtkIdTypeArray().GetDataTypeSize() req_dtype = np.int32 if isize == 4 else np.int64 n_elems = mat.shape[0] n_dim = mat.shape[1] cells.SetCells( n_elems, numpy_to_vtkIdTypeArray(np.hstack((np.ones(n_elems)[:, None] * n_dim, mat)).astype(req_dtype).ravel(), deep=1)) return cells
def initPolyData(self, np_points_data: Optional[np.ndarray] = None, **kwargs): vtk_points = vtk.vtkPoints() update_colors = kwargs.get('update_colors', False) vtk_color_data = None if update_colors or ( self.polydata is None ) else self.polydata.GetPointData().GetScalars('colors') self.polydata = vtk.vtkPolyData() self.polydata.SetPoints(vtk_points) vertices = vtk.vtkCellArray() self.polydata.SetVerts(vertices) if np_points_data is not None: nPoints = int(np_points_data.size / 3) vtk_points_data = npsup.numpy_to_vtk(np_points_data.ravel(), deep=1) vtk_points_data.SetNumberOfComponents(3) vtk_points_data.SetNumberOfTuples(nPoints) vtk_points.SetData(vtk_points_data) np_index_seq = np.arange(0, nPoints) cell_sizes = np.ones_like(np_index_seq) np_cell_data = np.dstack((cell_sizes, np_index_seq)) vtk_cell_data = npsup.numpy_to_vtkIdTypeArray(np_cell_data.ravel(), deep=1) vertices.SetCells(cell_sizes.size, vtk_cell_data) self.set_point_colors(data=vtk_color_data) self.polydata.Modified() self.points_modified = True if self.mapper is not None: self.mapper.SetInputData(self.polydata) self.mapper.Modified() if self.actor is not None: self.actor.Modified()
def write_to_vtk(self, fname, mesh): """ Notes ----- """ node, cell, cellType, NC = mesh.to_vtk() points = vtk.vtkPoints() points.SetData(vnp.numpy_to_vtk(node)) cells = vtk.vtkCellArray() cells.SetCells(NC, vnp.numpy_to_vtkIdTypeArray(cell)) vtkmesh = vtk.vtkUnstructuredGrid() vtkmesh.SetPoints(points) vtkmesh.SetCells(cellType, cells) pdata = vtkmesh.GetPointData() for key, val in mesh.nodedata.items(): d = vnp.numpy_to_vtk(val) d.SetName(key) pdata.AddArray(d) cdata = vtkmesh.GetCellData() for key, val in mesh.celldata.items(): d = vnp.numpy_to_vtk(val) d.SetName(key) cdata.AddArray(d) writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetFileName(fname) writer.SetInputData(vtkmesh) writer.Write()
def toVTK(self): """Convert the triangulated surface to a ``vtkUnstructuredGrid`` object """ import vtk from vtk.util import numpy_support as nps output = vtk.vtkUnstructuredGrid() pts = vtk.vtkPoints() cells = vtk.vtkCellArray() # Generate the points pts.SetNumberOfPoints(self.num_nodes) pts.SetData(nps.numpy_to_vtk(self.vertices)) # Generate the triangle cells cellConn = self.triangles.array cellsMat = np.concatenate((np.ones( (cellConn.shape[0], 1), dtype=np.int64) * cellConn.shape[1], cellConn), axis=1).ravel() cells = vtk.vtkCellArray() cells.SetNumberOfCells(cellConn.shape[0]) cells.SetCells(cellConn.shape[0], nps.numpy_to_vtkIdTypeArray(cellsMat, deep=True)) # Add to output output.SetPoints(pts) output.SetCells(vtk.VTK_TRIANGLE, cells) return output
def __init__(self, mesh_data, tri_scalars=None, scalars=None, color=None, opacity=None, fig="gcf"): super().__init__(fig) self.vectors = np.ascontiguousarray(normalise_mesh_type(mesh_data)) triangles = np.empty((len(self.vectors), 4), np.int64) triangles[:, 0] = 3 for i in range(3): triangles[:, i + 1] = np.arange(i, len(self.vectors) * 3, 3) triangles = triangles.ravel() points = self.points = vtk.vtkPoints() self.update_points() self.polydata.vtk_polydata.SetPoints(points) cells = vtk.vtkCellArray() cells.SetCells(len(triangles), numpy_to_vtkIdTypeArray(triangles)) self.polydata.vtk_polydata.SetPolys(cells) self.add_to_plot() self.temp.append(triangles) self.set_scalars(scalars) self.set_tri_scalars(tri_scalars) self.color_opacity(color, opacity)
def MeshfromVF(points, triangles, clean=True): """ Generates mesh from points and triangles """ if triangles.shape[1] == 3: triangles = np.hstack((3 * np.ones( (triangles.shape[0], 1), np.int), triangles)) # Data checking if not points.flags['C_CONTIGUOUS']: points = np.ascontiguousarray(points) if not triangles.flags['C_CONTIGUOUS'] or triangles.dtype != 'int64': triangles = np.ascontiguousarray(triangles, 'int64') # Convert to vtk objects vtkpoints = vtk.vtkPoints() vtkpoints.SetData(VN.numpy_to_vtk(points, deep=True)) # Convert to a vtk array vtkcells = vtk.vtkCellArray() vtkcells.SetCells(triangles.shape[0], VN.numpy_to_vtkIdTypeArray(triangles, deep=True)) # Create polydata object mesh = vtk.vtkPolyData() mesh.SetPoints(vtkpoints) mesh.SetPolys(vtkcells) # return cleaned mesh if clean: return CleanMesh(mesh) else: return mesh
def AddPoints(self, points, color=[1, 1, 1], psize=5): # Convert to points actor if points is a numpy array if type(points) == np.ndarray: npoints = points.shape[0] # Make VTK cells array cells = np.hstack((np.ones( (npoints, 1)), np.arange(npoints).reshape(-1, 1))) cells = np.ascontiguousarray(cells, dtype=np.int64) vtkcells = vtk.vtkCellArray() vtkcells.SetCells(npoints, VN.numpy_to_vtkIdTypeArray(cells, deep=True)) # Convert points to vtk object vtkPoints = MakevtkPoints(points) # Create polydata pdata = vtk.vtkPolyData() pdata.SetPoints(vtkPoints) pdata.SetVerts(vtkcells) # Create mapper and add lines mapper = vtk.vtkDataSetMapper() SetVTKInput(mapper, pdata) # Create Actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetPointSize(psize) actor.GetProperty().SetColor(color) actor.GetProperty().LightingOff() self.ren.AddActor(actor)
def update(self, path_to_npy: str, render: bool = False) -> None: points_np = np.load(path_to_npy) point_count = points_np.shape[0] if points_np.shape[1] > 3: self.points.SetData(vtk_np.numpy_to_vtk(points_np[:, 3:])) self.scalars = vtk_np.numpy_to_vtk((points_np[:, :3] * 255).astype(np.uint8)) self.scalars.SetName("Colors") else: self.points.SetData(vtk_np.numpy_to_vtk(points_np[:, :3])) cells_numpy = np.vstack([np.ones(point_count, dtype=np.int64), np.arange(point_count, dtype=np.int64)]).T.flatten() self.cells.SetCells(point_count, vtk_np.numpy_to_vtkIdTypeArray(cells_numpy)) self.points.Modified() self.cells.Modified() self.point_poly_data.SetPoints(self.points) self.point_poly_data.SetVerts(self.cells) if self.scalars is not None: self.point_poly_data.GetPointData().SetScalars(self.scalars) self.set_color_mode(self.color_mode) self.point_poly_data.Modified() if render: self.render_window.Render()
def make_vtk_skeleton_from_paths(verts, paths): cell_list = [] num_cells = 0 for p in paths: cell_list.append(len(p)) cell_list += p num_cells += 1 cell_array = np.array(cell_list) mesh = vtk.vtkPolyData() points = vtk.vtkPoints() points.SetData(numpy_to_vtk(verts, deep=1)) mesh.SetPoints(points) cells = vtk.vtkCellArray() # Seemingly, VTK may be compiled as 32 bit or 64 bit. # We need to make sure that we convert the trilist to the correct dtype # based on this. See numpy_to_vtkIdTypeArray() for details. isize = vtk.vtkIdTypeArray().GetDataTypeSize() req_dtype = np.int32 if isize == 4 else np.int64 cells.SetCells(num_cells, numpy_to_vtkIdTypeArray(cell_array, deep=1)) mesh.SetLines(cells) return mesh
def ScaleSelectionCallback(self, caller, event): # This will contain a scale value from detail_image_flow, which should # only exist if there is also a highlight_selection from image_flow. # Here combine those two pieces of information to select the correct tree # node corresponding to that pedigree_id highlight and scale value # This call doesn't make sense if there isn't a highlight link # since it follows that highlighted individual to the selected scale if self.highlight_link is None: return # Don't want to update if this is an internal call if self.scale_internal_call: self.scale_internal_call = False return # The content type is Index for now... scaleSel = caller.GetCurrentSelection() # Note: Empty selection should still contain a node, but no tuples if (scaleSel.GetNumberOfNodes() > 0) and (scaleSel.GetNode(0).GetSelectionList().GetNumberOfTuples() > 0): # This should only contain a single value or none scaleVal = scaleSel.GetNode(0).GetSelectionList().GetValue(0) print "Scale value from detail to icicle: ", scaleVal # Highlight should also contain a single pedigree id... pedSel = self.highlight_link.GetCurrentSelection() pedIdVal = pedSel.GetNode(0).GetSelectionList().GetValue(0) print "Pedigree ID value right now in icicle highlight", pedIdVal # NOTE: Accessing member variable nodes_at_scale = N.nonzero(self.ds.Scales==scaleVal)[0].tolist() for node_id in nodes_at_scale: if (self.ds.PointsInNet[node_id]==pedIdVal).any(): # Assuming for now that this is a cell "Index", so getting pedigree ID sel = vtk.vtkSelection() node = vtk.vtkSelectionNode() node.SetFieldType(0) # Cell node.SetContentType(4) # Indices id_array = N.array([node_id], dtype='int64') id_vtk = VN.numpy_to_vtkIdTypeArray(id_array, deep=True) node.SetSelectionList(id_vtk) sel.AddNode(node) # Note: When selection is cleared, the current selection does NOT contain any nodes self.areapoly1.Update() cs = vtk.vtkConvertSelection() pedIdSelection = cs.ToPedigreeIdSelection(sel, self.areapoly1.GetOutput()) pedIdSelection.GetNode(0).SetFieldType(3) # convert to vertext selection # Copy converted selection to output annotation link (fires AnnotationChangedEvent) self.output_link.SetCurrentSelection(pedIdSelection) self.applycolors1.Update() self.renWin.Render()
def updateVertices( self, **args ): self.vertices = vtk.vtkCellArray() if isNone(self.np_index_seq): wait = args.get( 'wait', False ) if wait: self.waitForData( ExecutionDataPacket.INDICES ) else: return cell_sizes = numpy.ones_like( self.np_index_seq ) self.np_cell_data = numpy.dstack( ( cell_sizes, self.np_index_seq ) ).flatten() self.vtk_cell_data = numpy_support.numpy_to_vtkIdTypeArray( self.np_cell_data ) self.vertices.SetCells( cell_sizes.size, self.vtk_cell_data ) self.polydata.SetVerts(self.vertices)
def writeVTK(mesh, fileName, models=None): """ Function to write a VTU file from a SimPEG TreeMesh and model. """ import vtk from vtk import vtkXMLUnstructuredGridWriter as Writer, VTK_VERSION from vtk.util.numpy_support import numpy_to_vtk, numpy_to_vtkIdTypeArray if str(type(mesh)).split()[-1][1:-2] not in 'SimPEG.Mesh.TreeMesh.TreeMesh': raise IOError('mesh is not a SimPEG TreeMesh.') # Make the data parts for the vtu object # Points mesh.number() ptsMat = mesh._gridN + mesh.x0 vtkPts = vtk.vtkPoints() vtkPts.SetData(numpy_to_vtk(ptsMat,deep=True)) # Cells cellConn = np.array([c.nodes for c in mesh],dtype=np.int64) cellsMat = np.concatenate((np.ones((cellConn.shape[0],1),dtype=np.int64)*cellConn.shape[1],cellConn),axis=1).ravel() cellsArr = vtk.vtkCellArray() cellsArr.SetNumberOfCells(cellConn.shape[0]) cellsArr.SetCells(cellConn.shape[0],numpy_to_vtkIdTypeArray(cellsMat,deep=True)) # Make the object vtuObj = vtk.vtkUnstructuredGrid() vtuObj.SetPoints(vtkPts) vtuObj.SetCells(vtk.VTK_VOXEL,cellsArr) # Add the level of refinement as a cell array cellSides = np.array([np.array(vtuObj.GetCell(i).GetBounds()).reshape((3,2)).dot(np.array([-1, 1])) for i in np.arange(vtuObj.GetNumberOfCells())]) uniqueLevel, indLevel = np.unique(np.prod(cellSides,axis=1),return_inverse=True) refineLevelArr = numpy_to_vtk(indLevel.max() - indLevel,deep=1) refineLevelArr.SetName('octreeLevel') vtuObj.GetCellData().AddArray(refineLevelArr) # Assign the model('s) to the object if models is not None: for item in models.iteritems(): # Convert numpy array vtkDoubleArr = numpy_to_vtk(item[1],deep=1) vtkDoubleArr.SetName(item[0]) vtuObj.GetCellData().AddArray(vtkDoubleArr) # Make the writer vtuWriteFilter = Writer() if float(VTK_VERSION.split('.')[0]) >=6: vtuWriteFilter.SetInputData(vtuObj) else: vtuWriteFilter.SetInput(vtuObj) vtuWriteFilter.SetFileName(fileName) # Write the file vtuWriteFilter.Update()
def ImageFlowSelectionChanged(self): """Routine for adding pedigree ID to output annotation link selection list when selection has been changed in image flow. Only allowing single selection for now.""" if self.highlightIndex >= 0: ped_id_list = [self.pedigree_id_dict[self.highlightIndex]] else: ped_id_list = [] id_array = N.array(ped_id_list, dtype='int64') id_vtk = VN.numpy_to_vtkIdTypeArray(id_array, deep=True) self.output_link.GetCurrentSelection().GetNode(0).SetSelectionList(id_vtk) self.output_link.InvokeEvent("AnnotationChangedEvent")
def polydata_from_numpy(coords): """ Converts Numpy Array to vtkPolyData Parameters ---------- coords: array, shape= [number of points, point features] array containing the point cloud in which each point has three coordinares [x, y, z] and none, one or three values corresponding to colors. Returns: -------- PolyData: vtkPolyData concrete dataset represents vertices, lines, polygons, and triangle strips """ Npts, Ndim = np.shape(coords) Points = vtkPoints() ntype = get_numpy_array_type(Points.GetDataType()) coords_vtk = numpy_to_vtk(np.asarray(coords[:,0:3], order='C',dtype=ntype), deep=1) Points.SetNumberOfPoints(Npts) Points.SetData(coords_vtk) Cells = vtkCellArray() ids = np.arange(0,Npts, dtype=np.int64).reshape(-1,1) IDS = np.concatenate([np.ones(Npts, dtype=np.int64).reshape(-1,1), ids],axis=1) ids_vtk = numpy_to_vtkIdTypeArray(IDS, deep=True) Cells.SetNumberOfCells(Npts) Cells.SetCells(Npts,ids_vtk) if Ndim == 4: color = [128]*len(coords) color = np.c_[color, color, color] elif Ndim == 6: color = coords[:,3:] else: color = [[128, 128, 128]]*len(coords) color_vtk = numpy_to_vtk( np.ascontiguousarray(color, dtype=get_vtk_to_numpy_typemap()[VTK_UNSIGNED_CHAR]), deep=True) color_vtk.SetName("colors") PolyData = vtkPolyData() PolyData.SetPoints(Points) PolyData.SetVerts(Cells) PolyData.GetPointData().SetScalars(color_vtk) return PolyData
def ply_exporter(mesh, file_path, binary=False, **kwargs): r""" Given a file path to write in to write out the mesh data. No value is returned. Only file paths are supported and if a file handle is passed it will be ignored and a warning will be raised. Note that this does not save out textures of textured images, and so should not be used in isolation. Parameters ---------- file_path : `str` The full path where the obj will be saved out. mesh : :map:`TriMesh` Any subclass of :map:`TriMesh`. If :map:`TexturedTriMesh` texture coordinates will be saved out. Note that :map:`ColouredTriMesh` will only have shape data saved out, as .PLY doesn't robustly support per-vertex colour information. binary: `bool`, optional Specify whether to format output in binary or ascii, defaults to False """ import vtk from vtk.util.numpy_support import numpy_to_vtk, numpy_to_vtkIdTypeArray file_path = _enforce_only_paths_supported(file_path, 'PLY') polydata = vtk.vtkPolyData() points = vtk.vtkPoints() points.SetData(numpy_to_vtk(mesh.points)) polydata.SetPoints(points) cells = vtk.vtkCellArray() counts = np.empty((mesh.trilist.shape[0], 1), dtype=np.int) counts.fill(3) tris = np.concatenate((counts, mesh.trilist), axis=1) cells.SetCells(mesh.trilist.shape[0], numpy_to_vtkIdTypeArray(tris)) polydata.SetPolys(cells) if isinstance(mesh, TexturedTriMesh): pointdata = polydata.GetPointData() pointdata.SetTCoords(numpy_to_vtk(mesh.tcoords.points)) ply_writer = vtk.vtkPLYWriter() ply_writer.SetFileName(str(file_path)) ply_writer.SetInputData(polydata) if not binary: ply_writer.SetFileTypeToASCII() else: ply_writer.SetFileTypeToBinary() ply_writer.Update() ply_writer.Write()
def manuallySelectScale(self, index): """Here just detect whether something was picked and pass the index (or empty list) to the output_link, then rely on the output_link callback to update the highlight actor and scroll the view to the correct index""" if index >= 0: scale_list = [self.scale_dict[index]] else: scale_list = [] id_array = N.array(scale_list, dtype='int64') id_vtk = VN.numpy_to_vtkIdTypeArray(id_array, deep=True) self.output_link.GetCurrentSelection().GetNode(0).SetSelectionList(id_vtk) # This event should update selection highlight based on picked scale self.output_link.InvokeEvent("AnnotationChangedEvent")
def build_vtk_polydata(self): vtkPolyData = vtk.vtkPolyData() vtkPoints = vtk.vtkPoints() vtkCells = vtk.vtkCellArray() vtkPolyData.SetPoints(vtkPoints) vtkPolyData.SetVerts(vtkCells) num_points = self.xyz.shape[0] vtk_data = converter.numpy_to_vtk(self.xyz) vtkPoints.SetNumberOfPoints(num_points) vtkPoints.SetData(vtk_data) vtkCells.SetCells(num_points, converter.numpy_to_vtkIdTypeArray(self.np_cells, deep=1)) return (vtkPolyData, vtkPoints, vtkCells)
def updateSelection(self, selectedIds): if len(selectedIds)==0: return Ids = VN.numpy_to_vtkIdTypeArray(np.array(selectedIds), deep=True) node = vtk.vtkSelectionNode() node.SetContentType(vtk.vtkSelectionNode.INDICES) node.SetFieldType(vtk.vtkSelectionNode.POINT) node.SetSelectionList(Ids) selection = vtk.vtkSelection() selection.AddNode(node) self.annotationLink.SetCurrentSelection(selection) self.widget.Render()
def HighlightSelectionCallback(self, caller, event): # Need to convert pedigree IDs that we get back from image_flow into indices annSel = caller.GetCurrentSelection() # Note: When selection is cleared, the current selection does NOT contain any nodes if annSel.GetNumberOfNodes() > 0: idxVtk = annSel.GetNode(0).GetSelectionList() if idxVtk.GetNumberOfTuples() > 0: cs = vtk.vtkConvertSelection() idxSelection = cs.ToIndexSelection(annSel, self.table) # Copy converted selection to output annotation link (fires AnnotationChangedEvent) self.highlight_link_idxs.SetCurrentSelection(idxSelection) else: empty_arr = N.array([],dtype='int64') empty_vtk = VN.numpy_to_vtkIdTypeArray(empty_arr, deep=True) self.highlight_link_idxs.GetCurrentSelection().GetNode(0).SetSelectionList(empty_vtk) self.chartView.Render()
def extract_using_vtk(self,ids): node=vtk.vtkSelectionNode() sel = vtk.vtkSelection() node.GetProperties().Set(vtk.vtkSelectionNode.CONTENT_TYPE(),\ vtk.vtkSelectionNode.INDICES) node.GetProperties().Set(vtk.vtkSelectionNode.FIELD_TYPE(),\ vtk.vtkSelectionNode.POINT) #Create Id Array with point Ids for each cluster vtk_ids=numpy_to_vtkIdTypeArray(ids) node.SetSelectionList(vtk_ids) #sel_filter = vtk.vtkExtractSelectedPolyDataIds() sel_filter = vtk.vtkExtractSelection() sel_filter.SetInput(0,self._in_vtk) sel_filter.SetInput(1,sel) sel_filter.Update() return sel_filter.GetOutput()
def polydata_from_numpy(coords, color): """ :param coords: :param color: :return: """ Npts, Ndim = np.shape(coords) Points = vtkPoints() ntype = get_numpy_array_type(Points.GetDataType()) coords_vtk = numpy_to_vtk(np.asarray(coords, order='C',dtype=ntype), deep=1) Points.SetNumberOfPoints(Npts) Points.SetData(coords_vtk) Cells = vtkCellArray() ids = np.arange(0,Npts, dtype=np.int64).reshape(-1,1) IDS = np.concatenate([np.ones(Npts, dtype=np.int64).reshape(-1,1), ids],axis=1) ids_vtk = numpy_to_vtkIdTypeArray(IDS, deep=True) Cells.SetNumberOfCells(Npts) Cells.SetCells(Npts,ids_vtk) if color is None: [[128, 128, 128]]*len(coords) size = np.shape(color) if len(size)==1: color = [128]*len(coords) color = np.c_[color, color, color] color_vtk = numpy_to_vtk( np.ascontiguousarray(color, dtype=get_vtk_to_numpy_typemap()[VTK_UNSIGNED_CHAR]), deep=True ) color_vtk.SetName("colors") PolyData = vtkPolyData() PolyData.SetPoints(Points) PolyData.SetVerts(Cells) PolyData.GetPointData().SetScalars(color_vtk) return PolyData
def fileOpen(self): openFilesDefaultPath = '' # This dialog allows multiple files to be selected at once # If only want a single file, change to fileName = QtGui.QFileDialog.getOpenFileName(...) # Just change the string in the next to last line of the method for different file types file = QtGui.QFileDialog.getOpenFileName(self, "Load Saved Matlab File", self.last_data_dir, "All Files (*);;Matlab Files (*.mat)") if file: # Clear out selections empty_arr = N.array([],dtype='int64') empty_vtk = VN.numpy_to_vtkIdTypeArray(empty_arr, deep=True) self.pc_class.GetAnnotationLink().GetCurrentSelection().GetNode(0).SetSelectionList(empty_vtk) self.pc_class.GetAnnotationLink().InvokeEvent("AnnotationChangedEvent") self.if_class.GetOutputAnnotationLink().GetCurrentSelection().GetNode(0).SetSelectionList(empty_vtk) self.if_class.GetOutputAnnotationLink().InvokeEvent("AnnotationChangedEvent") self.nf_class.GetOutputAnnotationLink().GetCurrentSelection().GetNode(0).SetSelectionList(empty_vtk) self.nf_class.GetOutputAnnotationLink().InvokeEvent("AnnotationChangedEvent") self.ds.SetFileName(str(file)) self.ds.LoadData() self.setWindowTitle(QtGui.QApplication.translate("MainWindow", "Multi-scale SVD :: Wavelets", None, QtGui.QApplication.UnicodeUTF8)) self.ui.actionWavelet.setChecked(True) # Remove old color_by_array menu items for action in self.color_array_actions_list: self.ui.menuPlot_Colors.removeAction(action) self.colorActionGroup.removeAction(action) QtCore.QObject.connect(action, QtCore.SIGNAL("triggered()"), self.setColorByArray) # Add new color_by_array menu items self.generate_color_array_actions() self.pc_class.SetColorByArrayOff() self.xy_class.SetColorByArrayOff() self.ice_class.SetColorByArrayOff() self.ice_class.LoadData() self.ui.qvtkWidget_0.update() self.ui.qvtkWidget_1.update()
def trimesh_to_vtk(trimesh): r"""Return a `vtkPolyData` representation of a :map:`TriMesh` instance Parameters ---------- trimesh : :map:`TriMesh` The menpo :map:`TriMesh` object that needs to be converted to a `vtkPolyData` Returns ------- `vtk_mesh` : `vtkPolyData` A VTK mesh representation of the Menpo :map:`TriMesh` data Raises ------ ValueError: If the input trimesh is not 3D. """ import vtk from vtk.util.numpy_support import numpy_to_vtk, numpy_to_vtkIdTypeArray if trimesh.n_dims != 3: raise ValueError('trimesh_to_vtk() only works on 3D TriMesh instances') mesh = vtk.vtkPolyData() points = vtk.vtkPoints() points.SetData(numpy_to_vtk(trimesh.points, deep=1)) mesh.SetPoints(points) cells = vtk.vtkCellArray() # Seemingly, VTK may be compiled as 32 bit or 64 bit. # We need to make sure that we convert the trilist to the correct dtype # based on this. See numpy_to_vtkIdTypeArray() for details. isize = vtk.vtkIdTypeArray().GetDataTypeSize() req_dtype = np.int32 if isize == 4 else np.int64 cells.SetCells(trimesh.n_tris, numpy_to_vtkIdTypeArray( np.hstack((np.ones(trimesh.n_tris)[:, None] * 3, trimesh.trilist)).astype(req_dtype).ravel(), deep=1)) mesh.SetPolys(cells) return mesh
def _repr_vtk_(self): import vtk from vtk.util.numpy_support import numpy_to_vtk, numpy_to_vtkIdTypeArray from openalea.container import array_dict if len(self.triangles) > 0: vtk_mesh = vtk.vtkPolyData() vtk_points = vtk.vtkPoints() vtk_point_data = vtk.vtkDoubleArray() vtk_triangles = vtk.vtkCellArray() vtk_triangle_data = vtk.vtkDoubleArray() if len(self.triangle_data)>0 and np.array(self.triangle_data.values()).ndim > 1: if np.array(self.triangle_data.values()).ndim==2: vtk_point_data.SetNumberOfComponents(np.array(self.triangle_data.values()).shape[1]) elif np.array(self.triangle_data.values()).ndim==3: vtk_point_data.SetNumberOfComponents(np.array(self.triangle_data.values()).shape[1]*np.array(self.triangle_data.values()).shape[2]) mesh_points = [] positions = array_dict(self.points) for t in self.triangles.keys(): triangle_center = positions.values(self.triangles[t]).mean(axis=0) tid = vtk_points.InsertNextPoint(triangle_center) mesh_points.append(tid) if self.triangle_data.has_key(t): if isiterable(self.triangle_data[t]): if np.array(self.triangle_data[t]).ndim==1: vtk_point_data.InsertTuple(tid,self.triangle_data[t]) else: vtk_point_data.InsertTuple(tid,np.concatenate(self.triangle_data[t])) mesh_points = array_dict(mesh_points,self.triangles.keys()) vtk_mesh.SetPoints(vtk_points) if np.array(self.triangle_data.values()).ndim==2: vtk_mesh.GetPointData().SetVectors(vtk_point_data) elif np.array(self.triangle_data.values()).ndim==3: vtk_mesh.GetPointData().SetTensors(vtk_point_data) else: from time import time start_time = time() double_array = vtk.vtkDoubleArray() double_array = numpy_to_vtk(np.array(self.points.values()), deep=True, array_type=vtk.VTK_DOUBLE) vtk_points.SetData(double_array) if self.point_data.has_key(self.points.keys()[0]): if isiterable(self.point_data[self.points.keys()[0]]): vtk_point_data = numpy_to_vtk(np.array([v[0] for v in self.point_data.values()]), deep=True, array_type=vtk.VTK_DOUBLE) else: vtk_point_data = numpy_to_vtk(np.array(self.point_data.values()), deep=True, array_type=vtk.VTK_DOUBLE) vtk_point_data.SetNumberOfComponents(1) # mesh_points = [] # for p in self.points.keys(): # pid = vtk_points.InsertNextPoint(self.points[p]) # mesh_points.append(pid) # if self.point_data.has_key(p): # if isiterable(self.point_data[p]): # vtk_point_data.InsertValue(pid,self.point_data[p][0]) # else: # vtk_point_data.InsertValue(pid,self.point_data[p]) mesh_points = array_dict(np.arange(len(self.points)),self.points.keys()) # mesh_points = array_dict(mesh_points,self.points.keys()) if len(self.point_data) > 0: vtk_mesh.GetPointData().SetScalars(vtk_point_data) triangles_vtk = np.concatenate([3*np.ones(len(self.triangles),int)[:,np.newaxis],mesh_points.values(np.array(self.triangles.values()))],axis=1) vtk_ids = numpy_to_vtkIdTypeArray(triangles_vtk, deep=True) vtk_triangles.SetCells(len(self.triangles), vtk_ids) if self.triangle_data.has_key(self.triangles.keys()[0]): if isiterable(self.triangle_data[self.triangles.keys()[0]]): if np.array(self.triangle_data[self.triangles.keys()[0]]).ndim==1: vtk_triangle_data = numpy_to_vtk(np.array(self.triangle_data.values()), deep=True, array_type=vtk.VTK_DOUBLE) else: vtk_triangle_data = numpy_to_vtk(np.array([np.concatenate(v) for v in self.triangle_data.values()]), deep=True, array_type=vtk.VTK_DOUBLE) else: vtk_triangle_data = numpy_to_vtk(np.array(self.triangle_data.values()), deep=True, array_type=vtk.VTK_DOUBLE) # for t in self.triangles.keys(): # poly = vtk_triangles.InsertNextCell(3) # for i in xrange(3): # vtk_triangles.InsertCellPoint(mesh_points[self.triangles[t][i]]) # if self.triangle_data.has_key(t): # if isiterable(self.triangle_data[t]): # if np.array(self.triangle_data[t]).ndim==1: # vtk_triangle_data.InsertTuple(poly,self.triangle_data[t]) # else: # vtk_triangle_data.InsertTuple(poly,np.concatenate(self.triangle_data[t])) # # vtk_triangle_data.InsertValue(poly,self.triangle_data[t][0]) # else: # vtk_triangle_data.InsertValue(poly,self.triangle_data[t]) vtk_mesh.SetPoints(vtk_points) vtk_mesh.SetPolys(vtk_triangles) if len(self.triangle_data) > 0: vtk_mesh.GetCellData().SetScalars(vtk_triangle_data) end_time = time() print "--> Converting to VTK PolyData [",end_time-start_time,"s]" return vtk_mesh elif len(self.edges) > 0: vtk_mesh = vtk.vtkPolyData() vtk_points = vtk.vtkPoints() vtk_point_data = vtk.vtkDoubleArray() vtk_lines = vtk.vtkCellArray() vtk_line_data = vtk.vtkDoubleArray() mesh_points = [] for p in self.points.keys(): pid = vtk_points.InsertNextPoint(self.points[p]) mesh_points.append(pid) if self.point_data.has_key(p): if isiterable(self.point_data[p]): vtk_point_data.InsertValue(pid,self.point_data[p][0]) else: vtk_point_data.InsertValue(pid,self.point_data[p]) mesh_points = array_dict(mesh_points,self.points.keys()) if len(self.point_data) > 0: vtk_mesh.GetPointData().SetScalars(vtk_point_data) for e in self.edges.keys(): line = vtk.vtkLine() line.GetPointIds().SetId(0,mesh_points[self.edges[e][0]]) line.GetPointIds().SetId(1,mesh_points[self.edges[e][1]]) edge = vtk_lines.InsertNextCell(line) if self.edge_data.has_key(e): if isiterable(self.edge_data[e]): vtk_line_data.InsertValue(edge,self.edge_data[e][0]) else: vtk_line_data.InsertValue(edge,self.edge_data[e]) else: vtk_line_data.InsertValue(edge,0) vtk_mesh.SetPoints(vtk_points) vtk_mesh.SetLines(vtk_lines) vtk_mesh.GetCellData().SetScalars(vtk_line_data) return vtk_mesh else: vtk_mesh = vtk.vtkPolyData() vtk_points = vtk.vtkPoints() vtk_cells = vtk.vtkDoubleArray() if len(self.point_data)>0 and np.array(self.point_data.values()).ndim==2: vtk_cells.SetNumberOfComponents(np.array(self.point_data.values()).shape[1]) elif len(self.point_data)>0 and np.array(self.point_data.values()).ndim==3: vtk_cells.SetNumberOfComponents(np.array(self.point_data.values()).shape[1]*np.array(self.point_data.values()).shape[2]) for p in self.points.keys(): pid = vtk_points.InsertNextPoint(self.points[p]) if self.point_data.has_key(p): if isiterable(self.point_data[p]): if np.array(self.point_data[p]).ndim==1: cell = vtk_cells.InsertNextTuple(self.point_data[p]) else: cell = vtk_cells.InsertNextTuple(np.concatenate(self.point_data[p])) else: vtk_cells.InsertValue(pid,self.point_data[p]) else: vtk_cells.InsertValue(pid,p) vtk_mesh.SetPoints(vtk_points) if len(self.point_data)>0 and np.array(self.point_data.values()).ndim==2: vtk_mesh.GetPointData().SetVectors(vtk_cells) elif len(self.point_data)>0 and np.array(self.point_data.values()).ndim==3: vtk_mesh.GetPointData().SetTensors(vtk_cells) else: vtk_mesh.GetPointData().SetScalars(vtk_cells) return vtk_mesh
def selectNode(self): # (x0,y0) = self.interactor.GetLastEventPosition() (x,y) = self.interactor.GetEventPosition() cellPicker = vtk.vtkCellPicker() someCellPicked = cellPicker.Pick(x,y,0,self.renderer) pickedCellId = cellPicker.GetCellId() propPicker = vtk.vtkPropPicker() somePropPicked = propPicker.PickProp(x,y,self.renderer) pickedProp = propPicker.GetViewProp() navigated = False # NOTE: For some reason, sometimes on switching data sets # we're getting to the print statement with scale_list undefined # so I added this initialization... scale_list = [] # Navigate with buttons if somePropPicked and (pickedProp != self.icicle_actor): # First, test whether there is a current selection because we can only move if # there was a selection to move in the first place if self.output_link.GetCurrentSelection().GetNumberOfNodes() > 0: # If so, get the current pedigree_id prev_ped_vtk = self.output_link.GetCurrentSelection().GetNode(0).GetSelectionList() # NOTE: Counting on a single ID prev_ped_id = prev_ped_vtk.GetValue(0) # Now figure out which menu item was picked for ii, m_actor in enumerate(self.menu.GetActorList()): if pickedProp == m_actor: # print "Menu Actor picked, index = ", ii # Call the proper nav routine and get back the new ped_id new_ped_id = self.menu_functions[ii](prev_ped_id) new_ped_n = N.array([new_ped_id], dtype='int64') new_ped_vtk = VN.numpy_to_vtkIdTypeArray(new_ped_n, deep=True) self.output_link.GetCurrentSelection().GetNode(0).SetSelectionList(new_ped_vtk) self.output_link.InvokeEvent("AnnotationChangedEvent") self.applycolors1.Update() self.renWin.Render() # Set list for scale_link scale_list = [self.ds.Scales[new_ped_id]] navigated = True # Pick a cell of the icicle view # Cell picker doesn't work with Actor2D, so nav menu won't report any cells if someCellPicked and not navigated: print "Icicle picked cell index: ", pickedCellId # Assuming for now that this is a cell "Index", so getting pedigree ID sel = vtk.vtkSelection() node = vtk.vtkSelectionNode() node.SetFieldType(0) # Cell node.SetContentType(4) # Indices id_array = N.array([pickedCellId], dtype='int64') id_vtk = VN.numpy_to_vtkIdTypeArray(id_array, deep=True) node.SetSelectionList(id_vtk) sel.AddNode(node) # Note: When selection is cleared, the current selection does NOT contain any nodes self.areapoly1.Update() cs = vtk.vtkConvertSelection() pedIdSelection = cs.ToPedigreeIdSelection(sel, self.areapoly1.GetOutput()) pedIdSelection.GetNode(0).SetFieldType(3) # convert to vertext selection # Copy converted selection to output annotation link (fires AnnotationChangedEvent) self.output_link.SetCurrentSelection(pedIdSelection) self.applycolors1.Update() self.renWin.Render() # Set list for scale_link scale_list = [self.ds.Scales[pickedCellId]] if not someCellPicked and not somePropPicked: # reset selection to blank print "Blank selection" return self.output_link.GetCurrentSelection().RemoveAllNodes() self.output_link.InvokeEvent("AnnotationChangedEvent") self.applycolors1.Update() self.renWin.Render() # Set list for scale_link scale_list = [] print "scale picked in icicle view: ", scale_list id_array = N.array(scale_list, dtype='int64') id_vtk = VN.numpy_to_vtkIdTypeArray(id_array, deep=True) self.scale_link.GetCurrentSelection().GetNode(0).SetSelectionList(id_vtk) # For now want this event to trigger detail view, but not internal scale selection callback self.scale_internal_call = True self.scale_link.InvokeEvent("AnnotationChangedEvent")
def LoadData(self): # Remove all old actors from renderer self.renderer.RemoveAllViewProps() # Put back nav menu menu_actor_list = self.menu.GetActorList() for m_actor in menu_actor_list: self.renderer.AddActor(m_actor) tree = self.ds.GetTree() # Parallel pipeline with no shrinkage to get TCoords self.TreeLevels = vtk.vtkTreeLevelsFilter() self.TreeLevels.SetInput(tree) VertexDegree = vtk.vtkVertexDegree() VertexDegree.SetInputConnection(self.TreeLevels.GetOutputPort(0)) TreeAggregation = vtk.vtkTreeFieldAggregator() TreeAggregation.LeafVertexUnitSizeOff() TreeAggregation.SetField('size') TreeAggregation.SetInputConnection(VertexDegree.GetOutputPort(0)) # Layout without shrinkage for generating texture coordinates strategy = vtk.vtkStackedTreeLayoutStrategy() strategy.UseRectangularCoordinatesOn() strategy.SetRootStartAngle(0.0) strategy.SetRootEndAngle(15.0) strategy.SetRingThickness(self.THICK) # layer thickness strategy.ReverseOn() strategy.SetShrinkPercentage(0.0) layout = vtk.vtkAreaLayout() layout.SetLayoutStrategy(strategy) layout.SetInputConnection(TreeAggregation.GetOutputPort(0)) layout.SetAreaArrayName("area") layout.SetSizeArrayName("num_in_vertex") areapoly = vtk.vtkTreeMapToPolyData() areapoly.SetInputConnection(layout.GetOutputPort(0)) areapoly.SetAddNormals(0) areapoly.SetInputArrayToProcess( 0, 0, 0, 4, "area") # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES texPlane = vtk.vtkTextureMapToPlane() texPlane.SetInputConnection(areapoly.GetOutputPort(0)) texPlane.AutomaticPlaneGenerationOn() texPlane.Update() # Layout with shrinkage for generating geometry strategy0 = vtk.vtkStackedTreeLayoutStrategy() strategy0.UseRectangularCoordinatesOn() strategy0.SetRootStartAngle(0.0) strategy0.SetRootEndAngle(15.0) strategy0.SetRingThickness(self.THICK) # layer thickness strategy0.ReverseOn() strategy0.SetShrinkPercentage(self.SHRINK) layout0 = vtk.vtkAreaLayout() layout0.SetLayoutStrategy(strategy0) layout0.SetInputConnection(TreeAggregation.GetOutputPort(0)) layout0.SetAreaArrayName("area") layout0.SetSizeArrayName("num_in_vertex") areapoly0 = vtk.vtkTreeMapToPolyData() areapoly0.SetAddNormals(0) areapoly0.SetInputConnection(layout0.GetOutputPort(0)) areapoly0.SetInputArrayToProcess( 0, 0, 0, 4, "area") # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES areapoly0.Update() # Copy over texture coordinates def transferTCoords(): input = paf.GetInputDataObject(0,0) refin = paf.GetInputList().GetItem(0) output = paf.GetPolyDataOutput() TCorig = refin.GetPointData().GetTCoords() TC = vtk.vtkFloatArray() TC.SetNumberOfComponents(TCorig.GetNumberOfComponents()) TC.SetNumberOfTuples(TCorig.GetNumberOfTuples()) TC.SetName('Texture Coordinates') for ii in range(TCorig.GetNumberOfTuples()): ff = TCorig.GetTuple2(ii) TC.SetTuple2(ii,ff[0],ff[1]) output.GetPointData().AddArray(TC) output.GetPointData().SetActiveTCoords('Texture Coordinates') paf = vtk.vtkProgrammableAttributeDataFilter() paf.SetInput(areapoly0.GetOutput()) paf.AddInput(texPlane.GetOutput()) paf.SetExecuteMethod(transferTCoords) # Need to find proper ordering of wavelet coeffs based on icicle layout # tree.GetVertexData().GetArray('area') is 4-component (Xmin,Xmax,Ymin,Ymax) print 'Reordering wavelet coeffs' out_polys = areapoly.GetOutputDataObject(0) isleaf = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('leaf')) poly_bounds = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('area')) vertex_ids = VN.vtk_to_numpy(out_polys.GetCellData().GetArray('vertex_ids')) self.LeafIds = vertex_ids[isleaf>0] self.LeafXmins = poly_bounds[isleaf>0,0] self.XOrderedLeafIds = self.LeafIds[self.LeafXmins.argsort()] # Grab texture images and color map self.GrabTextureImagesAndLUT() # For each node and corresponding image data in self.WCimageDataList, need to create a texture, # then pull out the correct rectangle from areapoly0 (using vtkExtractSelectedPolyDataIds # and create a mapper and actor and apply the texture. self.texture_list = [] self.tex_mapper_list = [] self.tex_actor_list = [] for ii in range(len(self.WCimageDataList)): # Set up texture with lookup table for matrix polys tex = vtk.vtkTexture() tex.SetInput(self.WCimageDataList[ii]) tex.SetLookupTable(self.lut) self.texture_list.append(tex) # Grab correct poly out of areapoly0 sel = vtk.vtkSelection() node = vtk.vtkSelectionNode() node.SetContentType(4) # 4 = indices node.SetFieldType(0) # 0 = cell id_array = N.array([ii],dtype='int64') id_list = VN.numpy_to_vtkIdTypeArray(id_array) node.SetSelectionList(id_list) sel.AddNode(node) ext_id_poly = vtk.vtkExtractSelectedPolyDataIds() ext_id_poly.SetInput(1, sel) ext_id_poly.SetInputConnection(0, areapoly0.GetOutputPort(0)) # ext_id_poly.Update() # print ext_id_poly.GetOutput() poly_tm = vtk.vtkTextureMapToPlane() poly_tm.SetInputConnection(ext_id_poly.GetOutputPort(0)) poly_tm.AutomaticPlaneGenerationOn() poly_tm.Update() # Separate mapper and actor for textured polys map2 = vtk.vtkPolyDataMapper() map2.SetInputConnection(poly_tm.GetOutputPort(0)) map2.ScalarVisibilityOff() self.tex_mapper_list.append(map2) act2 = vtk.vtkActor() act2.SetMapper(self.tex_mapper_list[ii]) act2.SetTexture(self.texture_list[ii]) act2.GetProperty().SetColor(1,1,1) act2.SetPickable(0) act2.SetPosition(0,0,0.1) # ??? self.tex_actor_list.append(act2) # Add textured polys to the view self.renderer.AddActor(self.tex_actor_list[ii]) # Layout with shrinkage for generating outline geometry for showing selections self.applycolors1 = vtk.vtkApplyColors() self.applycolors1.SetInputConnection(0,layout0.GetOutputPort(0)) self.applycolors1.AddInputConnection(1,self.output_link.GetOutputPort(0)) self.applycolors1.SetDefaultPointColor(self.theme.GetPointColor()) self.applycolors1.SetDefaultPointOpacity(self.theme.GetPointOpacity()) self.applycolors1.SetSelectedPointColor(self.theme.GetSelectedPointColor()) self.applycolors1.SetSelectedPointOpacity(self.theme.GetSelectedPointOpacity()) self.areapoly1 = vtk.vtkTreeMapToPolyData() self.areapoly1.SetInputConnection(self.applycolors1.GetOutputPort(0)) self.areapoly1.SetAddNormals(0) self.areapoly1.SetInputArrayToProcess( 0, 0, 0, 4, "area") # 4 = vtkDataObject::FIELD_ASSOCIATION_VERTICES # Separate mapper and actor for icicle polys outlines (pickable) map = vtk.vtkPolyDataMapper() map.SetInputConnection(self.areapoly1.GetOutputPort(0)) map.SetScalarModeToUseCellFieldData() map.SelectColorArray("vtkApplyColors color") map.SetScalarVisibility(True) act = vtk.vtkActor() act.SetMapper(map) act.GetProperty().SetColor(1,1,1) act.SetPickable(True) act.SetPosition(0,0,0) act.GetProperty().SetRepresentationToWireframe() act.GetProperty().SetLineWidth(4.0) self.icicle_actor = act # Add actor for selection highlight outlines self.renderer.AddActor(act) # Now need to set up data for generating "selection lines" which come from # xy or pcoords chart. Basic method is to create a new scalar array out of x-coord # of the texture coordinates, then do a Delaunay2D on the shrunken polys and contour # that at values obtained by finding what normalized distance along data set are # selected pedigree ids. self.calc = vtk.vtkArrayCalculator() self.calc.SetInputConnection(paf.GetOutputPort()) self.calc.SetAttributeModeToUsePointData() self.calc.AddScalarVariable("tcoords_X", "Texture Coordinates", 0) self.calc.SetFunction("tcoords_X") self.calc.SetResultArrayName("tcx") # self.calc.Update() # print VN.vtk_to_numpy(self.calc.GetOutput().GetPointData().GetArray('tcx')) self.group_contour = vtk.vtkContourFilter() self.group_contour.SetInputConnection(self.calc.GetOutputPort(0)) self.group_contour.SetInputArrayToProcess(0,0,0,0,'tcx') self.highlight_contour = vtk.vtkContourFilter() self.highlight_contour.SetInputConnection(self.calc.GetOutputPort(0)) self.highlight_contour.SetInputArrayToProcess(0,0,0,0,'tcx') # Separate mapper and actor group selection (pcoords or xy) lines map3 = vtk.vtkPolyDataMapper() map3.SetInputConnection(self.group_contour.GetOutputPort(0)) map3.SetScalarVisibility(0) act3 = vtk.vtkActor() act3.SetMapper(map3) act3.SetPickable(False) act3.SetPosition(0,0,0.2) act3.GetProperty().SetRepresentationToWireframe() act3.GetProperty().SetLineWidth(2.0) act3.GetProperty().SetColor(1,0,0) act3.GetProperty().SetOpacity(0.6) self.group_actor = act3 # Add actor for selection highlight outlines self.renderer.AddActor(act3) # Separate mapper and actor for individual (image_flow) selection highlight map4 = vtk.vtkPolyDataMapper() map4.SetInputConnection(self.highlight_contour.GetOutputPort(0)) map4.SetScalarVisibility(0) act4 = vtk.vtkActor() act4.SetMapper(map4) act4.SetPickable(False) act4.SetPosition(0,0,0.25) act4.GetProperty().SetRepresentationToWireframe() act4.GetProperty().SetLineWidth(3.0) act4.GetProperty().SetColor(0,0.5,1) act4.GetProperty().SetOpacity(0.6) self.highlight_actor = act4 # Add actor for selection highlight outlines self.renderer.AddActor(act4) # Get Ordered fractional positions for pedigree ids (for setting contour values) self.ped_id_fracs = self.ds.GetIdsFractionalPosition(self.XOrderedLeafIds) # Clear out selections on data change self.output_link.GetCurrentSelection().RemoveAllNodes() self.output_link.InvokeEvent("AnnotationChangedEvent") self.renderer.ResetCamera(self.icicle_actor.GetBounds())
def set_polydata_triangles(self, triangles): vtk_triangles = np.hstack(np.c_[np.ones(len(triangles)).astype(np.int) * 3, triangles]) vtk_triangles = ns.numpy_to_vtkIdTypeArray(vtk_triangles, deep=True) vtk_cells = vtk.vtkCellArray() vtk_cells.SetCells(len(triangles), vtk_triangles) self.get_polydata().SetPolys(vtk_cells)
def InputSelectionCallback(self, caller, event): """This is the callback that tracks changes in the icicle view and sets the input table for the parallel coordinates chart accordingly. Note: This can only handle a single input nodeID for now...""" annSel = caller.GetCurrentSelection() # Note: When selection is cleared, the current selection does NOT contain any nodes if annSel.GetNumberOfNodes() > 0: idxVtk = annSel.GetNode(0).GetSelectionList() idxArr = VN.vtk_to_numpy(idxVtk) print "ice input to PC ", idxArr # Manually clear out selections if changing data # self.chart.GetPlot(0).ResetSelectionRange() # Here is where I'm limiting the selection to _one_ nodeID for now... node_id = idxArr[0] # NOTE: Hard coding for testing!!! # numPerSet = self.ds.ManifoldDim # Directly accessing member variable... # numPerSet = 3 # NOTE: Using only first few dimensions for testing!!! self.table, self.scale_dims = self.ds.GetNodeAllScaleCoeffTable(node_id) # self.table = self.ds.GetNodeAllScaleDDimCoeffTable(node_id,numPerSet) self.currentScale = self.ds.Scales[node_id] # Directly accessing member variable... # If this is the same icicle node as before, then reset to original XY indices # before view is updated if node_id != self.input_link_idx: self.XYcurrentX = 0 self.XYcurrentY = 1 # Get the axis image XY indices in case resetting to those values # and the number of dimensions has changed, and xI or yI are over the limit if self.XYcurrentY > self.XYcurrentX: y_bigger = 1 else: y_bigger = 0 # Check whether they're out of range for the new data max_dim = self.scale_dims[self.currentScale] - 1 if self.XYcurrentY > max_dim: self.XYcurrentY = max_dim if self.XYcurrentX > max_dim: self.XYcurrentX = max_dim if self.XYcurrentX == self.XYcurrentY: if y_bigger: self.XYcurrentX = self.XYcurrentY-1 else: self.XYcurrentY = self.XYcurrentX-1 if self.XYcurrentX < 0: self.XYcurrentX = 0 if self.XYcurrentY < 0: self.XYcurrentY = 0 # self.chartView.ResetCamera() self.input_link_idx = node_id # Using method for rest of call so don't have to load in new data if # just resetting axis set range self.UpdateChartWithCurrentData() else: # Need to clear out annotation link so downstream views will be cleared # before table is destroyed empty_vtk = VN.numpy_to_vtkIdTypeArray(N.array([],dtype='int64'), deep=True) self.link.GetCurrentSelection().GetNode(0).SetSelectionList(empty_vtk) empty_vtk2 = VN.numpy_to_vtkIdTypeArray(N.array([],dtype='int64'), deep=True) self.highlight_link.GetCurrentSelection().GetNode(0).SetSelectionList(empty_vtk2) # And make sure the output_link knows the selection has changed # NOTE: Commented out for now so we can preserve selections across icicle_view node changes # self.link.InvokeEvent("AnnotationChangedEvent") # self.highlight_link.InvokeEvent("AnnotationChangedEvent") # If there is no SelectionNode in IcicleView selection print "Ice cleared PC called" # For right now the only way I can get it to clear out the data is # to set the table=None. Should try creating a table with all the right # columns but no data in each column... self.table = None self.chart.GetPlot(0).SetInput(self.table)
for index in [0, 1, 2, 0, 1, 2, 0, 1, 2]: ice_class.SetDataSource(data_source_list[index]) ice_class.LoadData() # Set up an xy or PC plot annotation link as if selections were coming from another class group_link = vtk.vtkAnnotationLink() group_link.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point group_link.GetCurrentSelection().GetNode(0).SetContentType(2) # 2 = PedigreeIds, 4 = Indices ice_class.SetGroupAnnotationLink(group_link) # Fill selection link with individual data point IDs group_id_array = N.array([3,5,10,200,103,54],dtype='int64') group_id_list = VN.numpy_to_vtkIdTypeArray(group_id_array) group_link.GetCurrentSelection().GetNode(0).SetSelectionList(group_id_list) group_link.InvokeEvent("AnnotationChangedEvent") # Set up highlight annotation link as if selections were coming from another class highlight_link = vtk.vtkAnnotationLink() highlight_link.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point highlight_link.GetCurrentSelection().GetNode(0).SetContentType(2) # 2 = PedigreeIds, 4 = Indices ice_class.SetHighlightAnnotationLink(highlight_link) # Fill selection link with individual data point IDs highlight_id_array = N.array([54],dtype='int64') highlight_id_list = VN.numpy_to_vtkIdTypeArray(highlight_id_array) highlight_link.GetCurrentSelection().GetNode(0).SetSelectionList(highlight_id_list)
def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Set up a 2D scene (later we'll add a pcoords chart to it) self.view = vtk.vtkContextView() # self.view.GetRenderer().SetBackground(1.0, 1.0, 1.0) # // QVTKWidget *widget = new QVTKWidget; # // vtkContextView *view = vtkContextView::New(); # // view->SetInteractor(widget->GetInteractor()); # // widget->SetRenderWindow(view->GetRenderWindow()); # Necessary for RenderView types self.view.SetInteractor(self.ui.vtkWidget.GetInteractor()) self.ui.vtkWidget.SetRenderWindow(self.view.GetRenderWindow()) data_file = '/Users/emonson/Data/Fodava/EMoGWDataSets/mnist12_1k_20101119.mat' # DataSource loads .mat file and can generate data from it for other views ds = DataSource(data_file) # Testing my custom chart class which has image hover tooltips chart = vtkvtg.vtkMyChartXY() chart.SetActionToButton(vtk.vtkChart.PAN, 2) chart.SetActionToButton(vtk.vtkChart.ZOOM, 4) chart.SetActionToButton(vtk.vtkChart.SELECT, 1) self.view.GetScene().AddItem(chart) # Create a annotation link to access selection in parallel coordinates view annotationLink = vtk.vtkAnnotationLink() # If you don't set the FieldType explicitly it ends up as UNKNOWN (as of 21 Feb 2010) # See vtkSelectionNode doc for field and content type enum values annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point annotationLink.GetCurrentSelection().GetNode(0).SetContentType(4) # Indices # Connect the annotation link to the parallel coordinates representation chart.SetAnnotationLink(annotationLink) test_id = 3 table = ds.GetNodeOneScaleCoeffTable(test_id) chart.ClearPlots() line1 = vtkvtg.vtkMyPlotPoints() chart.AddPlot(line1) # POINTS line1.SetInput(table, 0, 1) line1.SetMarkerStyle(2) line1.SetColor(0, 0, 0, 255) # Tooltip image stack will now be owned by the tooltip, so need to do that differently... id_list = ds.PointsInNet[test_id] image_stack = ds.GetProjectedImages(id_list) chart.SetTooltipImageStack(image_stack) chart.SetTooltipShowImage(True) # chart.SetTooltipImageScalingFactor(2.0) chart.SetTooltipImageTargetSize(40) # Set up annotation link which will carry indices to parallel coordinates chart # for highlighting outside selections (e.g. back from image_flow) # This needs to carry indices, while image_flow link outputs pedigree ids # so conversion happens in HighlightSelectionCallback highlight_link_idxs = vtk.vtkAnnotationLink() highlight_link_idxs.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point highlight_link_idxs.GetCurrentSelection().GetNode(0).SetContentType(4) # 2 = PedigreeIds, 4 = Indices chart.SetHighlightLink(highlight_link_idxs) # Finally render the scene and compare the image to a reference image # view.GetRenderWindow().SetMultiSamples(0) annotationLink.AddObserver("AnnotationChangedEvent", self.selectionCallback) # view.ResetCamera() # view.Render() # Fill selection link with dummy IDs id_array = N.array([0],dtype='int64') id_list = VN.numpy_to_vtkIdTypeArray(id_array) highlight_link_idxs.GetCurrentSelection().GetNode(0).SetSelectionList(id_list) highlight_link_idxs.InvokeEvent("AnnotationChangedEvent") # Set up annotation link which will carry indices to parallel coordinates chart # for highlighting outside selections (e.g. back from image_flow) # This needs to carry indices, while image_flow link outputs pedigree ids # so conversion happens in HighlightSelectionCallback data_col_idxs = vtk.vtkAnnotationLink() data_col_idxs.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point data_col_idxs.GetCurrentSelection().GetNode(0).SetContentType(4) # 2 = PedigreeIds, 4 = Indices chart.SetDataColumnsLink(data_col_idxs) # Fill selection link with dummy IDs col_array = N.array([1,2],dtype='int64') col_list = VN.numpy_to_vtkIdTypeArray(col_array) data_col_idxs.GetCurrentSelection().GetNode(0).SetSelectionList(col_list) data_col_idxs.InvokeEvent("AnnotationChangedEvent") # Start interaction event loop self.ui.vtkWidget.show()
def __init__(self, parent = None): QtGui.QMainWindow.__init__(self, parent) self.ui = Ui_MainWindow() self.renWinList = [] # data_file = askopenfilename() data_file = '/Users/emonson/Data/Fodava/EMoGWDataSets/mnist1_5c_20100324.mat' # self.openFilesDefaultPath = QtCore.QDir.homePath() # data_file = QtGui.QFileDialog.getOpenFileName(self, # "Load Saved Matlab File", # self.openFilesDefaultPath, # "All Files (*);;Matlab Files (*.mat)") # DataSource loads .mat file and can generate data from it for other views self.ds = DataSource(str(data_file)) # All view classes have access to an instance of that data source for internal queries # Note that the only view which will pull and display data right away is the icicle view # the other views need to be able to initialize without any data and only pull and show # upon the first AnnotationChanged event... # View #0 -- Icicle View # Set up a 2D scene, add an XY chart to it self.chartView = vtk.vtkContextView() self.chartView.GetRenderer().SetBackground(1.0, 1.0, 1.0) self.renWinList.append(self.chartView.GetRenderWindow()) self.chart = vtkvtg.vtkMyChartXY() self.chartView.GetScene().AddItem(self.chart) # View #1 -- AxisImageView self.axisView = vtk.vtkContextView() self.axisView.GetRenderer().SetBackground(1.0, 1.0, 1.0) self.renWinList.append(self.axisView.GetRenderWindow()) self.ai = vtkvtg.vtkAxisImageItem() self.axisView.GetScene().AddItem(self.ai) # Set up all the render windows in the GUI self.ui.setupUi(self, self.renWinList) # Now need to get all the interactors working properly # XY style0 = vtk.vtkInteractorStyleRubberBand2D() self.chartView.GetInteractor().SetInteractorStyle(style0) self.chartView.GetScene().SetInteractorStyle(style0) # Axis images style1 = vtk.vtkInteractorStyleRubberBand2D() self.axisView.GetInteractor().SetInteractorStyle(style1) self.axisView.GetScene().SetInteractorStyle(style1) # Set sizes for veritcal splitters self.ui.splitter.setSizes([200,400]) # Connect signals and slots QtCore.QObject.connect(self.ui.actionExit, QtCore.SIGNAL("triggered()"), self.fileExit) # CORE setting up chart and axis images test_id = 68 self.table = self.ds.GetNodeOneScaleCoeffTable(test_id) line1 = vtkvtg.vtkMyPlotPoints() # line1.DebugOn() self.chart.AddPlot(line1) # POINTS line1.SetInput(self.table, 0, 1) line1.SetMarkerStyle(2) line1.SetColor(0, 0, 0, 255) # Tooltip image stack will now be owned by the tooltip, so need to do that differently... id_list = self.ds.PIN[test_id] image_stack = self.ds.GetProjectedImages(id_list) self.chart.SetTooltipImageStack(image_stack) self.chart.SetTooltipShowImage(True) # self.chart.SetTooltipImageScalingFactor(2.0) self.chart.SetTooltipImageTargetSize(40) axis_images = self.ds.GetNodeBasisImages(test_id) center_image = self.ds.GetNodeCenterImage(test_id) self.ai.SetAxisImagesHorizontal() self.ai.SetChartXY(self.chart) self.ai.SetChartXYView(self.chartView) self.ai.SetAxisImageStack(axis_images) self.ai.SetCenterImage(center_image) # Set up annotation link which will carry indices to parallel coordinates chart # for highlighting outside selections (e.g. back from image_flow) # This needs to carry indices, while image_flow link outputs pedigree ids # so conversion happens in HighlightSelectionCallback # data_col_idxs = vtk.vtkAnnotationLink() # data_col_idxs.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point # data_col_idxs.GetCurrentSelection().GetNode(0).SetContentType(4) # 2 = PedigreeIds, 4 = Indices # self.chart.SetDataColumnsLink(data_col_idxs) # self.ai.SetDataColumnsLink(data_col_idxs) # Create a annotation link to access selection in XY chart annotationLink = vtk.vtkAnnotationLink() annotationLink.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point annotationLink.GetCurrentSelection().GetNode(0).SetContentType(4) # Indices # Connect the annotation link to the parallel coordinates representation self.chart.SetAnnotationLink(annotationLink) self.chart.GetAnnotationLink().AddObserver("AnnotationChangedEvent", self.IcicleSelectionCallback) # Set up annotation link which will carry indices to parallel coordinates chart # for highlighting outside selections (e.g. back from image_flow) # This needs to carry indices, while image_flow link outputs pedigree ids # so conversion happens in HighlightSelectionCallback highlight_link_idxs = vtk.vtkAnnotationLink() highlight_link_idxs.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point highlight_link_idxs.GetCurrentSelection().GetNode(0).SetContentType(4) # 2 = PedigreeIds, 4 = Indices self.chart.SetHighlightLink(highlight_link_idxs) # Fill selection link with dummy IDs id_array = N.array([0],dtype='int64') id_list = VN.numpy_to_vtkIdTypeArray(id_array, deep=True) highlight_link_idxs.GetCurrentSelection().GetNode(0).SetSelectionList(id_list) highlight_link_idxs.InvokeEvent("AnnotationChangedEvent") # self.updater = vtk.vtkViewUpdater() # self.updater.AddAnnotationLink(data_col_idxs) # self.updater.AddView(self.axisView) # self.updater.AddView(self.chartView) # col_array = N.array([0,1],dtype='int64') # col_vtk = VN.numpy_to_vtkIdTypeArray(col_array, deep=True) # data_col_idxs.GetCurrentSelection().GetNode(0).SetSelectionList(col_vtk) # data_col_idxs.InvokeEvent("AnnotationChangedEvent") self.chart.RecalculateBounds() # Only need to Start() interactor for one view # self.pc_class.GetView().GetInteractor().Start() # Shouldn't have to do this render... for rw in self.renWinList: rw.Render()
# data_file = askopenfilename() data_file = '/Users/emonson/Data/Fodava/EMoGWDataSets/mnist1_5c_20100324.mat' # DataSource loads .mat file and can generate data from it for other views ds = DataSource(data_file) # Set up an annotation link as if selections were coming from another class dummy_link = vtk.vtkAnnotationLink() dummy_link.GetCurrentSelection().GetNode(0).SetFieldType(1) # Point dummy_link.GetCurrentSelection().GetNode(0).SetContentType(2) # 2 = PedigreeIds, 4 = Indices if_class = ImageFlow(ds, dummy_link) if_class.GetRenderWindow().SetSize(600,300) if_class.SetFlowDirection(Direction.Horizontal) # if_class.GetRenderWindow().SetSize(300,600) # if_class.SetFlowDirection(Direction.Vertical) # Fill selection link with dummy IDs id_array = N.array(range(50),dtype='int64') id_list = VN.numpy_to_vtkIdTypeArray(id_array) dummy_link.GetCurrentSelection().GetNode(0).SetSelectionList(id_list) dummy_link.InvokeEvent("AnnotationChangedEvent") # Only need to Start() interactor for one view if_class.GetRenderWindow().GetInteractor().Start()
def tracts_to_vtkPolyData64(tracts, tracts_data={}, lines_indices=None): # if isinstance(tracts, Tractography): tracts_data = tracts.tracts_data() tracts = tracts.tracts() lengths = [len(p) for p in tracts] line_starts = ns.numpy.r_[0, ns.numpy.cumsum(lengths)] if lines_indices is None: lines_indices = [ ns.numpy.arange(length) + line_start for length, line_start in izip(lengths, line_starts) ] ids = ns.numpy.hstack([ ns.numpy.r_[c[0], c[1]] for c in izip(lengths, lines_indices) ]) ids=np.int64(ids) vtk_ids = ns.numpy_to_vtkIdTypeArray(ids, deep=True) cell_array = vtk.vtkCellArray() cell_array.SetCells(len(tracts), vtk_ids) points = ns.numpy.vstack(tracts).astype( ns.get_vtk_to_numpy_typemap()[vtk.VTK_DOUBLE] ) points_array = ns.numpy_to_vtk(points, deep=True) poly_data = vtk.vtkPolyData() vtk_points = vtk.vtkPoints() vtk_points.SetData(points_array) poly_data.SetPoints(vtk_points) poly_data.SetLines(cell_array) saved_keys = set() for key, value in tracts_data.items(): if key in saved_keys: continue if key.startswith('Active'): saved_keys.add(value) name = value value = tracts_data[value] else: name = key if len(value) == len(tracts): if value[0].ndim == 1: value_ = ns.numpy.hstack(value)[:, None] else: value_ = ns.numpy.vstack(value) elif len(value) == len(points): value_ = value else: raise ValueError( "Data in %s does not have the correct number of items") vtk_value = ns.numpy_to_vtk(np.ascontiguousarray(value_), deep=True) vtk_value.SetName(name) if key == 'ActiveScalars' or key == 'Scalars_': poly_data.GetPointData().SetScalars(vtk_value) elif key == 'ActiveVectors' or key == 'Vectors_': poly_data.GetPointData().SetVectors(vtk_value) elif key == 'ActiveTensors' or key == 'Tensors_': poly_data.GetPointData().SetTensors(vtk_value) else: poly_data.GetPointData().AddArray(vtk_value) poly_data.BuildCells() return poly_data