def _format_output_polydata(output_polydata, cluster_idx, color, embed): """ Output polydata with embedding colors, cluster numbers, and embedding coordinates. Cell data array names are: EmbeddingColor ClusterNumber EmbeddingCoordinate """ embed_colors = vtk.vtkUnsignedCharArray() embed_colors.SetNumberOfComponents(3) embed_colors.SetName('EmbeddingColor') cluster_colors = vtk.vtkIntArray() cluster_colors.SetName('ClusterNumber') embed_data = vtk.vtkFloatArray() embed_data.SetNumberOfComponents(embed.shape[1]) embed_data.SetName('EmbeddingCoordinate') for lidx in range(0, output_polydata.GetNumberOfLines()): embed_colors.InsertNextTuple3( color[lidx, 0], color[lidx, 1], color[lidx, 2]) cluster_colors.InsertNextTuple1(int(cluster_idx[lidx])) embed_data.InsertNextTupleValue(embed[lidx, :]) output_polydata.GetCellData().AddArray(embed_data) output_polydata.GetCellData().AddArray(cluster_colors) output_polydata.GetCellData().AddArray(embed_colors) output_polydata.GetCellData().SetActiveScalars('EmbeddingColor') return output_polydata
def quadsActor(bounds, color): """Create solid, axis-aligned quads at 0 in Z. Args: bounds: [[[xmin, ymin], [xmax, ymax]], ...] color: [R, G, B, A] """ points = vtk.vtkPoints() quads = vtk.vtkCellArray() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(4) for (index, bound) in enumerate(bounds): colors.InsertNextTuple4(*color) (low, high) = bound points.InsertNextPoint(low[0], low[1], 0) points.InsertNextPoint(high[0], low[1], 0) points.InsertNextPoint(high[0], high[1], 0) points.InsertNextPoint(low[0], high[1], 0) quad = vtk.vtkQuad() for i in range(4): quad.GetPointIds().SetId(i, 4 * index + i) quads.InsertNextCell(quad) poly_data = vtk.vtkPolyData() poly_data.SetPoints(points) poly_data.SetPolys(quads) poly_data.GetCellData().SetScalars(colors) mapper = vtk.vtkPolyDataMapper() set_mapper_input(mapper, poly_data) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.RotateZ(180) actor.RotateY(180) return actor
def array_to_vtk(array_in, dtype=None): """Get vtkFloatArray/vtkDoubleArray from the input numpy array.""" if dtype == None: dtype = _numpy.dtype(array_in.dtype) else: dtype = _numpy.dtype(dtype) if dtype == _numpy.float32: float_array = _vtk.vtkFloatArray() elif dtype == _numpy.float64: float_array = _vtk.vtkDoubleArray() elif dtype == _numpy.uint8: float_array = _vtk.vtkUnsignedCharArray() elif dtype == _numpy.int8: float_array = _vtk.vtkCharArray() else: raise ValueError("Wrong format of input array, must be float32 or float64") if len(array_in.shape) != 1 and len(array_in.shape) != 2: raise ValueError("Wrong shape: array must be 1D or 2D.") #float_array.SetNumberOfComponents(_numpy.product(array_in.shape)) # if len(array_in.shape) == 2: # float_array.SetNumberOfComponents(array_in.shape[1]) # elif len(array_in.shape) == 1: # float_array.SetNumberOfComponents(1) float_array.SetNumberOfComponents(1) array_contiguous = _numpy.ascontiguousarray(array_in, dtype) float_array.SetVoidArray(array_contiguous, _numpy.product(array_in.shape), 1) float_array._contiguous_array = array_contiguous # Hack to keep the array of being garbage collected # if len(array_in.shape) == 2: # print "set tuple to {0}".format(array_in.shape[1]) # #float_array.SetNumberOfTuples(array_in.shape[1]) # float_array.Resize(array_in.shape[1]) # float_array.Squeeze() return float_array
def pointCloudActor(points, color = (0, 0, 0, 255)): """Create a vtkActor representing a point cloud. Args: points: iterable of points [[x0, y0, z0], [x1, y1, z1], ...] color: color of the points in the RBBA format Returns: An instance of vtkActor """ vtk_points = vtk.vtkPoints() vertices = vtk.vtkCellArray() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(4) colors.SetName("Colors") for (x, y, z) in points: point_id = vtk_points.InsertNextPoint(x, y, z) vertices.InsertNextCell(1) vertices.InsertCellPoint(point_id) colors.InsertNextTuple4(color[0], color[1], color[2], color[3]) poly_data = vtk.vtkPolyData() poly_data.SetPoints(vtk_points) poly_data.SetVerts(vertices) poly_data.GetPointData().SetScalars(colors) mapper = vtk.vtkPolyDataMapper() set_mapper_input(mapper, poly_data) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
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
def CheckFilter(inputDS): numOrigCells = inputDS.GetNumberOfCells() ghostArray = vtk.vtkUnsignedCharArray() ghostArray.SetNumberOfTuples(numOrigCells) ghostArray.SetName(vtk.vtkDataSetAttributes.GhostArrayName()) ghostArray.Fill(0) inputDS.GetCellData().AddArray(ghostArray) removeGhosts = vtk.vtkRemoveGhosts() removeGhosts.SetInputDataObject(inputDS) removeGhosts.Update() outPD = removeGhosts.GetOutput() if outPD.GetNumberOfCells() != numOrigCells: print("Should have the same amount of cells but did not", outPD.GetNumberOfCells(), numOrigCells) sys.exit(1) ghostArray.SetValue(0, 1) ghostArray.Modified() removeGhosts.Modified() removeGhosts.Update() if outPD.GetNumberOfCells() != numOrigCells-1: print("Should have had one less cell but did not", outPD.GetNumberOfCells(), numOrigCells) sys.exit(1)
def visualize_graph(self): """shows a visualization of the graph""" self._graph.GetVertexData().AddArray(self._labels) self._graph.GetEdgeData().AddArray(self._weights) colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(1) colors.SetName('Colors') types = int(245 / len(self._color_dict)) for c in self._colors: colors.InsertNextValue(int(c * types)) self._graph.GetVertexData().AddArray(colors) graphLayoutView = vtk.vtkGraphLayoutView() graphLayoutView.AddRepresentationFromInput(self._graph) graphLayoutView.SetLayoutStrategy(vtk.vtkSpanTreeLayoutStrategy()) graphLayoutView.GetLayoutStrategy().SetEdgeWeightField("Weights") graphLayoutView.GetLayoutStrategy().SetWeightEdges(1) graphLayoutView.GetRenderer().GetActiveCamera().ParallelProjectionOff() graphLayoutView.SetEdgeLabelArrayName("Weights") graphLayoutView.SetEdgeLabelVisibility(1) graphLayoutView.SetVertexLabelArrayName('labels') graphLayoutView.SetVertexLabelVisibility(1) graphLayoutView.SetVertexColorArrayName('Colors') graphLayoutView.SetColorVertices(1) graphLayoutView.SetInteractorStyle(MouseAndKeysInteractor(graphLayoutView)) graphLayoutView.ResetCamera() graphLayoutView.Render() graphLayoutView.GetInteractor().Start()
def write(self, file_name): writer = vtk.vtkPLYWriter() writer.SetFileName(file_name) writer.SetInputData(self.vtk_poly_data) if self.is_color_mode_height: # set lookup tbale for depth values to colors lut = vtk.vtkLookupTable() lut.SetTableRange(self.height_min, self.height_max) lut.Build() # in order to be convertable to pcd, use lut to generate colors. # THIS IS A DIRTY HACK BUT NEEDED SINCE PCL IS STUPID # writer.SetLookupTable(lut) only works for meshlab cur_color_data = vtk.vtkUnsignedCharArray() cur_color_data.SetNumberOfComponents(3) for id in self.color_ids: val = self.color_data.GetValue(id) col = [0., 0., 0.] lut.GetColor(val, col) col = [int(c * 255) for c in col] cur_color_data.InsertNextTuple3(col[0], col[1], col[2]) self.color_data = cur_color_data self.color_data.SetName("Colors") self.vtk_poly_data.GetPointData().SetActiveScalars('Colors') self.vtk_poly_data.GetPointData().SetScalars(self.color_data) writer.SetArrayName("Colors") writer.Write()
def add_surface_overlay(self, data, colormap=None): scalar = vtk.vtkUnsignedCharArray() scalar.SetNumberOfComponents(3) if colormap is None: ran = (np.amin(data), np.amax(data)) mid = (ran[0] + ran[1]) / 2. for val in data: if val < mid: gr = 255.0 * (val - ran[0]) / (mid - ran[0]) else: gr = 255.0 * (ran[1] - val) / (ran[1] - mid) scalar.InsertNextTuple3( 255 * (val - ran[0]) / (ran[1] - ran[0]), gr, 255 * (ran[1] - val) / (ran[1] - ran[0])) else: for val in data: if val < colormap[0][0]: ind = 0 elif val > colormap[-1][0]: ind = colormap.shape[0] - 1 else: for ind in xrange(colormap.shape[0] - 1): if val < colormap[ind + 1][0]: break scalar.InsertNextTuple3(255 * colormap[ind][1], 255 * colormap[ind][2], 255 * colormap[ind][3]) self.surface_overlays.append(scalar) self.surface_overlay_data.append(data)
def testLinear(self): pts = vtk.vtkPoints() pts.SetNumberOfPoints(4) pts.InsertPoint(0, (0, 0, 0)) pts.InsertPoint(1, (1, 0, 0)) pts.InsertPoint(2, (0.5, 1, 0)) pts.InsertPoint(3, (0.5, 0.5, 1)) te = vtk.vtkTetra() ptIds = te.GetPointIds() for i in range(4): ptIds.SetId(i, i) ghosts = vtk.vtkUnsignedCharArray() ghosts.SetName("vtkGhostLevels") ghosts.SetNumberOfTuples(4) ghosts.SetValue(0, 1) ghosts.SetValue(1, 1) ghosts.SetValue(2, 1) ghosts.SetValue(3, 0) grid = vtk.vtkUnstructuredGrid() grid.Allocate(1, 1) grid.InsertNextCell(te.GetCellType(), te.GetPointIds()) grid.SetPoints(pts) grid.GetPointData().AddArray(ghosts) dss = vtk.vtkDataSetSurfaceFilter() dss.SetInputData(grid) dss.Update() self.assertEqual(dss.GetOutput().GetNumberOfCells(), 3)
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)
def setup_topography(x, y, topography, xmax=None, ymax=None, decimation=1): # Define points, triangles and colors x = x[::decimation] y = y[::decimation] lonsize = len(x)-1 if not xmax else xmax latsize = len(y)-1 if not ymax else ymax colors = vtk.vtkUnsignedCharArray() # colors.SetNumberOfComponents(3) colors.SetNumberOfComponents(1) points = vtk.vtkPoints() triangles = vtk.vtkCellArray() zmax = topography.max() zmin = topography.min() zrange = zmax - zmin xmesh, ymesh = scaled_mesh(x, y) count = 0 t1 = time.time() topography = topography.T topo_new = num.zeros((len(y), len(x))) for iy in xrange(len(y)): topo_new[iy, :] = topography[iy*decimation, ::decimation] topography = topo_new for i in xrange(latsize): print '%i / %i' % (i+1, latsize) for j in xrange(lonsize-3): d = (ymesh[i][j], xmesh[i][j], topography[i][j]) c = (ymesh[i][j+1], xmesh[i][j+1], topography[i][j+1]) b = (ymesh[i+1][j+1], xmesh[i+1][j+1], topography[i+1][j+1]) a = (ymesh[i+1][j], xmesh[i+1][j], topography[i+1][j]) points.InsertNextPoint(*a) points.InsertNextPoint(*b) points.InsertNextPoint(*c) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, count) triangle.GetPointIds().SetId(1, count + 1) triangle.GetPointIds().SetId(2, count + 2) triangles.InsertNextCell(triangle) points.InsertNextPoint(*a) points.InsertNextPoint(*d) points.InsertNextPoint(*c) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, count + 3) triangle.GetPointIds().SetId(1, count + 4) triangle.GetPointIds().SetId(2, count + 5) count += 6 triangles.InsertNextCell(triangle) # rs = [[int((zmax-topography[j][i])/zrange*255)]]*6 rs = [[int((zmax-topography[i][j])/zrange*255)]]*6 map(colors.InsertNextTupleValue, rs) print 'total time needed ', time.time()-t1 return points, triangles, colors
def getNewVtkDataArray( scalar_dtype ): if scalar_dtype == np.ushort: return vtk.vtkUnsignedShortArray() if scalar_dtype == np.ubyte: return vtk.vtkUnsignedCharArray() if scalar_dtype == np.float: return vtk.vtkFloatArray() return None
def set_scalars(self, values): colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) for r,g,b,a in 255*self.cmapper.to_rgba(values): colors.InsertNextTuple3(r,g,b) self.polydata.GetPointData().SetScalars(colors)
def vtk_point_cloud(points, colors=[], point_size=2): """ Represent a point cloud in VTK Parameters ---------- points : numpy array, each row is a point colors : list of colors, one per point point_size : rendering size for the points Returns ------- actor : vtkActor representing the point cloud """ nb = len(points); vtk_points = vtk.vtkPoints(); vtk_verts = vtk.vtkCellArray(); if colors: vtk_colors = vtk.vtkUnsignedCharArray(); vtk_colors.SetNumberOfComponents(3); vtk_colors.SetName( "Colors"); for i in range(0,nb): p = points[i] if len(p) >= 3: print "ok",p coords = [p[0],p[1],p[2]] elif len(p) == 2: coords = [p[0],p[1],0] elif len(p) == 1: coords = [p[0],0,0] else: print "**ERROR** wrong dimension" sys.exit(1) id = vtk_points.InsertNextPoint( *coords ) vtk_verts.InsertNextCell(1) vtk_verts.InsertCellPoint(id) if colors: vtk_colors.InsertNextTuple3( *colors[i] ) poly = vtk.vtkPolyData() poly.SetPoints(vtk_points) poly.SetVerts(vtk_verts) if colors: poly.GetPointData().SetScalars(vtk_colors) poly.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInput(poly) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetRepresentationToPoints actor.GetProperty().SetPointSize( point_size ) return actor
def execute(self): output_collection = vtk.vtkCollection() cluster=ClusterParticles(input,output_collection,feature_extractor=self.feature_extractor) cluster._number_of_clusters=2 #cluster._method='MiniBatchKMeans' cluster._method='KMeans' cluster.execute() points = vtk_to_numpy(input.GetPoints().GetData()) p_centroids = np.zeros([2,3]) for ii,ll in enumerate(cluster._unique_labels): p_centroids[ii,:]=np.mean(points[cluster._labels==ll,:],axis=0) if p_centroids[0,0] > p_centroids[1,0]: self.cluster_tags=['left','right'] chest_region=[3,2] chest_type=[3,3] else: self.cluster_tags=['right','left'] chest_region=[2,3] chest_type=[3,3] append=vtk.vtkAppendPolyData() for k,tag,cr,ct in zip([0,1],self.cluster_tags,chest_region,chest_type): self._out_vtk[tag]=output_collection.GetItemAsObject(k) chest_region_arr = vtk.vtkUnsignedCharArray() chest_region_arr.SetName('ChestRegion') chest_type_arr = vtk.vtkUnsignedCharArray() chest_type_arr.SetName('ChestType') n_p = self._out_vtk[tag].GetNumberOfPoints() chest_region_arr.SetNumberOfTuples(n_p) chest_type_arr.SetNumberOfTuples(n_p) for ii in xrange(self._out_vtk[tag].GetNumberOfPoints()): chest_region_arr.SetValue(ii,cr) chest_type_arr.SetValue(ii,ct) self._out_vtk[tag].GetPointData().AddArray(chest_region_arr) self._out_vtk[tag].GetPointData().AddArray(chest_type_arr) append.AddInput(self._out_vtk[tag]) append.Update() self._out_vtk['all']=append.GetOutput() return self._out_vtk
def initScalarArray(self): """Sets up scalar array describing tetrahedra values.""" self.scalar = vtk.vtkUnsignedCharArray() self.scalar.SetNumberOfComponents(3) self.scalar.SetName("Colors") return self.scalar
def colors_to_scalars(colors): colorData = vtk.vtkUnsignedCharArray() colorData.SetName("colors") colorData.SetNumberOfComponents(3) for color in colors: colorData.InsertNextTuple3(*color) return colorData
def generate(self): if self.actor is not None: self.frame.ren.RemoveActor(self.actor) self.pts = vtk.vtkPoints() self.radii = vtk.vtkFloatArray() self.radii.SetName('radii') self.colors = vtk.vtkUnsignedCharArray() self.colors.SetNumberOfComponents(3) self.colors.SetName('colors') # nodes for k, node in self.K.items(): self.pts.InsertPoint(k, *node.pos) self.radii.InsertTuple1(k, node.radius) if self.color_tips_in_yellow and not node.children: self.colors.InsertTuple3(k, *name_to_rgb('yellow')) else: self.colors.InsertTuple3(k, *name_to_rgb(self.base_color)) # edges lines = vtk.vtkCellArray() for k, node in self.K.items(): if node.parent is None: continue lines.InsertNextCell(2) lines.InsertCellPoint(k) lines.InsertCellPoint(node.parent) self.polydata = vtk.vtkPolyData() self.polydata.SetPoints(self.pts) self.polydata.SetLines(lines) self.polydata.GetPointData().AddArray(self.radii) self.polydata.GetPointData().AddArray(self.colors) self.polydata.GetPointData().SetActiveScalars('radii') self.tubes = vtk.vtkTubeFilter() self.tubes.SetNumberOfSides(10) if USING_VTK6: self.tubes.SetInputData(self.polydata) else: self.tubes.SetInput(self.polydata) self.tubes.SetVaryRadiusToVaryRadiusByAbsoluteScalar() self.tubes.CappingOn() self.mapper = vtk.vtkPolyDataMapper() if self.show_volume: if USING_VTK6: self.mapper.SetInputConnection(self.tubes.GetOutputPort()) else: self.mapper.SetInput(self.tubes.GetOutput()) else: if USING_VTK6: self.mapper.SetInputData(self.polydata) else: self.mapper.SetInput(self.polydata) self.mapper.ScalarVisibilityOn() self.mapper.SetScalarModeToUsePointFieldData() self.mapper.SelectColorArray('colors') self.actor = vtk.vtkActor() self.actor.GetProperty().SetColor(name_to_rgb_float(self.base_color)) self.actor.SetMapper(self.mapper) self.frame.ren.AddActor(self.actor) self.frame.ren_win.Render()
def unfoldData(): inputDS = filter.GetInputDataObject(0, 0) outputDS = filter.GetImageDataOutput() dims = inputDS.GetDimensions() # dims[1] * dims[2] nbSlices = (dims[1] * dims[2]) / 2048 outputDS.SetDimensions(dims[0], dims[1] * dims[2] / nbSlices, nbSlices) outputDS.SetOrigin(0,0,0) outputDS.SetSpacing(1,1,1) for arrayIdx in range(inputDS.GetPointData().GetNumberOfArrays()): array = inputDS.GetPointData().GetArray(arrayIdx) size = dims[0] * dims[1] * dims[2] if not array.GetName() in fieldsRange: continue dataRangeToUser = fieldsRange[array.GetName()] print "Process array: ", array.GetName() rescale = 256.0 * 256.0 * 256.0 / (dataRangeToUser[1] - dataRangeToUser[0]) newArray = vtkUnsignedCharArray() newArray.SetName(array.GetName()) newArray.SetNumberOfComponents(3) newArray.SetNumberOfTuples(size) outputDS.GetPointData().AddArray(newArray) progress = int(size / 100) count = 0 for idx in range(size): value = array.GetValue(idx) if value < dataRangeToUser[0]: newArray.SetValue(idx * 3, 0) newArray.SetValue(idx * 3 + 1, 0) newArray.SetValue(idx * 3 + 2, 0) elif value > dataRangeToUser[1]: newArray.SetValue(idx * 3, 255) newArray.SetValue(idx * 3 + 1, 255) newArray.SetValue(idx * 3 + 2, 255) else: value = (value - dataRangeToUser[0]) * rescale newArray.SetValue(idx * 3, int(value%256)) newArray.SetValue(idx * 3 + 1, int(value/256%256)) newArray.SetValue(idx * 3 + 2, int(value/256/256)) # if idx % progress == 0: # count = count + 1 # print count # # sys.stdout.write('.') # # sys.stdout.flush() # #sys. "\rProcessing %s: %d %s" % (array.GetName(), count, "/-\\|"[count%4]) print
def colorArray(self, array, cmap=None): colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) if cmap is None: cmap = 'coolwarm' colormap = cm.get_cmap(cmap) mapped = colormap(array) for r,g,b,a in 255*mapped: colors.InsertNextTuple3(r,g,b) return colors
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(1, 1, 1) self.vtkWidget.GetRenderWindow().AddRenderer(self.ren) self.iren = self.vtkWidget.GetRenderWindow().GetInteractor() # Create points points = vtk.vtkPoints() points.InsertNextPoint(0, 0, 0) points.InsertNextPoint(5, 0, 0) points.InsertNextPoint(10, 0, 0) # Setup scales. This can also be an Int array # char is used since it takes the least memory colors = vtk.vtkUnsignedCharArray() colors.SetName("colors") colors.SetNumberOfComponents(3) colors.InsertNextTupleValue((255, 0, 0)) colors.InsertNextTupleValue((0, 255, 0)) colors.InsertNextTupleValue((0, 0, 255)) # Combine into a polydata polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.GetPointData().SetScalars(colors) # Create anything you want here, we will use a cube for the demo. cubeSource = vtk.vtkCubeSource() glyph3D = vtk.vtkGlyph3D() glyph3D.SetColorModeToColorByScalar() glyph3D.SetSourceConnection(cubeSource.GetOutputPort()) glyph3D.SetInput(polyData) glyph3D.ScalingOff() #Needed, otherwise only the red cube is visible glyph3D.Update() # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyph3D.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def load_octomap(octomap_h5_file, conf=0.9, wireframe=False): h5f = h5py.File(octomap_h5_file, 'r') octree_data = h5f['octree'][...] octree_data = octree_data[octree_data[:, 4] > conf] pts = vtk.vtkPoints() #vtk_pt_data = converter.numpy_to_vtk(np.ascontiguousarray(octree_data[:, 0:3])) #pts.SetData(vtk_pt_data) use_colors = octree_data.shape[1] > 5 colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) #color_data = np.ascontiguousarray(octree_data[:, 5:8]) #colors = converter.numpy_to_vtk(color_data) #colors.SetName('ColorArray') #polydata.GetPointData().SetActiveScalars('ColorArray') for k in range(octree_data.shape[0]): pts.InsertNextPoint(*octree_data[k, 0:3]) if use_colors: r = int(octree_data[k, 5]) g = int(octree_data[k, 6]) b = int(octree_data[k, 7]) colors.InsertNextTupleValue((r, g, b)) polydata = vtk.vtkPolyData() polydata.SetPoints(pts) if use_colors: polydata.GetPointData().SetScalars(colors) cube = vtk.vtkCubeSource() cube.SetXLength(octree_data[0, 3]) cube.SetYLength(octree_data[0, 3]) cube.SetZLength(octree_data[0, 3]) glyph = vtk.vtkGlyph3D() if use_colors: glyph.SetColorModeToColorByScalar() glyph.SetSourceConnection(cube.GetOutputPort()) glyph.SetInput(polydata) glyph.ScalingOff() glyph.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(glyph.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) if wireframe: actor.GetProperty().SetRepresentationToWireframe() actor.GetProperty().SetLineWidth(1) actor.GetProperty().SetOpacity(0.2) actor.GetProperty().LightingOff() return actor
def testLinearHidden(self): hidden = vtk.vtkDataSetAttributes.HIDDENPOINT ghosts = vtk.vtkUnsignedCharArray() ghosts.SetName(vtk.vtkDataSetAttributes.GhostArrayName()) ghosts.SetNumberOfTuples(4) ghosts.SetValue(0, hidden) ghosts.SetValue(1, hidden) ghosts.SetValue(2, hidden) ghosts.SetValue(3, 0) self.doLinear(ghosts, 0)
def testLinearDuplicate(self): duplicate = vtk.vtkDataSetAttributes.DUPLICATEPOINT ghosts = vtk.vtkUnsignedCharArray() ghosts.SetName(vtk.vtkDataSetAttributes.GhostArrayName()) ghosts.SetNumberOfTuples(4) ghosts.SetValue(0, duplicate) ghosts.SetValue(1, duplicate) ghosts.SetValue(2, duplicate) ghosts.SetValue(3, 0) self.doLinear(ghosts, 3)
def get_new_vtk_data_array(self, scalar_dtype): if scalar_dtype == np.int32: return vtk.vtkIntArray() if scalar_dtype == np.ushort: return vtk.vtkUnsignedShortArray() if scalar_dtype == np.ubyte: return vtk.vtkUnsignedCharArray() if scalar_dtype == np.float32: return vtk.vtkFloatArray() print >> sys.stderr, '[ERROR] ' + str(scalar_dtype) + ' is not supported ' return None
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!"
def vtkTile(tile, min_temp, max_temp): # calcula a intensidade da cor para representar a temperatura. # vermelho, com pastilha. azul, estourou intensity = 255 - int(((tile.last_temp - min_temp) / (max_temp - min_temp)) * 256) if tile.bursted: color = (intensity, intensity, 255) else: color = (255, intensity, intensity) Points = vtk.vtkPoints() Triangles = vtk.vtkCellArray() Points.InsertNextPoint(*tile.edges[0]) Points.InsertNextPoint(*tile.edges[1]) Points.InsertNextPoint(*tile.edges[2]) Points.InsertNextPoint(*tile.edges[3]) Triangle1 = vtk.vtkTriangle(); Triangle1.GetPointIds().SetId(0, 0); Triangle1.GetPointIds().SetId(1, 1); Triangle1.GetPointIds().SetId(2, 2); Triangles.InsertNextCell(Triangle1); Triangle2 = vtk.vtkTriangle(); Triangle2.GetPointIds().SetId(0, 1); Triangle2.GetPointIds().SetId(1, 3); Triangle2.GetPointIds().SetId(2, 2); Triangles.InsertNextCell(Triangle2); Colors = vtk.vtkUnsignedCharArray(); Colors.SetNumberOfComponents(3); Colors.SetName("Colors"); Colors.InsertNextTuple3(*color); Colors.InsertNextTuple3(*color); polydata = vtk.vtkPolyData() polydata.SetPoints(Points) polydata.SetPolys(Triangles) polydata.GetCellData().SetScalars(Colors); polydata.Modified() polydata.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInput(polydata) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetAmbient(1.0) actor.GetProperty().SetDiffuse(0.0) return actor
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() points = vtk.vtkPoints() points.InsertNextPoint(0.0, 0.0, 0.0) points.InsertNextPoint(1.0, 0.0, 0.0) points.InsertNextPoint(0.0, 1.0, 0.0) pointsPolydata = vtk.vtkPolyData() pointsPolydata.SetPoints(points) vertexFilter = vtk.vtkVertexGlyphFilter() vertexFilter.SetInputConnection(pointsPolydata.GetProducerPort()) vertexFilter.Update() polydata = vtk.vtkPolyData() polydata.ShallowCopy(vertexFilter.GetOutput()) # Setup colors colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") colors.InsertNextTupleValue((255, 0, 0)) colors.InsertNextTupleValue((0, 255, 0)) colors.InsertNextTupleValue((0, 0, 255)) polydata.GetPointData().SetScalars(colors) # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(polydata.GetProducerPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetPointSize(5) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def boxesActor(boxes, color = (0, 0, 0, 100), wireframe=False): """Create a vtkActor representing a list of hexahedron. The hexahedrons are assumed to be aligned with the coordinate axis, and are given using their extremal points. Args: box: [[[xmin, ymin, zmin], [xmax, ymax, zmax]], ...] color: RGBA color wireframe: if True, the boxes are drawn in wireframe mode """ grid = vtk.vtkUnstructuredGrid() points = vtk.vtkPoints() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(4) colors.SetName("Colors") for (index, box) in enumerate(boxes): colors.InsertNextTuple4(color[0], color[1], color[2], 100) P0 = [box[0][0], box[0][1], box[0][2]] P1 = [box[1][0], box[0][1], box[0][2]] P2 = [box[1][0], box[1][1], box[0][2]] P3 = [box[0][0], box[1][1], box[0][2]] P4 = [box[0][0], box[0][1], box[1][2]] P5 = [box[1][0], box[0][1], box[1][2]] P6 = [box[1][0], box[1][1], box[1][2]] P7 = [box[0][0], box[1][1], box[1][2]] points.InsertNextPoint(P0) points.InsertNextPoint(P1) points.InsertNextPoint(P2) points.InsertNextPoint(P3) points.InsertNextPoint(P4) points.InsertNextPoint(P5) points.InsertNextPoint(P6) points.InsertNextPoint(P7) hexa = vtk.vtkHexahedron() hexa.GetPointIds().SetNumberOfIds(8) for i in range(8): hexa.GetPointIds().SetId(i, 8 * index + i) grid.InsertNextCell(hexa.GetCellType(), hexa.GetPointIds()) grid.SetPoints(points) grid.GetCellData().SetScalars(colors) mapper = vtk.vtkDataSetMapper() set_mapper_input(mapper, grid) actor = vtk.vtkActor() actor.SetMapper(mapper) if wireframe: actor.GetProperty().SetRepresentationToWireframe() actor.GetProperty().SetLineWidth(2.) return actor
def testNonLinear(self): pts = vtk.vtkPoints() pts.SetNumberOfPoints(10) pts.InsertPoint(0, (0, 0, 0)) pts.InsertPoint(1, (1, 0, 0)) pts.InsertPoint(2, (0.5, 1, 0)) pts.InsertPoint(3, (0.5, 0.5, 1)) pts.InsertPoint(4, (0.5, 0, 0)) pts.InsertPoint(5, (1.25, 0.5, 0)) pts.InsertPoint(6, (0.25, 0.5, 0)) pts.InsertPoint(7, (0.25, 0.25, 0.5)) pts.InsertPoint(8, (0.75, 0.25, 0.5)) pts.InsertPoint(9, (0.5, 0.75, 0.5)) te = vtk.vtkQuadraticTetra() ptIds = te.GetPointIds() for i in range(10): ptIds.SetId(i, i) ghosts = vtk.vtkUnsignedCharArray() ghosts.SetName(vtk.vtkDataSetAttributes.GhostArrayName()) ghosts.SetNumberOfTuples(10) ghosts.SetValue(0, 1) ghosts.SetValue(1, 1) ghosts.SetValue(2, 1) ghosts.SetValue(3, 0) ghosts.SetValue(4, 1) ghosts.SetValue(5, 1) ghosts.SetValue(6, 1) ghosts.SetValue(7, 0) ghosts.SetValue(8, 0) grid = vtk.vtkUnstructuredGrid() grid.Allocate(1, 1) grid.InsertNextCell(te.GetCellType(), te.GetPointIds()) grid.SetPoints(pts) grid.GetPointData().AddArray(ghosts) ugg = vtk.vtkUnstructuredGridGeometryFilter() ugg.SetInputData(grid) dss = vtk.vtkDataSetSurfaceFilter() dss.SetNonlinearSubdivisionLevel(2) dss.SetInputConnection(ugg.GetOutputPort()) dss.Update() self.assertEqual(dss.GetOutput().GetNumberOfCells(), 48)
def _polydata(self, inflated=False): """ Compute a vtk polydata of the TriSurface. This code uses vtk. Parameters ---------- inflated: bool (optional, default False) If True use the inflated vertices. Returns ------- polydata: vtkPolyData the TriSurface vtk polydata. """ import vtk # Select the vertices to use labels = copy.deepcopy(self.labels) if inflated: vertices = self.inflated_vertices else: vertices = self.vertices # First setup points, triangles and colors. vtk_points = vtk.vtkPoints() vtk_triangles = vtk.vtkCellArray() vtk_colors = vtk.vtkUnsignedCharArray() vtk_colors.SetNumberOfComponents(1) labels[numpy.where(labels < 0)] = 0 for index in range(len(vertices)): vtk_points.InsertNextPoint(vertices[index]) vtk_colors.InsertNextTuple1(labels[index]) for triangle in self.triangles: vtk_triangle = vtk.vtkTriangle() vtk_triangle.GetPointIds().SetId(0, triangle[0]) vtk_triangle.GetPointIds().SetId(1, triangle[1]) vtk_triangle.GetPointIds().SetId(2, triangle[2]) vtk_triangles.InsertNextCell(vtk_triangle) # Create (geometry and topology) the associated polydata polydata = vtk.vtkPolyData() polydata.SetPoints(vtk_points) polydata.GetPointData().SetScalars(vtk_colors) polydata.SetPolys(vtk_triangles) return polydata
def colorize_verts_ply(ply_in_filename, ply_out_filename, image, camera): """ add per-vertex color information based on projections into images Parameters ---------- ply_in_filename : str ply_out_filename : str image : array_like The image camera : """ # read in PLY file reader = vtk.vtkPLYReader() reader.SetFileName(ply_in_filename) reader.Update() data = reader.GetOutput() # create Color data colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") num_pts = data.GetNumberOfPoints() for n in range(num_pts): pt3d = data.GetPoint(n) pt2d = camera.project_point(pt3d).astype(np.int) img_size = np.array((image.shape[1], image.shape[0])) if np.any(pt2d < 0) or np.any(pt2d >= img_size): color = (128, 128, 128) else: color = image[pt2d[1], pt2d[0], :] # convert gray to RGB if len(color) == 1: color = (color, color, color) colors.InsertNextTuple3(color[0], color[1], color[2]) data.GetPointData().SetScalars(colors) data.Update() # write new PLY writer = vtk.vtkPLYWriter() writer.SetFileName(ply_out_filename) writer.SetInput(data) writer.SetArrayName("Colors") writer.Update() writer.Write()
def ConstructVTKMesh(self): """Construct polydata triangle mesh objects from data""" for set_indx, set_points in enumerate(self.plant_data.triMeshPntSets): mesh_points = vtk.vtkPoints() mesh_triangles = vtk.vtkCellArray() set_polydata = vtk.vtkPolyData() set_cols = vtk.vtkUnsignedCharArray() set_cols.SetNumberOfComponents(3) set_cols.SetName("Colors") for point_idx, point in enumerate(set_points): mesh_points.InsertNextPoint(point) set_cols.InsertNextTuple( (round( 255 * self.plant_data.triMeshColSets[set_indx][point_idx][0] ), round( 255 * self.plant_data.triMeshColSets[set_indx][point_idx][1] ), round( 255 * self.plant_data.triMeshColSets[set_indx][point_idx][2] ))) for indx_tuple in self.plant_data.triMeshPntIndxSets[set_indx]: triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, indx_tuple[0]) triangle.GetPointIds().SetId(1, indx_tuple[1]) triangle.GetPointIds().SetId(2, indx_tuple[2]) mesh_triangles.InsertNextCell(triangle) set_polydata.SetPoints(mesh_points) set_polydata.SetPolys(mesh_triangles) set_polydata.GetPointData().SetScalars(set_cols) smooth_filter = vtk.vtkSmoothPolyDataFilter() smooth_filter.SetInputData(set_polydata) smooth_filter.FeatureEdgeSmoothingOn() smooth_filter.BoundarySmoothingOn() smooth_filter.Update() self.MeshPolydataList.append(smooth_filter.GetOutput()) self.vtkObjects.extend( [set_polydata, mesh_points, mesh_triangles, set_cols])
def __init__(self): vtkCameraManipulator.__init__(self) self._start_position = [0, 0] self._end_position = [0, 0] self._pixel_array = vtk.vtkUnsignedCharArray() self._left_button_down = False self._ctrl_left_button_down = False self._right_button_down = False self._middle_button_down = False self._down_pos = None self._up_pos = None self._point_list = [] self.renderer = None self.iren = None #self.reset_polygon() self._points = 0 self.polygon = vtk.vtkPolygon() self.poly_data = vtk.vtkPolyData() self.poly_points = vtk.vtkPoints() self.poly_data.SetPoints(self.poly_points) self.cell_array = vtk.vtkCellArray() self.cell_array.InsertNextCell(self.polygon) self.cell_array.Squeeze() self.poly_data.SetPolys(self.cell_array) self.done_picking = MrSignal() self._picking_active = False self.poly_pick_filter = PolyPickFilter() self.poly_pick_filter.set_poly_pick_data(self.poly_data) self.vtk_graphics = VTKGraphics.instance() from .picking_manager import PickingManager self.picking_manager = PickingManager.instance()
def findCellsWithin(self, xbounds=(), ybounds=(), zbounds=(), c=None): """ Find cells that are within specified bounds. Setting a color will add a vtk array to colorize these cells. """ if len(xbounds) == 6: bnds = xbounds else: bnds = list(self.bounds()) if len(xbounds) == 2: bnds[0] = xbounds[0] bnds[1] = xbounds[1] if len(ybounds) == 2: bnds[2] = ybounds[0] bnds[3] = ybounds[1] if len(zbounds) == 2: bnds[4] = zbounds[0] bnds[5] = zbounds[1] cellIds = vtk.vtkIdList() self.cell_locator = vtk.vtkCellTreeLocator() self.cell_locator.SetDataSet(self.polydata()) self.cell_locator.BuildLocator() self.cell_locator.FindCellsWithinBounds(bnds, cellIds) if c is not None: cellData = vtk.vtkUnsignedCharArray() cellData.SetNumberOfComponents(3) cellData.SetName('CellsWithinBoundsColor') cellData.SetNumberOfTuples(self.polydata(False).GetNumberOfCells()) defcol = np.array(self.color()) * 255 for i in range(cellData.GetNumberOfTuples()): cellData.InsertTuple(i, defcol) self.polydata(False).GetCellData().SetScalars(cellData) self._mapper.ScalarVisibilityOn() flagcol = np.array(colors.getColor(c)) * 255 cids = [] for i in range(cellIds.GetNumberOfIds()): cid = cellIds.GetId(i) if c is not None: cellData.InsertTuple(cid, flagcol) cids.append(cid) return np.array(cids)
def computeGliderTrajectoryColors(gliderTrajectory, minVerticalSpeed, maxVerticalSpeed): """ Compute the colors to display the glider's trajectory. If the vertical speed at a given point is >= 0, it will be from yellow to red (for hot air), and if the vertical speed is < 0, it will be blue. Two LookupTable were used to have to different scales of color for ascending and descending trajectory. Args: gliderTrajectory: The glider trajectory minVerticalSpeed: min vertical speed maxVerticalSpeed: max vertical speed Returns: An array of colors """ lutAsc = vtk.vtkLookupTable() lutAsc.SetTableRange(0, maxVerticalSpeed) lutAsc.SetHueRange(1 / 8, 0) lutAsc.Build() lutDesc = vtk.vtkLookupTable() lutDesc.SetTableRange(minVerticalSpeed, 0) lutDesc.SetHueRange(5 / 8, 1 / 2) lutDesc.Build() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") for i in range(0, len(gliderTrajectory)): dcolor = [0, 0, 0] if (i == 0): lutDesc.GetColor(0, dcolor) else: verticalSpeed = computeVerticalSpeed(gliderTrajectory, i) if (verticalSpeed >= 0): lutAsc.GetColor(verticalSpeed, dcolor) else: lutDesc.GetColor(verticalSpeed, dcolor) color = [0, 0, 0] for k in range(0, 3): color[k] = 255 * dcolor[k] colors.InsertNextTuple(color) return colors
def __init__(self, file_name, zMin=-10.0, zMax=10.0, max_num_points=1e6): # setting up visuvalization params print 'Setting up visuvalization params' # read the file self.dataFile = open(file_name, "r") # set maximum number of points to be used self.maxNumPoints = max_num_points # initialize a poly data self.vtkPolyData = vtk.vtkPolyData() self.clearPoints() # The mapper is responsible for pushing the geometry into the graphics # library. It may also do color mapping, if scalars or other # attributes are defined. mapper = vtk.vtkPolyDataMapper() mapper.SetInput(self.vtkPolyData) mapper.SetColorModeToDefault() mapper.SetScalarRange(zMin, zMax) mapper.SetScalarVisibility(1) self.vtkActor = vtk.vtkActor() self.vtkActor.SetMapper(mapper) # Setup the colors array self.colors = vtk.vtkUnsignedCharArray() self.colors.SetNumberOfComponents(3) self.colors.SetName("colors") # set up color dicts r = [255, 0, 0] g = [0, 255, 0] br = [244, 164, 96] y = [0, 255, 255] p = [255, 255, 0] # match labels to corresponding color self.colorDict = {1004: g, 1200: br, 1100: y, 1103: r, 1400: p} # dict for feeatures self.feature_dict = {1004: 0, 1200: 1, 1100: 2, 1103: 3, 1400: 4} print 'Done Setting up visuvalization'
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() # Provide some geometry resolution = 8 aPlane = vtk.vtkPlaneSource() aPlane.SetXResolution(resolution) aPlane.SetYResolution(resolution) aPlane.Update() # Create cell data cellData = vtk.vtkUnsignedCharArray() cellData.SetNumberOfComponents(3) cellData.SetNumberOfTuples(aPlane.GetOutput().GetNumberOfCells()) for i in range(aPlane.GetOutput().GetNumberOfCells()): rgb = random.randint(64, 255), random.randint(64, 255), random.randint( 64, 255) cellData.InsertTuple(i, rgb) aPlane.GetOutput().GetCellData().SetScalars(cellData) # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(aPlane.GetOutputPort()) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def __init__(self, colors=COLOR_MAP, *args, **kwargs): super(VTKCanon, self).__init__(*args, **kwargs) self.path_colors = colors # Create a vtkUnsignedCharArray container and store the colors in it self.colors = vtk.vtkUnsignedCharArray() self.colors.SetNumberOfComponents(4) self.points = vtk.vtkPoints() self.lines = vtk.vtkCellArray() self.poly_data = vtk.vtkPolyData() self.data_mapper = vtk.vtkPolyDataMapper() self.path_actor = vtk.vtkActor() self.path_points = [] self.append_path_point = self.path_points.append
def testNonLinearDuplicate(self): duplicate = vtk.vtkDataSetAttributes.DUPLICATEPOINT ghosts = vtk.vtkUnsignedCharArray() ghosts.SetName(vtk.vtkDataSetAttributes.GhostArrayName()) ghosts.SetNumberOfTuples(10) ghosts.SetValue(0, duplicate) ghosts.SetValue(1, duplicate) ghosts.SetValue(2, duplicate) ghosts.SetValue(3, 0) ghosts.SetValue(4, duplicate) ghosts.SetValue(5, duplicate) ghosts.SetValue(6, duplicate) ghosts.SetValue(7, 0) ghosts.SetValue(8, 0) ghosts.SetValue(9, 0) self.doNonLinear(ghosts, 64)
def testNonLinearHidden(self): hidden = vtk.vtkDataSetAttributes.HIDDENPOINT ghosts = vtk.vtkUnsignedCharArray() ghosts.SetName(vtk.vtkDataSetAttributes.GhostArrayName()) ghosts.SetNumberOfTuples(10) ghosts.SetValue(0, hidden) ghosts.SetValue(1, hidden) ghosts.SetValue(2, hidden) ghosts.SetValue(3, 0) ghosts.SetValue(4, hidden) ghosts.SetValue(5, hidden) ghosts.SetValue(6, hidden) ghosts.SetValue(7, 0) ghosts.SetValue(8, 0) ghosts.SetValue(9, 0) self.doNonLinear(ghosts, 0)
def color_electrodes_by_scalars(self, scalar_array, lut=None): s_array = np.array(scalar_array, dtype=np.float) self.electrode_colors = vtk.vtkUnsignedCharArray() self.electrode_colors.SetNumberOfComponents(3) if lut is None: min, max = np.min(s_array), np.max(s_array) lut = divergent_color_lut(table_size=len(s_array), table_range=[min, max]) for scalar in scalar_array: color_tuple = [0, 0, 0] lut.GetColor(scalar, color_tuple) color_tuple = map(lambda x: int(round(x * 255)), color_tuple) self.electrode_colors.InsertNextTupleValue(color_tuple)
def getImage(self): r""" Return an array representation of the image Returns ------- im: ndarray The array representation of the image """ vtkRGB = vtk.vtkUnsignedCharArray() width, height = self.GetSize() self.GetPixelData(0, 0, width-1, height-1, 1, vtkRGB) vtkRGB.Squeeze() im = np.flipud(np.resize(np.array(vtkRGB), [height, width, 3])) / 255.0 return im
def __init__(self, mainwindow): self.mainwindow = mainwindow self.segment_dict = dict() self.segment_keys = [] self.segment_data = None self.segments = [ 'HED', 'LCL', 'LFE', 'LFO', 'LHN', 'LHU', 'LRA', 'LTI', 'PEL', 'RCL', 'RFE', 'RFO', 'RHN', 'RHU', 'RRA', 'RTI', 'TRX' ] named_colours = vtk.vtkNamedColors() self.colors = vtk.vtkUnsignedCharArray() self.colors.SetNumberOfComponents(3) colours = ['Blue', 'Red', 'Green'] for colour in colours: self.colors.InsertNextTypedTuple(named_colours.GetColor3ub(colour)) self.axes = ('O', 'P', 'A', 'L') self.using_pycgm_segments = False
def create_pointcloud_actor(points, colors=None): """Creates a vtkActor with the point cloud from numpy arrays points: numpy.ndarray pointcloud with shape (n,3) colors: numpy.ndarray uint8 array with colors for each point. shape is (n,3) Returns vtkActor object """ import vtk vpoints = vtk.vtkPoints() vpoints.SetNumberOfPoints(points.shape[0]) for i in range(points.shape[0]): vpoints.SetPoint(i, points[i]) vpoly = vtk.vtkPolyData() vpoly.SetPoints(vpoints) if not colors is None: vcolors = vtk.vtkUnsignedCharArray() vcolors.SetNumberOfComponents(3) vcolors.SetName("Colors") vcolors.SetNumberOfTuples(points.shape[0]) for i in range(points.shape[0]): vcolors.SetTuple3(i, colors[i, 0], colors[i, 1], colors[i, 2]) vpoly.GetPointData().SetScalars(vcolors) vcells = vtk.vtkCellArray() for i in range(points.shape[0]): vcells.InsertNextCell(1) vcells.InsertCellPoint(i) vpoly.SetVerts(vcells) mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(vpoly) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetPointSize(3) return actor
def create_actor(path, N, time_step, min, max, particles_size): #Use an auxiliar array to work with a variable number of points, #allowing the user to make diferent points simulation with good results array_data = np.zeros((N, 4)) array_3d = load_data(path) #Fill the auxiliar array with the data of the original one for point_number in range(0, N): array_data[point_number] = array_3d[time_step][point_number] #Colors Colors = vtk.vtkUnsignedCharArray() Colors.SetNumberOfComponents(3) Colors.SetName("Colors") # Generate point positions and insert in vtkPoints color = [0, 0, 0] points = vtk.vtkPoints() for x in np.arange(0, N): points.InsertNextPoint(array_data[x][0], array_data[x][1], array_data[x][2]) color = colors.calculate_color_by_amplitude(array_data[x][3], min, max) Colors.InsertNextTuple3(color[0], color[1], color[2]) polyData = vtk.vtkPolyData() polyData.SetPoints(points) polyData.GetPointData().SetScalars(Colors) vertexFilter = vtk.vtkVertexGlyphFilter() vertexFilter.SetInputData(polyData) vertexFilter.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(vertexFilter.GetOutputPort()) mapper.ScalarVisibilityOn() actor = vtk.vtkActor() actor.SetMapper(mapper) #Point size actor.GetProperty().SetPointSize(particles_size) return actor
def generate_sphere(root, color): s = vtk.vtkSphereSource() s.SetRadius(root['radius']) s.SetCenter(root['x'], root['y'], root['z']) s.SetThetaResolution(32) s.SetPhiResolution(16) s.Update() pd = s.GetOutput() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("colors") points = pd.GetPoints() for i in range(points.GetNumberOfPoints()): colors.InsertNextTuple3(color[0], color[1], color[2]) pd.GetPointData().AddArray(colors) return pd
def createPlaneActor2(): xsize = params.PlaneXSize ysize = params.PlaneYSize center = params.PlaneCenter points = vtk.vtkPoints() points.InsertNextPoint( (center[0] - xsize / 2, center[1] - ysize / 2, center[2] - 0.1)) points.InsertNextPoint( (center[0] + xsize / 2, center[1] - ysize / 2, center[2] - 0.1)) points.InsertNextPoint( (center[0] + xsize / 2, center[1] + ysize / 2, center[2] - 0.1)) points.InsertNextPoint( (center[0] - xsize / 2, center[1] + ysize / 2, center[2] - 0.1)) triangle = vtk.vtkTriangle() triangle.GetPointIds().SetId(0, 0) triangle.GetPointIds().SetId(1, 1) triangle.GetPointIds().SetId(2, 2) triangle2 = vtk.vtkTriangle() triangle2.GetPointIds().SetId(0, 2) triangle2.GetPointIds().SetId(1, 3) triangle2.GetPointIds().SetId(2, 0) triangles = vtk.vtkCellArray() triangles.InsertNextCell(triangle) triangles.InsertNextCell(triangle2) colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") colors.InsertNextTuple3(255, 0, 0) colors.InsertNextTuple3(0, 255, 0) colors.InsertNextTuple3(0, 0, 255) colors.InsertNextTuple3(0, 255, 0) trianglePolyData = vtk.vtkPolyData() trianglePolyData.SetPoints(points) trianglePolyData.SetPolys(triangles) trianglePolyData.GetPointData().SetScalars(colors) return build_actor(trianglePolyData, True)
def __init__(self, shape='sphere'): self.electrode_points = vtk.vtkPoints() self.electrode_colors = vtk.vtkUnsignedCharArray() self.electrode_colors.SetNumberOfComponents(3) if shape == 'sphere': self.e_glyph_shape = vtk.vtkSphereSource() self.e_glyph_shape.SetRadius(3.0) elif shape == 'cone': self.e_glyph_shape = vtk.vtkConeSource() self.e_glyph_shape.SetResolution(5) self.e_glyph_shape.SetHeight(5) self.e_glyph_shape.SetRadius(5) self.opacity = None self.color = None
def __init__(self, z_min=-1.0, z_max=1.0, max_num=1e6): self.max_num = max_num self.vtkPolyData = vtk.vtkPolyData() self.vtkPoints = vtk.vtkPoints() self.vtkCells = vtk.vtkCellArray() self.vtkDepth = vtk.vtkDoubleArray() #setup colors self.colors = vtk.vtkUnsignedCharArray() self.colors.SetNumberOfComponents(3) self.colors.SetName("Colors") self.clear() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(self.vtkPolyData) # mapper.SetColorModeToDefault() mapper.SetScalarRange(z_min, z_max) mapper.SetScalarVisibility(1) self.vtkActor = vtk.vtkActor() self.vtkActors = [self.vtkActor] self.vtkActor.SetMapper(mapper)
def GenerateColors(num, color_name="green"): # set color for each point colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") # list some colors red = [255, 0, 0] green = [0, 255, 0] blue = [0, 0, 255] if color_name == "red": color = red elif color_name == "green": color = green elif color_name == "blue": color = blue for i in range(num): colors.InsertNextTypedTuple(color) return colors
def draw_ray(cls, vtk_renderer, p0, p1, width, color): # Create the polydata where we will store all the geometric data linesPolyData = vtk.vtkPolyData() pts = vtk.vtkPoints() pts.InsertNextPoint(p0) pts.InsertNextPoint(p1) # Add the points to the polydata container linesPolyData.SetPoints(pts) # Create the line between p0 and p1 line = vtk.vtkLine() line.GetPointIds().SetId(0, 0) line.GetPointIds().SetId(1, 1) # Create a vtkCellArray container and store the lines in it lines = vtk.vtkCellArray() lines.InsertNextCell(line) # Add the lines to the polydata container linesPolyData.SetLines(lines) # Create a vtkUnsignedCharArray container and store the colors in it namedColors = vtk.vtkNamedColors() colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) try: colors.InsertNextTupleValue(namedColors.GetColor3ub(color)) except AttributeError: # For compatibility with new VTK generic data arrays. colors.InsertNextTypedTuple(namedColors.GetColor3ub(color)) linesPolyData.GetCellData().SetScalars(colors) # Setup the visualization pipeline mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(linesPolyData) actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetLineWidth(width) vtk_renderer.AddActor(actor) return actor
def SetPoint(pos,r,g,blue): sphereStartSource = vtk.vtkSphereSource() sphereStartSource.SetCenter(pos) sphereStartSource.SetRadius(1) point = sphereStartSource.GetOutput() sphereStartSource.Update() color = [r, g, blue] colorsP = vtk.vtkUnsignedCharArray() colorsP.SetNumberOfComponents(3) colorsP.SetName("ColorsofPoints") # colors.SetNumberOfTuples(96) # print("ok") for k in range(96): colorsP.InsertNextTuple(color) sphereStartSource.Update() point.GetCellData().SetScalars(colorsP) appendPos.AddInputConnection(sphereStartSource.GetOutputPort())
def createLineVTKData(pts, col): points = vtk.vtkPoints() for p in pts: points.InsertNextPoint(p) lines = vtk.vtkCellArray() pl = vtk.vtkPolyLine() pl.GetPointIds().SetNumberOfIds(points.GetNumberOfPoints()) for i in range(points.GetNumberOfPoints()): pl.GetPointIds().SetId(i, i) lines.InsertNextCell(pl) polydata = vtk.vtkPolyData() polydata.SetLines(lines) polydata.SetPoints(points) colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") colors.InsertNextTupleValue(col) polydata.GetCellData().SetScalars(colors) return polydata
def make_axis_actor(): points = vtk.vtkPoints() points.InsertNextPoint([0, 0, 0]) # 0: origo points.InsertNextPoint([100, 0, 0]) # 1: x points.InsertNextPoint([0, 100, 0]) # 2: y points.InsertNextPoint([0, 0, 100]) # 3: z x = vtk.vtkLine() x.GetPointIds().SetId(0, 0) x.GetPointIds().SetId(1, 1) y = vtk.vtkLine() y.GetPointIds().SetId(0, 0) y.GetPointIds().SetId(1, 2) z = vtk.vtkLine() z.GetPointIds().SetId(0, 0) z.GetPointIds().SetId(1, 3) cells = vtk.vtkCellArray() cells.InsertNextCell(x) cells.InsertNextCell(y) cells.InsertNextCell(z) colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.InsertNextTuple3(255, 0, 0) colors.InsertNextTuple3(0, 255, 0) colors.InsertNextTuple3(0, 0, 255) lines = vtk.vtkPolyData() lines.SetPoints(points) lines.SetLines(cells) lines.GetCellData().SetScalars(colors) mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(lines) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def xy_axis(apoints_path): # print a green y-positive and a x-positive line in the centre sensor = pd.read_csv(apoints_path) mid_x = sensor[['sen_x']].mean(axis=0) mid_y = sensor[['sen_y']].mean(axis=0) mid_z = sensor[['sen_z']].mean(axis=0) min_z = sensor[['sen_z']].min(axis=0) max_x = sensor[['sen_x']].max(axis=0) max_y = sensor[['sen_y']].max(axis=0) pts = vtk.vtkPoints() pts.InsertNextPoint([mid_x, mid_y, min_z]) pts.InsertNextPoint([max_x, mid_y, min_z]) pts.InsertNextPoint([mid_x, max_y, min_z]) # Setup two colors - one for each line red = [255, 0, 0] green = [0, 255, 0] colors = vtk.vtkUnsignedCharArray() colors.SetNumberOfComponents(3) colors.SetName("Colors") colors.InsertNextTupleValue(red) colors.InsertNextTupleValue(green) line0 = vtk.vtkLine() line0.GetPointIds().SetId(0, 0) line0.GetPointIds().SetId(1, 1) line1 = vtk.vtkLine() line1.GetPointIds().SetId(0, 0) line1.GetPointIds().SetId(1, 2) lines = vtk.vtkCellArray() lines.InsertNextCell(line0) lines.InsertNextCell(line1) linespolydata = vtk.vtkPolyData() linespolydata.SetPoints(pts) linespolydata.SetLines(lines) linespolydata.GetCellData().SetScalars(colors) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(linespolydata) actor = vtk.vtkActor() actor.SetMapper(mapper) mid_point = [mid_x, mid_y, mid_z] return actor, mid_point
def _format_outputVTK(polyData, clusterIdx, colour, centroids, rejIdx=[]): """ *INTERNAL FUNCTION* Formats polydata with cluster index and colour. INPUT: polyData - polydata for information to be applied to clusterIdx - cluster indices to be applied to each fiber within the polydata model colour - colours to be applied to each fiber within the polydata model centroid - centroid location to associated with each cluster rejIdx - indices to reject OUTPUT: polyData - updated polydata with cluster and colour information """ dataColour = vtk.vtkUnsignedCharArray() dataColour.SetNumberOfComponents(3) dataColour.SetName('Colour') clusterLabel = vtk.vtkIntArray() clusterLabel.SetNumberOfComponents(1) clusterLabel.SetName('ClusterLabel') centroid = vtk.vtkFloatArray() centroid.SetNumberOfComponents(centroids.shape[1]) centroid.SetName('Centroid') for fidx in range(len(clusterIdx)): if fidx in rejIdx: continue dataColour.InsertNextTuple3(colour[clusterIdx[fidx], 0], colour[clusterIdx[fidx], 1], colour[clusterIdx[fidx], 2]) clusterLabel.InsertNextTuple1(int(clusterIdx[fidx])) centroid.InsertNextTuple(centroids[clusterIdx[fidx], :]) polyData.GetCellData().AddArray(dataColour) polyData.GetCellData().AddArray(clusterLabel) polyData.GetCellData().AddArray(centroid) return polyData
def __init__(self, zMin=-10.0, zMax=10.0, maxNumPoints=1e6): self.maxNumPoints = maxNumPoints self.vtkPolyData = vtk.vtkPolyData() #setup colors self.colors = vtk.vtkUnsignedCharArray() self.colors.SetNumberOfComponents(3) self.colors.SetName("Colors") self.clearPoints() self.vtkPolyData.GetPointData().SetScalars(self.colors) mapper = vtk.vtkPolyDataMapper() mapper.SetInput(self.vtkPolyData) mapper.SetColorModeToDefault() mapper.SetScalarRange(zMin, zMax) mapper.SetScalarVisibility(1) self.vtkActor = vtk.vtkActor() self.vtkActor.SetMapper(mapper) self.vtkActor.GetProperty().SetPointSize(3)
def set_objects(self, corners, colour=None): self.create_point_corners(corners) lines = self.create_lines() self.vtk_poly_data.SetPoints(self.vtk_points) self.vtk_poly_data.SetLines(lines) # Setup the colours array colours = vtk.vtkUnsignedCharArray() colours.SetNumberOfComponents(3) colours.SetName("Colours") if colour is None: colour = [0, 255, 0] # Add the colours we created to the colours array for i in range(12): colours.InsertNextTypedTuple(colour) self.vtk_poly_data.GetCellData().SetScalars(colours) self.vtk_data_mapper.SetInputData(self.vtk_poly_data) self.vtk_actor.SetMapper(self.vtk_data_mapper)