def initArea(self): ''' Sets up the VTK simulation area :return:None ''' self.actors_dict = {} self.actorCollection=vtk.vtkActorCollection() self.borderActor = vtk.vtkActor() self.borderActorHex = vtk.vtkActor() self.clusterBorderActor = vtk.vtkActor() self.clusterBorderActorHex = vtk.vtkActor() self.cellGlyphsActor = vtk.vtkActor() self.FPPLinksActor = vtk.vtkActor() # used for both white and colored links self.outlineActor = vtk.vtkActor() # self.axesActor = vtk.vtkCubeAxesActor2D() self.axesActor = vtk.vtkCubeAxesActor() self.outlineDim=[0,0,0] self.cellsActor = vtk.vtkActor() self.cellsActor.GetProperty().SetInterpolationToFlat() # ensures that pixels are drawn exactly not with interpolations/antialiasing self.hexCellsActor = vtk.vtkActor() self.hexCellsActor.GetProperty().SetInterpolationToFlat() # ensures that pixels are drawn exactly not with interpolations/antialiasing self.conActor = vtk.vtkActor() self.conActor.GetProperty().SetInterpolationToFlat() self.hexConActor = vtk.vtkActor() self.hexConActor.GetProperty().SetInterpolationToFlat() self.contourActor = vtk.vtkActor() self.glyphsActor=vtk.vtkActor() #self.linksActor=vtk.vtkActor() # # Concentration lookup table self.clut = vtk.vtkLookupTable() self.clut.SetHueRange(0.67, 0.0) self.clut.SetSaturationRange(1.0,1.0) self.clut.SetValueRange(1.0,1.0) self.clut.SetAlphaRange(1.0,1.0) self.clut.SetNumberOfColors(1024) self.clut.Build() # Contour lookup table # Do I need lookup table? May be just one color? self.ctlut = vtk.vtkLookupTable() self.ctlut.SetHueRange(0.6, 0.6) self.ctlut.SetSaturationRange(0,1.0) self.ctlut.SetValueRange(1.0,1.0) self.ctlut.SetAlphaRange(1.0,1.0) self.ctlut.SetNumberOfColors(1024) self.ctlut.Build()
def MakeLUT(tableSize): ''' Make a lookup table from a set of named colors. :param: tableSize - The table size :return: The lookup table. ''' nc = vtk.vtkNamedColors() lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(tableSize) lut.Build() # Fill in a few known colors, the rest will be generated if needed lut.SetTableValue(0,nc.GetColor4d("Black")) lut.SetTableValue(1,nc.GetColor4d("Banana")) lut.SetTableValue(2,nc.GetColor4d("Tomato")) lut.SetTableValue(3,nc.GetColor4d("Wheat")) lut.SetTableValue(4,nc.GetColor4d("Lavender")) lut.SetTableValue(5,nc.GetColor4d("Flesh")) lut.SetTableValue(6,nc.GetColor4d("Raspberry")) lut.SetTableValue(7,nc.GetColor4d("Salmon")) lut.SetTableValue(8,nc.GetColor4d("Mint")) lut.SetTableValue(9,nc.GetColor4d("Peacock")) return lut
def get_lookup_table(self, display_mode): """ Sets up and returns the lookup table depending upon the display mode """ lut = vtkLookupTable() ref_lut = vtkLookupTable() num_colours = 256 lut.SetNumberOfColors(num_colours) ref_lut.SetNumberOfColors(num_colours) if (display_mode == 'load'): lut.SetTableRange(0.0, 1.75) ref_lut.SetTableRange(0.0, 1.75) else: lut.SetTableRange(0.0, 1.0) ref_lut.SetTableRange(0.0, 1.0) lut.Build() ref_lut.Build() # invert the colours: we want red to be at the high end for j in range(num_colours): lut.SetTableValue(j, ref_lut.GetTableValue(num_colours-1-j)) return lut
def __init__(self): self.interactor = None self.image_original = None self.image_threshold = None self.render = None self.lut = vtk.vtkLookupTable() self.lut_original = vtk.vtkLookupTable() self.image_color = vtk.vtkImageMapToColors() self.blend = blend = vtk.vtkImageBlend() self.map = map = vtk.vtkImageMapper() self.actor = actor = vtk.vtkImageActor() self.actor2 = actor2 = vtk.vtkImageActor() self.actor3 = actor3 = vtk.vtkImageActor() self.image_color_o = vtk.vtkImageMapToColors() self.operation_type = 0 self.w = None self.slice = 0 self.clicked = 0 self.orientation = AXIAL self.w = (200, 1200)
def addArrayFromIdList(self, connectedIdList, inputModelNode, arrayName): if not inputModelNode: return inputModelNodePolydata = inputModelNode.GetPolyData() pointData = inputModelNodePolydata.GetPointData() numberofIds = connectedIdList.GetNumberOfIds() hasArrayInt = pointData.HasArray(arrayName) if hasArrayInt == 1: # ROI Array found pointData.RemoveArray(arrayName) arrayToAdd = vtk.vtkDoubleArray() arrayToAdd.SetName(arrayName) for i in range(0, inputModelNodePolydata.GetNumberOfPoints()): arrayToAdd.InsertNextValue(0.0) for i in range(0, numberofIds): arrayToAdd.SetValue(connectedIdList.GetId(i), 1.0) lut = vtk.vtkLookupTable() tableSize = 2 lut.SetNumberOfTableValues(tableSize) lut.Build() ID = inputModelNode.GetDisplayNodeID() slicer.app.mrmlScene().GetNodeByID(ID) displayNode = slicer.app.mrmlScene().GetNodeByID(ID) rgb = displayNode.GetColor() lut.SetTableValue(0, rgb[0], rgb[1], rgb[2], 1) lut.SetTableValue(1, 1.0, 0.0, 0.0, 1) arrayToAdd.SetLookupTable(lut) pointData.AddArray(arrayToAdd) inputModelNodePolydata.Modified() return True
def setParams(self): # You can use either Build() method (256 color by default) or # SetNumberOfTableValues() to allocate much more colors! self.lut = vtk.vtkLookupTable() # You need to explicitly call Build() when constructing the LUT by hand self.lut.Build() self.populateLookupTable()
def do_colour_mask(self, imagedata): scalar_range = int(imagedata.GetScalarRange()[1]) r, g, b = self.current_mask.colour # map scalar values into colors lut_mask = vtk.vtkLookupTable() lut_mask.SetNumberOfColors(256) lut_mask.SetHueRange(const.THRESHOLD_HUE_RANGE) lut_mask.SetSaturationRange(1, 1) lut_mask.SetValueRange(0, 255) lut_mask.SetRange(0, 255) lut_mask.SetNumberOfTableValues(256) lut_mask.SetTableValue(0, 0, 0, 0, 0.0) lut_mask.SetTableValue(1, 0, 0, 0, 0.0) lut_mask.SetTableValue(254, r, g, b, 1.0) lut_mask.SetTableValue(255, r, g, b, 1.0) lut_mask.SetRampToLinear() lut_mask.Build() # self.lut_mask = lut_mask # map the input image through a lookup table img_colours_mask = vtk.vtkImageMapToColors() img_colours_mask.SetLookupTable(lut_mask) img_colours_mask.SetOutputFormatToRGBA() img_colours_mask.SetInput(imagedata) img_colours_mask.Update() # self.img_colours_mask = img_colours_mask return img_colours_mask.GetOutput()
def _set_colour(self, imagedata, colour): scalar_range = int(imagedata.GetScalarRange()[1]) r, g, b = colour # map scalar values into colors lut_mask = vtk.vtkLookupTable() lut_mask.SetNumberOfColors(256) lut_mask.SetHueRange(const.THRESHOLD_HUE_RANGE) lut_mask.SetSaturationRange(1, 1) lut_mask.SetValueRange(0, 255) lut_mask.SetRange(0, 255) lut_mask.SetNumberOfTableValues(256) lut_mask.SetTableValue(0, 0, 0, 0, 0.0) lut_mask.SetTableValue(1, 1-r, 1-g, 1-b, 0.50) lut_mask.SetRampToLinear() lut_mask.Build() # map the input image through a lookup table img_colours_mask = vtk.vtkImageMapToColors() img_colours_mask.SetLookupTable(lut_mask) img_colours_mask.SetOutputFormatToRGBA() img_colours_mask.SetInput(imagedata) img_colours_mask.Update() return img_colours_mask.GetOutput()
def polyShowColorScalars(ren, obj): #@c Show scalar values on poly in renderer in color #@a ren: renderer #@a obj: object name if isinstance(obj,list): tag = "%s_%s" % (ren[0],obj[0]) elif isinstance(obj,str): tag = "%s_%s" % (ren[0],obj) else: raise ValueError("Argument type unsupported.") lookupColor = [None]*2 lookupColor[0] = "p_blueToRedLUT_"+tag lookupColor[1] = vtk.vtkLookupTable() lookupColor[1].SetHueRange(0.6667 ,0.0) lookupColor[1].SetSaturationRange(1.,1.) lookupColor[1].SetValueRange(1.,1.) lookupColor[1].SetAlphaRange(1.,1.) lookupColor[1].SetNumberOfColors(16384) lookupColor[1].Build() act = polyGetActor(ren,obj) act[1].GetMapper().SetLookupTable(lookupColor[1]) act[1].GetMapper().ScalarVisibilityOn() Range = act[1].GetMapper().GetInput().GetPointData().GetScalars().GetRange() act[1].GetMapper().SetScalarRange(Range[0],Range[1]) vis.render(ren) setattr(vis,act[0],act) setattr(vis,lookupColor[0],lookupColor) return
def __init__(self,data_reader): self.lut=vtk.vtkLookupTable() self.lut.SetNumberOfColors(256) self.lut.SetTableRange(data_reader.get_scalar_range()) self.lut.SetHueRange(0,1) self.lut.SetRange(data_reader.get_scalar_range()) self.lut.SetRange(data_reader.get_scalar_range()) self.lut.Build() self.arrow=vtk.vtkArrowSource() self.arrow.SetTipResolution(6) self.arrow.SetTipRadius(0.1) self.arrow.SetTipLength(0.35) self.arrow.SetShaftResolution(6) self.arrow.SetShaftRadius(0.03) self.glyph=vtk.vtkGlyph3D() self.glyph.SetInput(data_reader.get_data_set()) self.glyph.SetSource(self.arrow.GetOutput()) self.glyph.SetVectorModeToUseVector() self.glyph.SetColorModeToColorByScalar() self.glyph.SetScaleModeToScaleByVector() self.glyph.OrientOn() self.glyph.SetScaleFactor(0.002) mapper=vtk.vtkPolyDataMapper() mapper.SetInput(self.glyph.GetOutput()) mapper.SetLookupTable(self.lut) mapper.ScalarVisibilityOn() mapper.SetScalarRange(data_reader.get_scalar_range()) self.actor=vtk.vtkActor() self.actor.SetMapper(mapper)
def writeAllImageSlices(imgfn,pathfn,ext,output_dir): reader = vtk.vtkMetaImageReader() reader.SetFileName(imgfn) reader.Update() img = reader.GetOutput() parsed_path = parsePathFile(pathfn) slices = getAllImageSlices(img,parsed_path,ext) writer = vtk.vtkJPEGWriter() table = vtk.vtkLookupTable() scalar_range = img.GetScalarRange() table.SetRange(scalar_range[0], scalar_range[1]) # image intensity range table.SetValueRange(0.0, 1.0) # from black to white table.SetSaturationRange(0.0, 0.0) # no color saturation table.SetRampToLinear() table.Build() # Map the image through the lookup table color = vtk.vtkImageMapToColors() color.SetLookupTable(table) mkdir(output_dir) for i in range(len(slices)): color.SetInputData(slices[i]) writer.SetInputConnection(color.GetOutputPort()) writer.SetFileName(output_dir+'{}.jpg'.format(i)) writer.Update() writer.Write()
def setParams(self): # # You can use either Build() method (256 color by default) or # # SetNumberOfTableValues() to allocate much more colors! # self.celltypeLUT = vtk.vtkLookupTable() # # You need to explicitly call Build() when constructing the LUT by hand # self.celltypeLUT.Build() # # self.populate_cell_type_lookup_table() # self.populateLookupTable() # self.dim = [100, 100, 1] # Default values # for FPP links (and offset also for cell glyphs) self.eps = 1.e-4 # not sure how small this should be (checking to see if cell volume -> 0) self.stubSize = 3.0 # dangling line stub size for lines that wraparound periodic BCs # self.offset = 1.0 # account for fact that COM of cell is offset from visualized lattice # self.offset = 0.0 # account for fact that COM of cell is offset from visualized lattice # scaling factors to map square lattice to hex lattice (rf. CC3D Manual) self.xScaleHex = 1.0 self.yScaleHex = 0.866 self.zScaleHex = 0.816 self.lutBlueRed = vtk.vtkLookupTable() self.lutBlueRed.SetHueRange(0.667, 0.0) self.lutBlueRed.Build()
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 __init__(self, filename, max_num_of_vertices=-1, edge_color_filename=None): super(VTKVisualizer, self).__init__() self.vertex_id_idx_map = {} self.next_vertex_id = 0 self.edge_counter = 0 self.lookup_table = vtk.vtkLookupTable() self.lookup_table.SetNumberOfColors(int(1e8)) self.edge_color_tuples = {} self.edge_color_filename = edge_color_filename self.label_vertex_id_map = {} self.starting_vertex = None self.starting_vertex_index = -1 self.filename = filename self.max_num_of_vertices = max_num_of_vertices self.g = vtk.vtkMutableDirectedGraph() self.vertex_ids = vtk.vtkIntArray() self.vertex_ids.SetNumberOfComponents(1) self.vertex_ids.SetName(VERTEX_ID) self.labels = vtk.vtkStringArray() self.labels.SetNumberOfComponents(1) self.labels.SetName(LABELS) self.glyph_scales = vtk.vtkFloatArray() self.glyph_scales.SetNumberOfComponents(1) self.glyph_scales.SetName(SCALES) self.edge_weights = vtk.vtkDoubleArray() self.edge_weights.SetNumberOfComponents(1) self.edge_weights.SetName(WEIGHTS) self.edge_colors = vtk.vtkIntArray() self.edge_colors.SetNumberOfComponents(1) self.edge_colors.SetName(EDGE_COLORS)
def initArea(self): # Zoom items self.zitems = [] self.cellTypeActors={} self.outlineActor = vtk.vtkActor() self.outlineDim=[0,0,0] self.invisibleCellTypes={} self.typesInvisibleStr="" self.set3DInvisibleTypes() axesActor = vtk.vtkActor() axisTextActor = vtk.vtkFollower() self.clut = vtk.vtkLookupTable() self.clut.SetHueRange(0.67, 0.0) self.clut.SetSaturationRange(1.0,1.0) self.clut.SetValueRange(1.0,1.0) self.clut.SetAlphaRange(1.0,1.0) self.clut.SetNumberOfColors(1024) self.clut.Build() ## Set up the mapper and actor (3D) for concentration field. # self.conMapper = vtk.vtkPolyDataMapper() self.conActor = vtk.vtkActor() self.glyphsActor=vtk.vtkActor() # self.glyphsMapper=vtk.vtkPolyDataMapper() self.cellGlyphsActor = vtk.vtkActor() self.FPPLinksActor = vtk.vtkActor() # Weird attributes self.typeActors = {} # vtkActor
def __MakeLUT(self): ''' Make a lookup table using vtkColorSeries. :return: An indexed lookup table. ''' # Make the lookup table. pal = "../util/color_circle_Ajj.pal" tableSize = 255 colorFunc = vtk.vtkColorTransferFunction() scalars = self.histo()[1] with open(pal) as f: lines = f.readlines() # lines.reverse() for i, line in enumerate(lines): l = line.strip() r, g, b = self.__hex2rgb(l[1:]) # print scalars[i], r, g, b colorFunc.AddRGBPoint(scalars[i], r, g, b) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(tableSize) lut.Build() for i in range(0, tableSize): rgb = list(colorFunc.GetColor(float(i)/tableSize))+[1] lut.SetTableValue(i, rgb) return lut
def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._volume_input = None self._opacity_tf = vtk.vtkPiecewiseFunction() self._colour_tf = vtk.vtkColorTransferFunction() self._lut = vtk.vtkLookupTable() # list of tuples, where each tuple (scalar_value, (r,g,b,a)) self._config.transfer_function = [ (0, (0,0,0), 0), (255, (255,255,255), 1) ] self._view_frame = None self._create_view_frame() self._bind_events() self.view() # all modules should toggle this once they have shown their # stuff. self.view_initialised = True self.config_to_logic() self.logic_to_config() self.config_to_view()
def _makeLut(self): """ Creates vtkLookupTable for mapping the volumes """ random.seed(0) lut = vtk.vtkLookupTable() cm = self._gidToColorMap # Just simple alias # Number of colors in LUT is equal to the largest GID +1 lut.SetNumberOfColors(max(cm.keys())+1) # Then, allocate the table with the colors. Iterate over all color # slots and assign proper color for i in range(lut.GetNumberOfColors()): # If given index is defined in indexer: # assign its color to the lookup table # otherwise set it to black if i in cm: if cm[i][0] == cm[i][1] == cm[i][2] == 119: c = map(lambda x: float(random.randint(0, 255))/255., [0,0,0]) lut.SetTableValue(i, c[0], c[1], c[2], 1) else: c = cm[i] c = map(lambda x: float(x)/255., c) lut.SetTableValue(i, c[0], c[1], c[2], 1) else: lut.SetTableValue(i, 0., 0., 0., 0.) # Build the LUT and return it lut.SetRange(0, max(cm.keys())) lut.Build() return lut
def jet(self, m=256): # blue, cyan, green, yellow, red, black lut = vtk.vtkLookupTable() lut.SetNumberOfColors(m) lut.SetHueRange(0.667,0.0) lut.Build() return lut
def __init__( self, interactor, **args ): ListWidget.__init__( self, interactor, **args ) self.lut = vtk.vtkLookupTable() self.image_data = {} self.colorMapManager = ColorMapManager( self.lut ) self.textMapper = None self.build()
def __init__(self): self.lookupTable = vtk.vtkLookupTable() self.lookupTable.SetRampToLinear() self.lookupTable.SetNumberOfTableValues(2) self.lookupTable.SetTableRange(0, 1) self.lookupTable.SetTableValue(0, 0, 0, 0, 0) self.colorMapper = vtk.vtkImageMapToRGBA() self.colorMapper.SetOutputFormatToRGBA() self.colorMapper.SetLookupTable(self.lookupTable) self.thresholdFilter = vtk.vtkImageThreshold() self.thresholdFilter.SetInValue(1) self.thresholdFilter.SetOutValue(0) self.thresholdFilter.SetOutputScalarTypeToUnsignedChar() # Feedback actor self.mapper = vtk.vtkImageMapper() self.dummyImage = vtk.vtkImageData() self.dummyImage.AllocateScalars(vtk.VTK_UNSIGNED_INT, 1) self.mapper.SetInputData(self.dummyImage) self.actor = vtk.vtkActor2D() self.actor.VisibilityOff() self.actor.SetMapper(self.mapper) self.mapper.SetColorWindow(255) self.mapper.SetColorLevel(128) # Setup pipeline self.colorMapper.SetInputConnection(self.thresholdFilter.GetOutputPort()) self.mapper.SetInputConnection(self.colorMapper.GetOutputPort())
def putMaskOnVTKGrid(data,grid,actorColor=None,deep=True): #Ok now looking msk = data.mask imsk = VN.numpy_to_vtk(msk.astype(numpy.int).flat,deep=deep) mapper = None if msk is not numpy.ma.nomask: msk = VN.numpy_to_vtk(numpy.logical_not(msk).astype(numpy.uint8).flat,deep=deep) if actorColor is not None: grid2 = vtk.vtkStructuredGrid() grid2.CopyStructure(grid) geoFilter = vtk.vtkDataSetSurfaceFilter() if grid.IsA("vtkStructuredGrid"): grid2.GetPointData().SetScalars(imsk) #grid2.SetCellVisibilityArray(imsk) p2c = vtk.vtkPointDataToCellData() p2c.SetInputData(grid2) geoFilter.SetInputConnection(p2c.GetOutputPort()) else: grid2.GetCellData().SetScalars(imsk) geoFilter.SetInputData(grid) geoFilter.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputData(geoFilter.GetOutput()) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(1) r,g,b = actorColor lut.SetNumberOfTableValues(2) lut.SetTableValue(0,r/100.,g/100.,b/100.) lut.SetTableValue(1,r/100.,g/100.,b/100.) mapper.SetLookupTable(lut) mapper.SetScalarRange(1,1) if grid.IsA("vtkStructuredGrid"): grid.SetPointVisibilityArray(msk) #grid.SetCellVisibilityArray(msk) return mapper
def SetLookupTable(self, lut): if not lut: return vtkViewImage.SetLookupTable(self, lut) v_min = self.Level - 0.5*self.Window v_max = self.Level + 0.5+self.Window #========================================================================== # In the case of a shift/scale, one must set the lut range to values # without this shift/scale, because the object can be shared by different # views. #========================================================================== lut.SetRange( (v_min-0.5*self.Shift)/self.Scale, (v_max-1.5*self.Shift)/self.Scale) #========================================================================== # Due to the same problem as above (shift/scale), one must copy the lut # so that it does not change values of the shared object. #========================================================================== realLut = vtk.vtkLookupTable.SafeDownCast(lut) if not realLut: raise RuntimeError, "Error: Cannot cast vtkScalarsToColors to vtkLookupTable." newLut = vtk.vtkLookupTable() newLut.DeepCopy(realLut) newLut.SetRange(v_min, v_max) self.WindowLevel.SetLookupTable(newLut) del newLut
def setupLuts(self): self.luts = [] # HSV (Blue to REd) Default lut = vtk.vtkLookupTable() lut.SetHueRange(0.667, 0.0) lut.SetNumberOfColors(256) lut.Build() self.luts.append(lut) # Diverging (Cool to Warm) color scheme ctf = vtk.vtkColorTransferFunction() ctf.SetColorSpaceToDiverging() ctf.AddRGBPoint(0.0, 0.230, 0.299, 0.754) ctf.AddRGBPoint(1.0, 0.706, 0.016, 0.150) cc = list() for i in xrange(256): cc.append(ctf.GetColor(float(i) / 255.0)) lut = vtk.vtkLookupTable() lut.SetNumberOfColors(256) for i, item in enumerate(cc): lut.SetTableValue(i, item[0], item[1], item[2], 1.0) lut.Build() self.luts.append(lut) # Shock ctf = vtk.vtkColorTransferFunction() min = 93698.4 max = 230532 ctf.AddRGBPoint(self._normalize(min, max, 93698.4), 0.0, 0.0, 1.0) ctf.AddRGBPoint(self._normalize(min, max, 115592.0), 0.0, 0.905882, 1.0) ctf.AddRGBPoint(self._normalize(min, max, 138853.0), 0.0941176, 0.733333, 0.027451) ctf.AddRGBPoint(self._normalize(min, max, 159378.0), 1.0, 0.913725, 0.00784314) ctf.AddRGBPoint(self._normalize(min, max, 181272.0), 1.0, 0.180392, 0.239216) ctf.AddRGBPoint(self._normalize(min, max, 203165.0), 1.0, 0.701961, 0.960784) ctf.AddRGBPoint(self._normalize(min, max, 230532.0), 1.0, 1.0, 1.0) cc = list() for i in xrange(256): cc.append(ctf.GetColor(float(i) / 255.0)) lut = vtk.vtkLookupTable() lut.SetNumberOfColors(256) for i, item in enumerate(cc): lut.SetTableValue(i, item[0], item[1], item[2], 1.0) lut.Build() self.luts.append(lut) self.current_lut = self.luts[0]
def draw(self, gfxwindow, device): device.comment("Material Color") if config.dimension() == 2: themesh = self.who().resolve(gfxwindow) polygons = self.polygons(gfxwindow, themesh) # colorcache is a dictionary of colors keyed by Material. It # prevents us from having to call material.fetchProperty for # each element. colorcache = {} for polygon, material in zip(polygons, self.materials(gfxwindow, themesh)): if material is not None: try: # If material has been seen already, retrieve its color. color = colorcache[material] except KeyError: # This material hasn't been seen yet. try: colorprop = material.fetchProperty('Color') color = colorprop.color() except ooferror.ErrNoSuchProperty: color = None colorcache[material] = color if color is not None: device.set_fillColor(color) device.fill_polygon(primitives.Polygon(polygon)) elif config.dimension() == 3: # TODO 3D: clean up this code in general, perhaps the look # up table should be a member of the microstructure... themesh = self.who().resolve(gfxwindow).getObject() grid = themesh.skelgrid numCells = grid.GetNumberOfCells() # TODO 3D: will need to handle the creation and deletion of this array within canvas... materialdata = vtk.vtkIntArray() materialdata.SetNumberOfValues(numCells) grid.GetCellData().SetScalars(materialdata) lut = vtk.vtkLookupTable() colordict = {} for i in xrange(numCells): cat = themesh.elements[i].dominantPixel(themesh.MS) materialdata.SetValue(i,cat) mat = themesh.elements[i].material(themesh) if mat is not None: try: color = colordict[cat] except KeyError: colorprop = mat.fetchProperty('Color') color = colorprop.color() colordict[cat] = color lut.SetNumberOfColors(max(colordict.keys())+1) lut.SetTableRange(min(colordict.keys()), max(colordict.keys())) for i in colordict: color = colordict[i] if color is not None: lut.SetTableValue(i,color.getRed(),color.getGreen(),color.getBlue(),1) else: lut.SetTableValue(i,0,0,0,0) device.draw_unstructuredgrid_with_lookuptable(grid, lut, mode="cell", scalarbar=False)
def __init__(self): ''' Constructor ''' self.__OrientationMatrix = vtk.vtkMatrix4x4() self.__CornerAnnotation = vtk.vtkCornerAnnotation() self.__TextProperty = vtk.vtkTextProperty() self.__LookupTable = vtk.vtkLookupTable() self.__ScalarBarActor = vtk.vtkScalarBarActor() self.__Prop3DCollection = vtk.vtkProp3DCollection() self.__DataSetCollection = vtk.vtkDataSetCollection() self.__OrientationTransform = vtk.vtkMatrixToLinearTransform() self.__OrientationMatrix.Identity() self.__CornerAnnotation.SetNonlinearFontScaleFactor(0.30) self.__CornerAnnotation.SetText(0, "Jolly - (c) summit 2009 ref vtkINRIA3D") self.__CornerAnnotation.SetMaximumFontSize(46) self.__ScalarBarActor.SetLabelTextProperty(self.__TextProperty) self.__ScalarBarActor.GetLabelTextProperty().BoldOff() self.__ScalarBarActor.GetLabelTextProperty().ItalicOff() self.__ScalarBarActor.SetNumberOfLabels(3) self.__ScalarBarActor.SetWidth(0.1) self.__ScalarBarActor.SetHeight(0.5) self.__ScalarBarActor.SetPosition(0.9, 0.3) self.__LookupTable.SetTableRange(0, 1) self.__LookupTable.SetSaturationRange(0, 0) self.__LookupTable.SetHueRange(0, 0) self.__LookupTable.SetValueRange(0, 1) self.__LookupTable.Build() self.__ShowAnnotations = True self.__ShowScalarBar = True self.__OrientationTransform.SetInput(self.__OrientationMatrix) self.__WindowLevel = self.GetWindowLevel() self.__WindowLevel.SetLookupTable( self.__LookupTable ) self.__ScalarBarActor.SetLookupTable(self.__LookupTable) self.__Renderer = self.GetRenderer() self.__Renderer.AddViewProp(self.__CornerAnnotation) self.__Renderer.AddViewProp(self.__ScalarBarActor) self.__ImageActor = self.GetImageActor() self.__RenderWindow = self.GetRenderWindow () self.__InteractorStyle = self.GetInteractorStyle() self.__Interactor = None self.__CornerAnnotation.SetWindowLevel(self.__WindowLevel) self.__CornerAnnotation.SetImageActor(self.__ImageActor) self.__CornerAnnotation.ShowSliceAndImageOn() # Sometime we would want to set the default window/level value instead # of the ImageData's ScalarRange self.__RefWindow = None self.__RefLevel = None
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) # Create cell data cellData = vtk.vtkFloatArray() for i in range(resolution * resolution): cellData.InsertNextValue(i+1) # Create a lookup table to map cell data to colors lut = vtk.vtkLookupTable() tableSize = max(resolution*resolution+1, 10) lut.SetNumberOfTableValues(tableSize) lut.Build() # Fill in a few known colors, the rest will be generated if needed lut.SetTableValue(0 , 0 , 0 , 0, 1)# Black lut.SetTableValue(1, 0.8900, 0.8100, 0.3400, 1)# Banana lut.SetTableValue(2, 1.0000, 0.3882, 0.2784, 1)# Tomato lut.SetTableValue(3, 0.9608, 0.8706, 0.7020, 1)# Wheat lut.SetTableValue(4, 0.9020, 0.9020, 0.9804, 1)# Lavender lut.SetTableValue(5, 1.0000, 0.4900, 0.2500, 1)# Flesh lut.SetTableValue(6, 0.5300, 0.1500, 0.3400, 1)# Raspberry lut.SetTableValue(7, 0.9804, 0.5020, 0.4471, 1)# Salmon lut.SetTableValue(8, 0.7400, 0.9900, 0.7900, 1)# Mint lut.SetTableValue(9, 0.2000, 0.6300, 0.7900, 1)# Peacock aPlane.Update() #Force an update so we can set cell data aPlane.GetOutput().GetCellData().SetScalars(cellData) # Create a mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(aPlane.GetOutputPort()) mapper.SetScalarRange(0, tableSize - 1) mapper.SetLookupTable(lut) # Create an actor actor = vtk.vtkActor() actor.SetMapper(mapper) self.ren.AddActor(actor) self.ren.ResetCamera() self._initialized = False
def init_lut (self): "Set up the default LookupTable. Defaults to a blue to red table." debug ("In LutHandler::init_lut ()") self.lut = vtk.vtkLookupTable () self.lut.SetHueRange (0.667, 0.0) self.lut.SetNumberOfTableValues (self.n_color_var.get ()) self.lut.SetRampToSQRT() self.lut.Build ()
def SetCliplingLookuptable(self, tipo): if tipo == 'Green': lut = vtk.vtkLookupTable() lut.SetHueRange(0.0, 0.66667) lut.SetAlphaRange(0.0,0.8) self.PickPlaneZ.SetLookupTable(lut) self.PickPlaneY.SetLookupTable(lut) self.PickPlaneX.SetLookupTable(lut)
def autumn(self, m=256): lut = vtk.vtkLookupTable() lut.SetNumberOfColors(m) lut.SetHueRange(0.0, 0.15) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) lut.Build() return lut
Stream0.SetTerminalSpeed(1e-12) #del mbds aa = vtk.vtkAssignAttribute() aa.SetInputConnection(Stream0.GetOutputPort()) aa.Assign("Normals", "NORMALS", "POINT_DATA") Ribbon0 = vtk.vtkRibbonFilter() Ribbon0.SetInputConnection(aa.GetOutputPort()) Ribbon0.SetWidth(0.1) Ribbon0.SetAngle(0) Ribbon0.SetDefaultNormal(0, 0, 1) Ribbon0.SetVaryWidth(0) LookupTable1 = vtk.vtkLookupTable() LookupTable1.SetNumberOfTableValues(256) LookupTable1.SetHueRange(0, 0.66667) LookupTable1.SetSaturationRange(1, 1) LookupTable1.SetValueRange(1, 1) LookupTable1.SetTableRange(0.197813, 0.710419) LookupTable1.SetVectorComponent(0) LookupTable1.Build() Mapper10 = vtk.vtkPolyDataMapper() Mapper10.SetInputConnection(Ribbon0.GetOutputPort()) Mapper10.SetImmediateModeRendering(1) Mapper10.UseLookupTableScalarRangeOn() Mapper10.SetScalarVisibility(1) Mapper10.SetScalarModeToUsePointFieldData() Mapper10.SelectColorArray("Density")
def _plotInternal(self): tmpLevels = [] tmpColors = [] indices = self._gm.fillareaindices if indices is None: indices = [1,] while len(indices) < len(self._contourColors): indices.append(indices[-1]) if len(self._contourLevels) > len(self._contourColors): raise RuntimeError( "You asked for %i levels but provided only %i colors\n" "Graphic Method: %s of type %s\nLevels: %s" % (len(self._contourLevels), len(self._contourColors), self._gm.name, self._gm.g_name), repr(self._contourLevels)) elif len(self._contourLevels) < len(self._contourColors) - 1: warnings.warn( "You asked for %i lgridevels but provided %i colors, extra " "ones will be ignored\nGraphic Method: %s of type %s" % (len(self._contourLevels), len(self._contourColors), self._gm.name, self._gm.g_name)) for i, l in enumerate(self._contourLevels): if i == 0: C = [self._contourColors[i],] if numpy.allclose(self._contourLevels[0][0], -1.e20): ## ok it's an extension arrow L = [self._scalarRange[0] - 1., self._contourLevels[0][1]] else: L = list(self._contourLevels[i]) I = [indices[i],] else: if l[0] == L[-1] and I[-1] == indices[i]: # Ok same type lets keep going if numpy.allclose(l[1], 1.e20): L.append(self._scalarRange[1] + 1.) else: L.append(l[1]) C.append(self._contourColors[i]) else: # ok we need new contouring tmpLevels.append(L) tmpColors.append(C) C = [self._contourColors[i],] L = self._contourLevels[i] I = [indices[i],] tmpLevels.append(L) tmpColors.append(C) mappers = [] luts = [] cots = [] geos = [] for i,l in enumerate(tmpLevels): # Ok here we are trying to group together levels can be, a join will # happen if: next set of levels contnues where one left off AND # pattern is identical wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1) # TODO this should really just be a single polydata that is # colored by scalars: for j,color in enumerate(tmpColors[i]): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() th = vtk.vtkThreshold() th.ThresholdBetween(l[j], l[j+1]) th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(th.GetOutputPort()) geos.append(geoFilter2) mapper.SetInputConnection(geoFilter2.GetOutputPort()) lut.SetNumberOfTableValues(1) r, g, b = self._colorMap.index[color] lut.SetTableValue(0, r/100., g/100., b/100.) mapper.SetLookupTable(lut) mapper.SetScalarRange(l[j], l[j+1]) luts.append([lut, [l[j], l[j+1], True]]) ## Store the mapper only if it's worth it? ## Need to do it with the whole slab min/max for animation ## purposes if not (l[j+1] < wholeDataMin or l[j] > wholeDataMax): mappers.append(mapper) self._resultDict["vtk_backend_luts"]=luts if len(cots) > 0: self._resultDict["vtk_backend_contours"] = cots if len(geos) > 0: self._resultDict["vtk_backend_geofilters"] = geos numLevels = len(self._contourLevels) if mappers == []: # ok didn't need to have special banded contours mapper = vtk.vtkPolyDataMapper() mappers = [mapper,] ## Colortable bit # make sure length match while len(self._contourColors) < numLevels: self._contourColors.append(self._contourColors[-1]) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(numLevels) for i in range(numLevels): r, g, b = self._colorMap.index[self._contourColors[i]] lut.SetTableValue(i, r / 100., g / 100., b / 100.) mapper.SetLookupTable(lut) if numpy.allclose(self._contourLevels[0], -1.e20): lmn = mn - 1. else: lmn = self._contourLevels[0] if numpy.allclose(self._contourLevels[-1], 1.e20): lmx = mx + 1. else: lmx = self._contourLevels[-1] mapper.SetScalarRange(lmn, lmx) self._resultDict["vtk_backend_luts"] = [[lut, [lmn, lmx, True]],] if self._maskedDataMapper is not None: # Note that this is different for meshfill -- others prepend. mappers.append(self._maskedDataMapper) # This is also different for meshfill, others use # vcs.utils.getworldcoordinates x1, x2, y1, y2 = vcs2vtk.getRange(self._gm, self._vtkDataSetBounds[0], self._vtkDataSetBounds[1], self._vtkDataSetBounds[2], self._vtkDataSetBounds[3]) # Add a second mapper for wireframe meshfill: if self._gm.mesh: lineMappers = [] wireLUT = vtk.vtkLookupTable() wireLUT.SetNumberOfTableValues(1) wireLUT.SetTableValue(0, 0, 0, 0) for polyMapper in mappers: lineMapper = vtk.vtkPolyDataMapper() lineMapper.SetInputConnection(polyMapper.GetInputConnection(0, 0)) lineMapper._useWireFrame = True # Setup depth resolution so lines stay above points: polyMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(0, 1) polyMapper.SetResolveCoincidentTopologyToPolygonOffset() lineMapper.SetResolveCoincidentTopologyPolygonOffsetParameters(1, 1) lineMapper.SetResolveCoincidentTopologyToPolygonOffset() lineMapper.SetLookupTable(wireLUT) lineMappers.append(lineMapper) mappers.extend(lineMappers) # And now we need actors to actually render this thing actors = [] for mapper in mappers: act = vtk.vtkActor() act.SetMapper(mapper) if hasattr(mapper, "_useWireFrame"): prop = act.GetProperty() prop.SetRepresentationToWireframe() if self._vtkGeoTransform is None: # If using geofilter on wireframed does not get wrppaed not sure # why so sticking to many mappers act = vcs2vtk.doWrap(act, [x1,x2,y1,y2], self._dataWrapModulo) # TODO See comment in boxfill. if mapper is self._maskedDataMapper: actors.append([act, self._maskedDataMapper, [x1,x2,y1,y2]]) else: actors.append([act, [x1,x2,y1,y2]]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) ren = self._context.fitToViewport( act, [self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2], wc=[x1, x2, y1, y2], geo=self._vtkGeoTransform, priority=self._template.data.priority) self._resultDict["vtk_backend_actors"] = actors self._template.plot(self._context.canvas, self._data1, self._gm, bg=self._context.bg, X=numpy.arange(self._vtkDataSetBounds[0], self._vtkDataSetBounds[1] * 1.1, (self._vtkDataSetBounds[1] - self._vtkDataSetBounds[0]) / 10.), Y=numpy.arange(self._vtkDataSetBounds[2], self._vtkDataSetBounds[3] * 1.1, (self._vtkDataSetBounds[3] - self._vtkDataSetBounds[2]) / 10.)) legend = getattr(self._gm, "legend", None) if self._gm.ext_1: if isinstance(self._contourLevels[0], list): if numpy.less(abs(self._contourLevels[0][0]), 1.e20): ## Ok we need to add the ext levels self._contourLevels.insert(0, [-1.e20, levs[0][0]]) else: if numpy.less(abs(self._contourLevels[0]), 1.e20): ## need to add an ext self._contourLevels.insert(0, -1.e20) if self._gm.ext_2: if isinstance(self._contourLevels[-1],list): if numpy.less(abs(self._contourLevels[-1][1]), 1.e20): ## need ext self._contourLevels.append([self._contourLevels[-1][1], 1.e20]) else: if numpy.less(abs(self._contourLevels[-1]), 1.e20): ## need exts self._contourLevels.append(1.e20) self._resultDict.update( self._context.renderColorBar(self._template, self._contourLevels, self._contourColors, legend, self._colorMap)) if self._context.canvas._continents is None: self._useContinents = False if self._useContinents: projection = vcs.elements["projection"][self._gm.projection] self._context.plotContinents(x1, x2, y1, y2, projection, self._dataWrapModulo, self._template)
def prepareDelaunayData3d(dimension, agg_globalnodeidx, global_nodecoords, aggpolygons, aggid, aggid2nodes, aggid2procs): local_nodeidx2global_nodeidx = {} no_of_aggnodes = len(agg_globalnodeidx) no_aggs = len(aggid2nodes) Points = vtk.vtkPoints() Vertices = vtk.vtkCellArray() for i in range(0,len(agg_globalnodeidx)): id = -1 local_nodeidx2global_nodeidx[i] = agg_globalnodeidx[i] nodecoords = global_nodecoords[int(agg_globalnodeidx[i])] id = Points.InsertNextPoint(nodecoords[0]+ 0.0001 * random.random(),nodecoords[1]+ 0.0001 * random.random(),nodecoords[2]+ 0.0001 * random.random()) Vertices.InsertNextCell(1) Vertices.InsertCellPoint(id) polydata2 = vtk.vtkPolyData() polydata2.SetPoints(Points) polydata2.Modified() polydata2.Update() delaunay = vtk.vtkDelaunay3D() delaunay.SetInput(polydata2) delaunay.Update() # create surfaceFilter surfaceFilter = vtk.vtkDataSetSurfaceFilter() surfaceFilter.SetInputConnection(delaunay.GetOutputPort()) surfaceFilter.Update() pt_polydata = surfaceFilter.GetOutput() lookupTable = vtk.vtkLookupTable() lookupTable.SetNumberOfTableValues(no_aggs) lookupTable.Build() Ids = vtk.vtkUnsignedIntArray() Ids.SetNumberOfComponents(1) Ids.SetName("Ids") for i in range(0,Points.GetNumberOfPoints()): Ids.InsertNextTuple1(int(aggid)) Ids.SetLookupTable(lookupTable) Procs = vtk.vtkUnsignedCharArray() Procs.SetNumberOfComponents(1) Procs.SetName("proc") for i in range(0,Points.GetNumberOfPoints()): Procs.InsertNextTuple1(aggid2procs[aggid]) polydata3 = vtk.vtkPolyData() polydata3 = surfaceFilter.GetOutput() polydata3.GetPointData().SetScalars(Ids) polydata3.GetPointData().AddArray(Procs) polydata4 = vtk.vtkPolyData() polydata4.SetPoints(Points) polydata4.SetVerts(Vertices) polydata4.GetPointData().SetScalars(Ids) polydata4.GetPointData().AddArray(Procs) #datamapper = vtk.vtkDataSetMapper() #datamapper.SetInputConnection(delaunay.GetOutputPort()) #datamapper.SetInput(polydata3) #actor = vtk.vtkActor() #actor.SetMapper(datamapper) #renderer = vtk.vtkRenderer() #renderWindow = vtk.vtkRenderWindow() #renderWindow.AddRenderer(renderer) #renderWindowInteractor = vtk.vtkRenderWindowInteractor() #renderWindowInteractor.SetRenderWindow(renderWindow) #renderer.AddActor(actor) #renderWindow.Render() #renderWindowInteractor.Start() #print polydata.GetVertices() aggpolygons.AddInput(polydata3) aggpolygons.AddInput(polydata4)
b = float(j) / N v = 0.5 + 0.5 * cos(13 * a) * cos(8 * b + 3 * a * a) v = v**2 method(i, j, 0, 0, v) geometry_filter = vtk.vtkImageDataGeometryFilter() geometry_filter.SetInput(image_data) warp = vtk.vtkWarpScalar() warp.SetInput(geometry_filter.GetOutput()) warp.SetScaleFactor(8.1) normal_filter = vtk.vtkPolyDataNormals() normal_filter.SetInput(warp.GetOutput()) data_mapper = vtk.vtkDataSetMapper() data_mapper.SetInput(normal_filter.GetOutput()) data_actor = vtk.vtkActor() data_actor.SetMapper(data_mapper) renderer.AddActor(data_actor) table = vtk.vtkLookupTable() data_mapper.SetLookupTable(table) # the actual gradient editor code. def on_color_table_changed(): render_window.Render() # Gradient editor only works with tvtk objects, so convert the lut # to a tvtk version. tvtk_table = tvtk.to_tvtk(table) editor = GradientEditor(root, tvtk_table, on_color_table_changed) root.mainloop()
def testPlatonicSolids(self): # Create five instances of vtkPlatonicSolidSource # corresponding to each of the five Platonic solids. # tet = vtk.vtkPlatonicSolidSource() tet.SetSolidTypeToTetrahedron() tetMapper = vtk.vtkPolyDataMapper() tetMapper.SetInputConnection(tet.GetOutputPort()) tetActor = vtk.vtkActor() tetActor.SetMapper(tetMapper) cube = vtk.vtkPlatonicSolidSource() cube.SetSolidTypeToCube() cubeMapper = vtk.vtkPolyDataMapper() cubeMapper.SetInputConnection(cube.GetOutputPort()) cubeActor = vtk.vtkActor() cubeActor.SetMapper(cubeMapper) cubeActor.AddPosition(2.0, 0, 0) oct = vtk.vtkPlatonicSolidSource() oct.SetSolidTypeToOctahedron() octMapper = vtk.vtkPolyDataMapper() octMapper.SetInputConnection(oct.GetOutputPort()) octActor = vtk.vtkActor() octActor.SetMapper(octMapper) octActor.AddPosition(4.0, 0, 0) icosa = vtk.vtkPlatonicSolidSource() icosa.SetSolidTypeToIcosahedron() icosaMapper = vtk.vtkPolyDataMapper() icosaMapper.SetInputConnection(icosa.GetOutputPort()) icosaActor = vtk.vtkActor() icosaActor.SetMapper(icosaMapper) icosaActor.AddPosition(6.0, 0, 0) dode = vtk.vtkPlatonicSolidSource() dode.SetSolidTypeToDodecahedron() dodeMapper = vtk.vtkPolyDataMapper() dodeMapper.SetInputConnection(dode.GetOutputPort()) dodeActor = vtk.vtkActor() dodeActor.SetMapper(dodeMapper) dodeActor.AddPosition(8.0, 0, 0) # Create rendering stuff # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) # Add the actors to the renderer, set the background and size # ren.AddActor(tetActor) ren.AddActor(cubeActor) ren.AddActor(octActor) ren.AddActor(icosaActor) ren.AddActor(dodeActor) colors = self.Colors() # Create a lookup table with colors for each face # math = vtk.vtkMath() lut = vtk.vtkLookupTable() lut.SetNumberOfColors(20) lut.Build() lut.SetTableValue(0, colors.GetRGBAColor("red")) lut.SetTableValue(1, colors.GetRGBAColor("lime")) lut.SetTableValue(2, colors.GetRGBAColor("yellow")) lut.SetTableValue(3, colors.GetRGBAColor("blue")) lut.SetTableValue(4, colors.GetRGBAColor("magenta")) lut.SetTableValue(5, colors.GetRGBAColor("cyan")) lut.SetTableValue(6, colors.GetRGBAColor("spring_green")) lut.SetTableValue(7, colors.GetRGBAColor("lavender")) lut.SetTableValue(8, colors.GetRGBAColor("mint_cream")) lut.SetTableValue(9, colors.GetRGBAColor("violet")) lut.SetTableValue(10, colors.GetRGBAColor("ivory_black")) lut.SetTableValue(11, colors.GetRGBAColor("coral")) lut.SetTableValue(12, colors.GetRGBAColor("pink")) lut.SetTableValue(13, colors.GetRGBAColor("salmon")) lut.SetTableValue(14, colors.GetRGBAColor("sepia")) lut.SetTableValue(15, colors.GetRGBAColor("carrot")) lut.SetTableValue(16, colors.GetRGBAColor("gold")) lut.SetTableValue(17, colors.GetRGBAColor("forest_green")) lut.SetTableValue(18, colors.GetRGBAColor("turquoise")) lut.SetTableValue(19, colors.GetRGBAColor("plum")) lut.SetTableRange(0, 19) tetMapper.SetLookupTable(lut) tetMapper.SetScalarRange(0, 19) cubeMapper.SetLookupTable(lut) cubeMapper.SetScalarRange(0, 19) octMapper.SetLookupTable(lut) octMapper.SetScalarRange(0, 19) icosaMapper.SetLookupTable(lut) icosaMapper.SetScalarRange(0, 19) dodeMapper.SetLookupTable(lut) dodeMapper.SetScalarRange(0, 19) cam = ren.GetActiveCamera() cam.SetPosition(3.89696, 7.20771, 1.44123) cam.SetFocalPoint(3.96132, 0, 0) cam.SetViewUp(-0.0079335, 0.196002, -0.980571) cam.SetClippingRange(5.42814, 9.78848) ren.SetBackground(colors.GetRGBColor("black")) renWin.SetSize(400, 150) # render and interact with data iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) renWin.Render() img_file = "TestPlatonicSolids.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def _plotInternal(self): prepedContours = self._prepContours() tmpLevels = prepedContours["tmpLevels"] tmpIndices = prepedContours["tmpIndices"] tmpColors = prepedContours["tmpColors"] tmpOpacities = prepedContours["tmpOpacities"] style = self._gm.fillareastyle fareapixelspacing, fareapixelscale = self._patternSpacingAndScale() mappers = [] luts = [] geos = [] wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1) plotting_dataset_bounds = self.getPlottingBounds() x1, x2, y1, y2 = plotting_dataset_bounds _colorMap = self.getColorMap() for i, l in enumerate(tmpLevels): # Ok here we are trying to group together levels can be, a join # will happen if: next set of levels contnues where one left off # AND pattern is identical # TODO this should really just be a single polydata that is # colored by scalars: for j, color in enumerate(tmpColors[i]): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() th = vtk.vtkThreshold() th.ThresholdBetween(l[j], l[j + 1]) th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(th.GetOutputPort()) # Make the polydata output available here for patterning later geoFilter2.Update() geos.append(geoFilter2) mapper.SetInputConnection(geoFilter2.GetOutputPort()) lut.SetNumberOfTableValues(1) r, g, b, a = self.getColorIndexOrRGBA(_colorMap, color) if style == 'solid': tmpOpacity = tmpOpacities[j] if tmpOpacity is None: tmpOpacity = a / 100. else: tmpOpacity = tmpOpacities[j] / 100. lut.SetTableValue(0, r / 100., g / 100., b / 100., tmpOpacity) else: lut.SetTableValue(0, 1., 1., 1., 0.) mapper.SetLookupTable(lut) mapper.SetScalarRange(l[j], l[j + 1]) luts.append([lut, [l[j], l[j + 1], True]]) # Store the mapper only if it's worth it? # Need to do it with the whole slab min/max for animation # purposes if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax): mappers.append(mapper) self._resultDict["vtk_backend_luts"] = luts if len(geos) > 0: self._resultDict["vtk_backend_geofilters"] = geos """ numLevels = len(self._contourLevels) if mappers == []: # ok didn't need to have special banded contours mapper = vtk.vtkPolyDataMapper() mappers = [mapper] # Colortable bit # make sure length match while len(self._contourColors) < numLevels: self._contourColors.append(self._contourColors[-1]) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(numLevels) for i in range(numLevels): r, g, b, a = self._colorMap.index[self._contourColors[i]] lut.SetTableValue(i, r / 100., g / 100., b / 100., a / 100.) mapper.SetLookupTable(lut) if numpy.allclose(self._contourLevels[0], -1.e20): lmn = self._min - 1. else: lmn = self._contourLevels[0] if numpy.allclose(self._contourLevels[-1], 1.e20): lmx = self._max + 1. else: lmx = self._contourLevels[-1] mapper.SetScalarRange(lmn, lmx) self._resultDict["vtk_backend_luts"] = [[lut, [lmn, lmx, True]]] """ if self._maskedDataMapper is not None: # Note that this is different for meshfill -- others prepend. mappers.append(self._maskedDataMapper) # Add a second mapper for wireframe meshfill: if self._gm.mesh: lineMappers = [] wireLUT = vtk.vtkLookupTable() wireLUT.SetNumberOfTableValues(1) wireLUT.SetTableValue(0, 0, 0, 0) for polyMapper in mappers: lineMapper = vtk.vtkPolyDataMapper() lineMapper.SetInputConnection( polyMapper.GetInputConnection(0, 0)) lineMapper._useWireFrame = True # 'noqa' comments disable pep8 checking for these lines. There # is not a readable way to shorten them due to the unwieldly # method name. # # Setup depth resolution so lines stay above points: polyMapper.SetResolveCoincidentTopologyPolygonOffsetParameters( 0, 1) # noqa polyMapper.SetResolveCoincidentTopologyToPolygonOffset() lineMapper.SetResolveCoincidentTopologyPolygonOffsetParameters( 1, 1) # noqa lineMapper.SetResolveCoincidentTopologyToPolygonOffset() lineMapper.SetLookupTable(wireLUT) lineMappers.append(lineMapper) mappers.extend(lineMappers) # And now we need actors to actually render this thing actors = [] vp = self._resultDict.get('ratio_autot_viewport', [ self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2 ]) dataset_renderer = None xScale, yScale = (1, 1) cti = 0 ctj = 0 for mapper in mappers: act = vtk.vtkActor() act.SetMapper(mapper) wireframe = False if hasattr(mapper, "_useWireFrame"): prop = act.GetProperty() prop.SetRepresentationToWireframe() wireframe = True # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) dataset_renderer, xScale, yScale = self._context().fitToViewport( act, vp, wc=plotting_dataset_bounds, geoBounds=self._vtkDataSetBoundsNoMask, geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=(dataset_renderer is None), add_actor=(wireframe or (style == "solid"))) # TODO See comment in boxfill. if mapper is self._maskedDataMapper: actors.append( [act, self._maskedDataMapper, plotting_dataset_bounds]) else: actors.append([act, plotting_dataset_bounds]) if not wireframe: # Since pattern creation requires a single color, assuming the # first if ctj >= len(tmpColors[cti]): ctj = 0 cti += 1 c = self.getColorIndexOrRGBA(_colorMap, tmpColors[cti][ctj]) # Get the transformed contour data transform = act.GetUserTransform() transformFilter = vtk.vtkTransformFilter() transformFilter.SetInputData(mapper.GetInput()) transformFilter.SetTransform(transform) transformFilter.Update() patact = fillareautils.make_patterned_polydata( transformFilter.GetOutput(), fillareastyle=style, fillareaindex=tmpIndices[cti], fillareacolors=c, fillareaopacity=tmpOpacities[cti], fillareapixelspacing=fareapixelspacing, fillareapixelscale=fareapixelscale, size=self._context().renWin.GetSize(), renderer=dataset_renderer) ctj += 1 if patact is not None: actors.append([patact, plotting_dataset_bounds]) dataset_renderer.AddActor(patact) t = self._originalData1.getTime() if self._originalData1.ndim > 2: z = self._originalData1.getAxis(-3) else: z = None self._resultDict["vtk_backend_actors"] = actors kwargs = { "vtk_backend_grid": self._vtkDataSet, "dataset_bounds": self._vtkDataSetBounds, "plotting_dataset_bounds": plotting_dataset_bounds, "vtk_dataset_bounds_no_mask": self._vtkDataSetBoundsNoMask, "vtk_backend_geo": self._vtkGeoTransform } if ("ratio_autot_viewport" in self._resultDict): kwargs["ratio_autot_viewport"] = vp self._resultDict.update(self._context().renderTemplate( self._template, self._data1, self._gm, t, z, X=numpy.arange(min(x1, x2), max(x1, x2) * 1.1, abs(x2 - x1) / 10.), Y=numpy.arange(min(y1, y2), max(y1, y2) * 1.1, abs(y2 - y1) / 10.), **kwargs)) legend = getattr(self._gm, "legend", None) if self._gm.ext_1: if isinstance(self._contourLevels[0], list): if numpy.less(abs(self._contourLevels[0][0]), 1.e20): # Ok we need to add the ext levels self._contourLevels.insert( 0, [-1.e20, self._contourLevels[0][0]]) else: if numpy.less(abs(self._contourLevels[0]), 1.e20): # need to add an ext self._contourLevels.insert(0, -1.e20) if self._gm.ext_2: if isinstance(self._contourLevels[-1], list): if numpy.less(abs(self._contourLevels[-1][1]), 1.e20): # need ext self._contourLevels.append( [self._contourLevels[-1][1], 1.e20]) else: if numpy.less(abs(self._contourLevels[-1]), 1.e20): # need exts self._contourLevels.append(1.e20) patternArgs = {} patternArgs['style'] = self._gm.fillareastyle patternArgs['index'] = self._gm.fillareaindices if patternArgs['index'] is None: patternArgs['index'] = [ 1, ] # Compensate for the different viewport size of the colorbar patternArgs['opacity'] = self._gm.fillareaopacity patternArgs['pixelspacing'] = [ int(fareapixelspacing[0] / (vp[1] - vp[0])), int(fareapixelspacing[1] / (vp[3] - vp[2])) ] patternArgs['pixelscale'] = fareapixelscale / (vp[1] - vp[0]) self._resultDict.update(self._context().renderColorBar( self._template, self._contourLevels, self._contourColors, legend, self.getColorMap(), **patternArgs)) if self._context().canvas._continents is None: self._useContinents = False if self._useContinents: projection = vcs.elements["projection"][self._gm.projection] continents_renderer, xScale, yScale = self._context( ).plotContinents(plotting_dataset_bounds, projection, self._dataWrapModulo, vp, self._template.data.priority, **kwargs)
def main(): # setup the dataset filepath all_filename = ['pv_insitu_300x300x300_29072.vti','pv_insitu_300x300x300_29263.vti', 'pv_insitu_300x300x300_29449.vti','pv_insitu_300x300x300_29638.vti', 'pv_insitu_300x300x300_29827.vti','pv_insitu_300x300x300_30015.vti', 'pv_insitu_300x300x300_30205.vti','pv_insitu_300x300x300_30395.vti', 'pv_insitu_300x300x300_30587.vti','pv_insitu_300x300x300_30778.vti', 'pv_insitu_300x300x300_30966.vti'] # iso_value_1 = average mean + 3*std # ios_value_2 = average median + 3*std # we calculate it in other file "finalproject_T2" iso_value_1 = 0.3544; iso_value_2 = 0.3246; #for i in range(0, 2): for i in range(0, len(all_filename)): filename = "yC31/"+all_filename[i]; print(filename); #filename = "yC31/pv_insitu_300x300x300_29072.vti" # the name of data array which is used in this example daryName = "tev"; #'v03' 'prs' 'tev' # for accessomg build-in color access colors = vtk.vtkNamedColors(); # Create the renderer, the render window, and the interactor. # The renderer draws into the render window. # The interactor enables mouse and keyboard-based interaction # with the data within the render windows. aRenderer = vtk.vtkRenderer(); renWin = vtk.vtkRenderWindow(); renWin.AddRenderer(aRenderer); iren = vtk.vtkRenderWindowInteractor(); iren.SetRenderWindow(renWin); # Set a background color for the renderer # and set the size of the render window. aRenderer.SetBackground(colors.GetColor3d("Silver")); renWin.SetSize(600, 600); # data reader reader = vtk.vtkXMLImageDataReader(); reader.SetFileName(filename); reader.Update(); # specify the data array in the file to process reader.GetOutput().GetPointData().SetActiveAttribute(daryName, 0); # convert the data array to numpy array and get the min and maximum value dary = VN.vtk_to_numpy(reader.GetOutput().GetPointData().GetScalars(daryName)); dary = dary[dary!= 0] dMax = np.amax(dary); dMin = np.amin(dary); dRange = dMax - dMin; dMean = np.mean(dary); dMedian = np.median(dary); dstd = np.std(dary); print("Data array max: ", dMax); print("Data array min: ", dMin); print("Data array range: ", dRange); print("Data array mean: ", dMean); print("Data array median: ", dMedian); print("Data array std: ", dstd); ############ setup color map ######### # Now create a loopup table that consists of the full hue circle # (from HSV). hueLut = vtk.vtkLookupTable(); hueLut.SetTableRange(dMin, dMax); hueLut.Build(); # An outline provides context around the data. outlineData = vtk.vtkOutlineFilter(); outlineData.SetInputConnection(reader.GetOutputPort()); outlineData.Update() mapOutline = vtk.vtkPolyDataMapper(); mapOutline.SetInputConnection(outlineData.GetOutputPort()); outline = vtk.vtkActor(); outline.SetMapper(mapOutline); outline.GetProperty().SetColor(colors.GetColor3d("Black")); #################### create isosurface tev = mean + 3*std ###################################### # isosurface iso = vtk.vtkContourFilter(); iso.SetInputConnection(reader.GetOutputPort()); iso.Update(); #iso.SetValue(0, iso_value_1); iso.SetValue(0, iso_value_2); normals = vtk.vtkPolyDataNormals(); normals.SetInputConnection(iso.GetOutputPort()); normals.SetFeatureAngle(45); isoMapper = vtk.vtkPolyDataMapper(); isoMapper.SetInputConnection(normals.GetOutputPort()); isoMapper.ScalarVisibilityOff(); isoActor = vtk.vtkActor(); isoActor.SetMapper(isoMapper); isoActor.GetProperty().SetColor(colors.GetColor3d("bisque")); isoActor.GetProperty().SetOpacity(0.3); ################################################################################################# aCamera = vtk.vtkCamera(); aCamera.SetViewUp(0, 0, 1); aCamera.SetPosition(1, 1, 2); aCamera.SetFocalPoint(0, 0, 0); aCamera.ComputeViewPlaneNormal(); aCamera.Azimuth(45.0); aCamera.Elevation(45.0); ######################## create a text ##################### # create a text actor txt = vtk.vtkTextActor() txt_str = "isosurface value (median+3*std)(bisque) = "+ str(iso_value_2)[:5] #txt_str = "isosurface value (mean+3*std)(bisque) = "+ str(iso_value_1)[:5] txt.SetInput(txt_str) txtprop=txt.GetTextProperty() txtprop.SetFontFamilyToArial() txtprop.SetFontSize(24) txtprop.SetColor(colors.GetColor3d("bisque")) txt.SetDisplayPosition(50,550) ########################################################## txt3 = vtk.vtkTextActor() txt_str3 = "timestep = "+filename[27:32] txt3.SetInput(txt_str3) txtprop3=txt3.GetTextProperty() txtprop3.SetFontFamilyToArial() txtprop3.SetFontSize(24) txtprop3.SetColor(0,0,0) txt3.SetDisplayPosition(50,500) # Actors are added to the renderer. aRenderer.AddActor(outline); aRenderer.AddActor(isoActor); aRenderer.AddActor(txt); aRenderer.AddActor(txt3); # An initial camera view is created. The Dolly() method moves # the camera towards the FocalPoint, thereby enlarging the image. aRenderer.SetActiveCamera(aCamera); # Calling Render() directly on a vtkRenderer is strictly forbidden. # Only calling Render() on the vtkRenderWindow is a valid call. renWin.Render(); aRenderer.ResetCamera(); aCamera.Dolly(-2.0); #################################################################### # screenshot code: w2if = vtk.vtkWindowToImageFilter() w2if.SetInput(renWin) w2if.Update() writer = vtk.vtkPNGWriter() saveName = "plots/ios/tev/median/"+daryName+"_t_"+filename[27:32]+".png"; #saveName = "plots/ios/tev/mean/"+daryName+"_t_"+filename[27:32]+".png"; writer.SetFileName(saveName) writer.SetInputData(w2if.GetOutput()) writer.Write() ##################################################################### # Note that when camera movement occurs (as it does in the Dolly() method), # the clipping planes often need adjusting. # Clipping planes consist of two planes: # near and far along the view direction. # The near plane clips out objects in front of the plane; # the far plane clips out objects behind the plane. # This way only what is drawn between the planes is actually rendered. aRenderer.ResetCameraClippingRange(); # Interact with the data. renWin.Render();
def main(): colors = vtk.vtkNamedColors() # Create the RenderWindow, Renderer and interactive renderer. # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Generate the tensors. ptLoad = vtk.vtkPointLoad() ptLoad.SetLoadValue(100.0) ptLoad.SetSampleDimensions(6, 6, 6) ptLoad.ComputeEffectiveStressOn() ptLoad.SetModelBounds(-10, 10, -10, 10, -10, 10) # Extract a plane of data. plane = vtk.vtkImageDataGeometryFilter() plane.SetInputConnection(ptLoad.GetOutputPort()) plane.SetExtent(2, 2, 0, 99, 0, 99) # Generate the ellipsoids. sphere = vtk.vtkSphereSource() sphere.SetThetaResolution(8) sphere.SetPhiResolution(8) tensorEllipsoids = vtk.vtkTensorGlyph() tensorEllipsoids.SetInputConnection(ptLoad.GetOutputPort()) tensorEllipsoids.SetSourceConnection(sphere.GetOutputPort()) tensorEllipsoids.SetScaleFactor(10) tensorEllipsoids.ClampScalingOn() ellipNormals = vtk.vtkPolyDataNormals() ellipNormals.SetInputConnection(tensorEllipsoids.GetOutputPort()) # Map contour lut = vtk.vtkLookupTable() MakeLogLUT(lut) # lut.SetHueRange(.6667, 0.0) tensorEllipsoidsMapper = vtk.vtkPolyDataMapper() tensorEllipsoidsMapper.SetInputConnection(ellipNormals.GetOutputPort()) tensorEllipsoidsMapper.SetLookupTable(lut) plane.Update() # force update for scalar range tensorEllipsoidsMapper.SetScalarRange(plane.GetOutput().GetScalarRange()) tensorActor = vtk.vtkActor() tensorActor.SetMapper(tensorEllipsoidsMapper) # Create an outline around the data. # outline = vtk.vtkOutlineFilter() outline.SetInputConnection(ptLoad.GetOutputPort()) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outline.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) outlineActor.GetProperty().SetColor(colors.GetColor3d('Black')) # Create a cone whose apex indicates the application of load. # coneSrc = vtk.vtkConeSource() coneSrc.SetRadius(.5) coneSrc.SetHeight(2) coneMap = vtk.vtkPolyDataMapper() coneMap.SetInputConnection(coneSrc.GetOutputPort()) coneActor = vtk.vtkActor() coneActor.SetMapper(coneMap) coneActor.SetPosition(0, 0, 11) coneActor.RotateY(90) coneActor.GetProperty().SetColor(colors.GetColor3d('Red')) camera = vtk.vtkCamera() camera.SetFocalPoint(0.113766, -1.13665, -1.01919) camera.SetPosition(-29.4886, -63.1488, 26.5807) camera.SetViewAngle(24.4617) camera.SetViewUp(0.17138, 0.331163, 0.927879) camera.SetClippingRange(1, 100) ren.AddActor(tensorActor) ren.AddActor(outlineActor) ren.AddActor(coneActor) ren.SetBackground(colors.GetColor3d('WhiteSmoke')) ren.SetActiveCamera(camera) renWin.SetSize(512, 512) renWin.SetWindowName('TensorEllipsoids') iren.Initialize() renWin.Render() iren.Start()
def main(): colors = vtk.vtkNamedColors() # We are going to handle two different sources. # The first source is a superquadric source. torus = vtk.vtkSuperquadricSource() torus.SetCenter(0.0, 0.0, 0.0) torus.SetScale(1.0, 1.0, 1.0) torus.SetPhiResolution(64) torus.SetThetaResolution(64) torus.SetThetaRoundness(1) torus.SetThickness(0.5) torus.SetSize(0.5) torus.SetToroidal(1) # Rotate the torus towards the observer (around the x-axis) torusT = vtk.vtkTransform() torusT.RotateX(55) torusTF = vtk.vtkTransformFilter() torusTF.SetInputConnection(torus.GetOutputPort()) torusTF.SetTransform(torusT) # The quadric is made of strips, so pass it through a triangle filter as # the curvature filter only operates on polys tri = vtk.vtkTriangleFilter() tri.SetInputConnection(torusTF.GetOutputPort()) # The quadric has nasty discontinuities from the way the edges are generated # so let's pass it though a CleanPolyDataFilter and merge any points which # are coincident, or very close cleaner = vtk.vtkCleanPolyData() cleaner.SetInputConnection(tri.GetOutputPort()) cleaner.SetTolerance(0.005) # The next source will be a parametric function rh = vtk.vtkParametricRandomHills() rhFnSrc = vtk.vtkParametricFunctionSource() rhFnSrc.SetParametricFunction(rh) # Now we have the sources, lets put them into a list. sources = list() sources.append(cleaner) sources.append(cleaner) sources.append(rhFnSrc) sources.append(rhFnSrc) # Colour transfer function. ctf = vtk.vtkColorTransferFunction() ctf.SetColorSpaceToDiverging() p1 = [0.0] + list(colors.GetColor3d('MidnightBlue')) p2 = [1.0] + list(colors.GetColor3d('DarkOrange')) ctf.AddRGBPoint(*p1) ctf.AddRGBPoint(*p2) cc = list() for i in range(256): cc.append(ctf.GetColor(float(i) / 255.0)) # Lookup table. lut = list() for idx in range(len(sources)): lut.append(vtk.vtkLookupTable()) lut[idx].SetNumberOfColors(256) for i, item in enumerate(cc): lut[idx].SetTableValue(i, item[0], item[1], item[2], 1.0) if idx == 0: lut[idx].SetRange(-10, 10) if idx == 1: lut[idx].SetRange(0, 4) if idx == 2: lut[idx].SetRange(-1, 1) if idx == 3: lut[idx].SetRange(-1, 1) lut[idx].Build() curvatures = list() for idx in range(len(sources)): curvatures.append(vtk.vtkCurvatures()) if idx % 2 == 0: curvatures[idx].SetCurvatureTypeToGaussian() else: curvatures[idx].SetCurvatureTypeToMean() renderers = list() mappers = list() actors = list() textmappers = list() textactors = list() # Create a common text property. textProperty = vtk.vtkTextProperty() textProperty.SetFontSize(24) textProperty.SetJustificationToCentered() names = [ 'Torus - Gaussian Curvature', 'Torus - Mean Curvature', 'Random Hills - Gaussian Curvature', 'Random Hills - Mean Curvature' ] # Link the pipeline together. for idx, item in enumerate(sources): sources[idx].Update() curvatures[idx].SetInputConnection(sources[idx].GetOutputPort()) mappers.append(vtk.vtkPolyDataMapper()) mappers[idx].SetInputConnection(curvatures[idx].GetOutputPort()) mappers[idx].SetLookupTable(lut[idx]) mappers[idx].SetUseLookupTableScalarRange(1) actors.append(vtk.vtkActor()) actors[idx].SetMapper(mappers[idx]) textmappers.append(vtk.vtkTextMapper()) textmappers[idx].SetInput(names[idx]) textmappers[idx].SetTextProperty(textProperty) textactors.append(vtk.vtkActor2D()) textactors[idx].SetMapper(textmappers[idx]) textactors[idx].SetPosition(250, 16) renderers.append(vtk.vtkRenderer()) gridDimensions = 2 rendererSize = 512 for idx in range(len(sources)): if idx < gridDimensions * gridDimensions: renderers.append(vtk.vtkRenderer) # Create the RenderWindow # renderWindow = vtk.vtkRenderWindow() renderWindow.SetSize(rendererSize * gridDimensions, rendererSize * gridDimensions) renderWindow.SetWindowName('CurvaturesDemo') # Add and position the renders to the render window. viewport = list() for row in range(gridDimensions): for col in range(gridDimensions): idx = row * gridDimensions + col viewport[:] = [] viewport.append(float(col) / gridDimensions) viewport.append(float(gridDimensions - (row + 1)) / gridDimensions) viewport.append(float(col + 1) / gridDimensions) viewport.append(float(gridDimensions - row) / gridDimensions) if idx > (len(sources) - 1): continue renderers[idx].SetViewport(viewport) renderWindow.AddRenderer(renderers[idx]) renderers[idx].AddActor(actors[idx]) renderers[idx].AddActor(textactors[idx]) renderers[idx].SetBackground(colors.GetColor3d('CornflowerBlue')) interactor = vtk.vtkRenderWindowInteractor() interactor.SetRenderWindow(renderWindow) renderWindow.Render() interactor.Start()
def main(): # setup the dataset filepath #all_filename = np.genfromtxt('stats/yA31/filenames.csv', dtype=None) path = "D:/data/" files = os.listdir(path) time_index = [] for i in range(180, len(files)): if (i % 5 == 0): time_index.append(i) #print(files); daryName = "v02" #'v03' 'prs' 'tev' #for i in range(236, 237): #for i in range(0, 1): for i in range(0, len(time_index)): filename = path + files[time_index[i]] #filename = path+ files[i]; print(filename) # for accessomg build-in color access colors = vtk.vtkNamedColors() # Create the renderer, the render window, and the interactor. # The renderer draws into the render window. # The interactor enables mouse and keyboard-based interaction # with the data within the render windows. aRenderer = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(aRenderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Set a background color for the renderer # and set the size of the render window. aRenderer.SetBackground(colors.GetColor3d("Silver")) renWin.SetSize(600, 600) # data reader reader = vtk.vtkXMLImageDataReader() reader.SetFileName(filename) reader.Update() # specify the data array in the file to process reader.GetOutput().GetPointData().SetActiveAttribute(daryName, 0) # convert the data array to numpy array and get the min and maximum value dary = VN.vtk_to_numpy( reader.GetOutput().GetPointData().GetScalars(daryName)) dary = dary[dary != 0] dMax = np.amax(dary) #dary = dary[dary>dMax/2] dMin = np.amin(dary) dRange = dMax - dMin dMean = np.mean(dary) dMedian = np.median(dary) #dary = dary[dary>dMax/2] print("Data array max: ", dMax) print("Data array min: ", dMin) print("Data array range: ", dRange) print("Data array mean: ", dMean) print("Data array median: ", dMedian) ############ setup color map ######### hueLut = vtk.vtkLookupTable() # This creates a red ,white, blue lut. hueLut.SetHueRange(0.67, 0.0) hueLut.Build() # An outline provides context around the data. outlineData = vtk.vtkOutlineFilter() outlineData.SetInputConnection(reader.GetOutputPort()) outlineData.Update() mapOutline = vtk.vtkPolyDataMapper() mapOutline.SetInputConnection(outlineData.GetOutputPort()) outline = vtk.vtkActor() outline.SetMapper(mapOutline) outline.GetProperty().SetColor(colors.GetColor3d("Black")) ################## create volume rendering ################################ # Create transfer mapping scalar value to opacity opacityTransferFunction = vtk.vtkPiecewiseFunction() opacityTransferFunction.AddPoint(0.0, 0.0001) opacityTransferFunction.AddPoint(0.5, 0.0001) opacityTransferFunction.AddPoint(1.0, 0.005) # int AddRGBPoint (double x, double r, double g, double b) # int AddHSVPoint (double x, double h, double s, double v) # Create transfer mapping scalar value to color. colorTransferFunction = vtk.vtkColorTransferFunction() colorTransferFunction.AddRGBPoint(dMin, 0.0, 0.0, 1.0) colorTransferFunction.AddRGBPoint(0.5, 0.0, 1.0, 0.0) colorTransferFunction.AddRGBPoint(dMax, 1.0, 0.0, 0.0) # The property describes how the data will look. volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(colorTransferFunction) volumeProperty.SetScalarOpacity(opacityTransferFunction) volumeProperty.SetScalarOpacityUnitDistance(100) volumeProperty.SetInterpolationTypeToLinear() # The mapper / ray cast function know how to render the data. volumeMapper = vtk.vtkGPUVolumeRayCastMapper() volumeMapper.SetInputConnection(reader.GetOutputPort()) # The volume holds the mapper and the property and # can be used to position/orient the volume. volume = vtk.vtkVolume() volume.SetMapper(volumeMapper) volume.SetProperty(volumeProperty) ######################## create a text ##################### # create a text actor txt = vtk.vtkTextActor() txt.SetInput("Color map") txtprop = txt.GetTextProperty() txtprop.SetFontFamilyToArial() txtprop.SetFontSize(24) txtprop.SetColor(0.0, 0.0, 0.0) txt.SetDisplayPosition(450, 550) ############################################################ txt2 = vtk.vtkTextActor() txt_str2 = "timestep = " + filename[30:35] + ", Scalar Value (v02)" txt2.SetInput(txt_str2) txtprop2 = txt2.GetTextProperty() txtprop2.SetFontFamilyToArial() txtprop2.SetFontSize(24) txtprop2.SetColor(0, 0, 0) txt2.SetDisplayPosition(20, 550) ############################ create a color bar ########################### # create the scalar_bar scalar_bar = vtk.vtkScalarBarActor() scalar_bar.SetOrientationToHorizontal() scalar_bar.SetLookupTable(hueLut) # create the scalar_bar_widget scalar_bar_widget = vtk.vtkScalarBarWidget() scalar_bar_widget.SetInteractor(iren) scalar_bar_widget.SetScalarBarActor(scalar_bar) scalar_bar_widget.On() aCamera = vtk.vtkCamera() aCamera.SetViewUp(0, 1, 0) aCamera.SetPosition(-0.2, 0.2, 0.5) aCamera.SetFocalPoint(0, 0, 0) aCamera.ComputeViewPlaneNormal() #aCamera.Azimuth(45.0); #aCamera.Elevation(45.0); #aCamera.Zoom(0.01); #aCamera.Dolly(10.0); # Actors are added to the renderer. aRenderer.AddActor(outline) aRenderer.AddVolume(volume) aRenderer.AddActor(txt) aRenderer.AddActor(txt2) # An initial camera view is created. The Dolly() method moves # the camera towards the FocalPoint, thereby enlarging the image. aRenderer.SetActiveCamera(aCamera) # Calling Render() directly on a vtkRenderer is strictly forbidden. # Only calling Render() on the vtkRenderWindow is a valid call. renWin.Render() aRenderer.ResetCamera() #aCamera.Dolly(-2.0); #################################################################### # screenshot code: w2if = vtk.vtkWindowToImageFilter() w2if.SetInput(renWin) w2if.Update() writer = vtk.vtkPNGWriter() saveName = "plots/yA31/v_r/v02/" + daryName + "_t_" + filename[ 30:35] + ".png" writer.SetFileName(saveName) writer.SetInputData(w2if.GetOutput()) writer.Write() ##################################################################### # Note that when camera movement occurs (as it does in the Dolly() method), # the clipping planes often need adjusting. # Clipping planes consist of two planes: # near and far along the view direction. # The near plane clips out objects in front of the plane; # the far plane clips out objects behind the plane. # This way only what is drawn between the planes is actually rendered. aRenderer.ResetCameraClippingRange() # Interact with the data. renWin.Render()
def _plotInternal(self): """Overrides baseclass implementation.""" numLevels = len(self._contourLevels) cot = vtk.vtkContourFilter() if self._useCellScalars: cot.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) else: cot.SetInputData(self._vtkDataSet) cot.SetNumberOfContours(numLevels) if self._contourLevels[0] == 1.e20: self._contourLevels[0] = -1.e20 for i in range(numLevels): cot.SetValue(i, self._contourLevels[i]) cot.SetValue(numLevels, self._contourLevels[-1]) # TODO remove update cot.Update() mappers = [] lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(len(self._contourColors)) cmap = self._context().canvas.getcolormapname() cmap = vcs.elements["colormap"][cmap] for i, col in enumerate(self._contourColors): r, g, b = cmap.index[col] lut.SetTableValue(i, r / 100., g / 100., b / 100.) # Setup isoline labels if self._gm.label: # Setup label mapping array: tpropMap = vtk.vtkDoubleArray() tpropMap.SetNumberOfComponents(1) tpropMap.SetNumberOfTuples(numLevels) for i, val in enumerate(self._contourLevels): tpropMap.SetTuple(i, [val]) # Prep text properties: tprops = vtk.vtkTextPropertyCollection() if self._gm.text or self._gm.textcolors: # Text objects: if self._gm.text: texts = self._gm.text while len(texts) < numLevels: texts.append(texts[-1]) else: texts = [None] * len(self._gm.textcolors) # Custom colors: if self._gm.textcolors: colorOverrides = self._gm.textcolors while len(colorOverrides) < numLevels: colorOverrides.append(colorOverrides[-1]) else: colorOverrides = [None] * len(self._gm.text) for tc, colorOverride in zip(texts, colorOverrides): if vcs.queries.istextcombined(tc): tt, to = tuple(tc.name.split(":::")) elif tc is None: tt = "default" to = "default" elif vcs.queries.istexttable(tc): tt = tc.name to = "default" elif vcs.queries.istextorientation(tc): to = tc.name tt = "default" if colorOverride is not None: tt = vcs.createtexttable(None, tt) tt.color = colorOverride tt = tt.name tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize(), to, tt) tprops.AddItem(tprop) if colorOverride is not None: del (vcs.elements["texttable"][tt]) else: # No text properties specified. Use the default: tprop = vtk.vtkTextProperty() vcs2vtk.prepTextProperty(tprop, self._context().renWin.GetSize()) tprops.AddItem(tprop) self._resultDict["vtk_backend_contours_labels_text_properties"] = \ tprops mapper = vtk.vtkLabeledContourMapper() mapper.SetTextProperties(tprops) mapper.SetTextPropertyMapping(tpropMap) mapper.SetLabelVisibility(1) mapper.SetSkipDistance(self._gm.labelskipdistance) pdMapper = mapper.GetPolyDataMapper() self._resultDict["vtk_backend_labeled_luts"] = [[ lut, [self._contourLevels[0], self._contourLevels[-1], False] ]] else: # No isoline labels: mapper = vtk.vtkPolyDataMapper() pdMapper = mapper self._resultDict["vtk_backend_luts"] = \ [[lut, [self._contourLevels[0], self._contourLevels[-1], False]]] pdMapper.SetLookupTable(lut) pdMapper.SetScalarRange(self._contourLevels[0], self._contourLevels[-1]) pdMapper.SetScalarModeToUsePointData() stripper = vtk.vtkStripper() stripper.SetInputConnection(cot.GetOutputPort()) mapper.SetInputConnection(stripper.GetOutputPort()) # TODO remove update, make pipeline stripper.Update() mappers.append(mapper) self._resultDict["vtk_backend_contours"] = [cot] if self._maskedDataMapper is not None: mappers.insert(0, self._maskedDataMapper) x1, x2, y1, y2 = vcs.utils.getworldcoordinates(self._gm, self._data1.getAxis(-1), self._data1.getAxis(-2)) # And now we need actors to actually render this thing actors = [] for mapper in mappers: act = vtk.vtkActor() act.SetMapper(mapper) if self._vtkGeoTransform is None: # If using geofilter on wireframed does not get wrppaed not # sure why so sticking to many mappers act = vcs2vtk.doWrap(act, [x1, x2, y1, y2], self._dataWrapModulo) # TODO See comment in boxfill. if mapper is self._maskedDataMapper: actors.append([act, self._maskedDataMapper, [x1, x2, y1, y2]]) else: actors.append([act, [x1, x2, y1, y2]]) # create a new renderer for this mapper # (we need one for each mapper because of cmaera flips) self._context().fitToViewport( act, [ self._template.data.x1, self._template.data.x2, self._template.data.y1, self._template.data.y2 ], wc=[x1, x2, y1, y2], geo=self._vtkGeoTransform, priority=self._template.data.priority, create_renderer=True) self._resultDict["vtk_backend_actors"] = actors t = self._originalData1.getTime() if self._originalData1.ndim > 2: z = self._originalData1.getAxis(-3) else: z = None self._resultDict.update(self._context().renderTemplate( self._template, self._data1, self._gm, t, z)) if self._context().canvas._continents is None: self._useContinents = False if self._useContinents: projection = vcs.elements["projection"][self._gm.projection] self._context().plotContinents(x1, x2, y1, y2, projection, self._dataWrapModulo, self._template)
def surface(points, triangles, labels, ctab, opacity=1): """ Create a colored triangular surface. Parameters ---------- points: array (n_vertices, 3) the surface vertices. triangles: array nfaces x 3 array defining mesh triangles. labels: array (n_vertices) Annotation id at each vertex. If a vertex does not belong to any label its id must be negative. ctab: ndarray (n_labels, 5) RGBA + label id color table array. opacity: float the actor global opacity. Returns ------- actor: vtkActor one actor handling the surface. """ # 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(points)): vtk_points.InsertNextPoint(points[index]) vtk_colors.InsertNextTuple1(labels[index]) for cnt, triangle in enumerate(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) # Make a lookup table using vtkColorSeries nb_of_labels = len(ctab) lut = vtk.vtkLookupTable() lut.SetNumberOfColors(nb_of_labels) lut.Build() for cnt, lut_element in enumerate(ctab): lut.SetTableValue(cnt, lut_element[0] / 255., lut_element[1] / 255., lut_element[2] / 255., lut_element[3] / 255.) lut.SetNanColor(1, 0, 0, 1) # Create (geometry and topology) the associated polydata polydata = vtk.vtkPolyData() polydata.SetPoints(vtk_points) polydata.GetPointData().SetScalars(vtk_colors) polydata.SetPolys(vtk_triangles) # Create the mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInput(polydata) mapper.SetLookupTable(lut) mapper.SetColorModeToMapScalars() mapper.SetScalarRange(0, nb_of_labels) mapper.SetScalarModeToUsePointData() # Create the actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(opacity) return actor
def makeLUT(colorlist, interpolate=False, vmin=None, vmax=None, belowColor=None, aboveColor=None, nanColor=None): """ Generate colors in a vtk lookup table. :param list colorlist: a list in the form ``[(scalar1, [r,g,b]), (scalar2, 'blue'), ...]``. :param bool interpolate: interpolate or not intermediate scalars :param float vmin: specify minimum value of scalar range :param float vmax: specify maximum value of scalar range :param belowColor: color for scalars below the minimum in range :param aboveColor: color for scalars above the maximum in range :return: the lookup table object ``vtkLookupTable``. This can be fed into ``colorMap``. .. hint:: Example: |mesh_lut.py|_ """ lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(256) if nanColor is not None: lut.SetNanColor(list(getColor(nanColor)) + [1]) ctf = vtk.vtkColorTransferFunction() ctf.SetColorSpaceToRGB() ctf.SetScaleToLinear() if belowColor is not None: ctf.SetBelowRangeColor(getColor(belowColor)) ctf.SetUseBelowRangeColor(True) rgba = list(getColor(belowColor)) + [1] if aboveColor is not None: ctf.SetAboveRangeColor(getColor(aboveColor)) ctf.SetUseAboveRangeColor(True) rgba = list(getColor(aboveColor)) + [1] for sc in colorlist: if len(sc) == 3: scalar, col, _ = sc else: scalar, col = sc r, g, b = getColor(col) ctf.AddRGBPoint(scalar, r, g, b) x0, x1 = ctf.GetRange() if vmin is not None: x0 = vmin if vmax is not None: x1 = vmax ctf.SetRange(x0, x1) lut.SetRange(x0, x1) for i in range(256): p = i / 255 x = (1 - p) * x0 + p * x1 if interpolate: rgba = list(ctf.GetColor(x)) + [1] else: rgba = [0.5, 0.5, 0.5, 1] for c in colorlist: if x <= c[0]: if len(c) == 3: al = c[2] else: al = 1 rgba = list(getColor(c[1])) + [al] break lut.SetTableValue(i, rgba) lut.Build() return lut
def prepareDelaunayData(dimension, agg_globalnodeidx, global_nodecoords, aggpolygons, aggid, aggid2nodes, aggid2procs): local_nodeidx2global_nodeidx = {} no_of_aggnodes = len(agg_globalnodeidx) dim = len(global_nodecoords[0]) no_aggs = len(aggid2nodes) Points = vtk.vtkPoints() Vertices = vtk.vtkCellArray() for i in range(0,len(agg_globalnodeidx)): local_nodeidx2global_nodeidx[i] = agg_globalnodeidx[i] nodecoords = global_nodecoords[int(agg_globalnodeidx[i])] if dimension==2: id = Points.InsertNextPoint(nodecoords[0],nodecoords[1],0.0) elif dimension==3: id = Points.InsertNextPoint(nodecoords[0]+ 0.001 * random.random(),nodecoords[1]+ 0.001 * random.random(),nodecoords[2]+ 0.001 * random.random()) Vertices.InsertNextCell(1) Vertices.InsertCellPoint(id) # create polygon for current aggregate polydata = vtk.vtkPolyData() polydata.SetPoints(Points) polydata.SetVerts(Vertices) polydata.Modified() polydata.Update() polydata2 = vtk.vtkPolyData() if Points.GetNumberOfPoints()>2: # todo: avoid error messages + add support for lines/surfaces # create delaunay object if dimension==2: delaunay = vtk.vtkDelaunay2D() elif dimension==3: delaunay = vtk.vtkDelaunay3D() #delaunay.SetAlpha(0.1) delaunay.SetInput(polydata) delaunay.Update() # create surfaceFilter surfaceFilter = vtk.vtkDataSetSurfaceFilter() surfaceFilter.SetInputConnection(delaunay.GetOutputPort()) surfaceFilter.Update() polydata2 = surfaceFilter.GetOutput() lookupTable = vtk.vtkLookupTable() lookupTable.SetNumberOfTableValues(no_aggs) lookupTable.Build() Ids = vtk.vtkUnsignedIntArray() Ids.SetNumberOfComponents(1) Ids.SetName("Ids") for i in range(0,Points.GetNumberOfPoints()): Ids.InsertNextTuple1(int(aggid)) Ids.SetLookupTable(lookupTable) Procs = vtk.vtkUnsignedCharArray() Procs.SetNumberOfComponents(1) Procs.SetName("proc") for i in range(0,Points.GetNumberOfPoints()): Procs.InsertNextTuple1(aggid2procs[aggid]) polydata2.SetPoints(Points) polydata2.SetVerts(Vertices) polydata2.GetPointData().SetScalars(Ids) polydata2.GetPointData().AddArray(Procs) polydata2.Modified() polydata2.Update() aggpolygons.AddInput(polydata2)
def main(): xyzFile, qFile = get_program_parameters() colors = vtk.vtkNamedColors() # Create pipeline. Read structured grid data. pl3d = vtk.vtkMultiBlockPLOT3DReader() pl3d.SetXYZFileName(xyzFile) pl3d.SetQFileName(qFile) pl3d.SetScalarFunctionNumber(100) pl3d.SetVectorFunctionNumber(202) pl3d.Update() pl3dOutput = pl3d.GetOutput().GetBlock(0) # A convenience extract = vtk.vtkExtractGrid() extract.SetVOI(1, 55, -1000, 1000, -1000, 1000) extract.SetInputData(pl3dOutput) # The plane is used to do the cutting plane = vtk.vtkPlane() plane.SetOrigin(0, 4, 2) plane.SetNormal(0, 1, 0) # compositing. cutter = vtk.vtkCutter() cutter.SetInputConnection(extract.GetOutputPort()) cutter.SetCutFunction(plane) cutter.GenerateCutScalarsOff() cutter.SetSortByToSortByCell() clut = vtk.vtkLookupTable() clut.SetHueRange(0, 0.67) clut.Build() cutterMapper = vtk.vtkPolyDataMapper() cutterMapper.SetInputConnection(cutter.GetOutputPort()) cutterMapper.SetScalarRange(0.18, 0.7) cutterMapper.SetLookupTable(clut) cut = vtk.vtkActor() cut.SetMapper(cutterMapper) # Add in some surface geometry for interest. iso = vtk.vtkContourFilter() iso.SetInputData(pl3dOutput) iso.SetValue(0, .22) normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(iso.GetOutputPort()) normals.SetFeatureAngle(60) isoMapper = vtk.vtkPolyDataMapper() isoMapper.SetInputConnection(normals.GetOutputPort()) isoMapper.ScalarVisibilityOff() isoActor = vtk.vtkActor() isoActor.SetMapper(isoMapper) isoActor.GetProperty().SetDiffuseColor(colors.GetColor3d("Tomato")) isoActor.GetProperty().SetSpecularColor(colors.GetColor3d("White")) isoActor.GetProperty().SetDiffuse(0.8) isoActor.GetProperty().SetSpecular(0.5) isoActor.GetProperty().SetSpecularPower(30) outline = vtk.vtkStructuredGridOutlineFilter() outline.SetInputData(pl3dOutput) outlineStrip = vtk.vtkStripper() outlineStrip.SetInputConnection(outline.GetOutputPort()) outlineTubes = vtk.vtkTubeFilter() outlineTubes.SetInputConnection(outline.GetOutputPort()) outlineTubes.SetInputConnection(outlineStrip.GetOutputPort()) outlineTubes.SetRadius(0.1) outlineMapper = vtk.vtkPolyDataMapper() outlineMapper.SetInputConnection(outlineTubes.GetOutputPort()) outlineActor = vtk.vtkActor() outlineActor.SetMapper(outlineMapper) # Create the RenderWindow, Renderer and Interactor. ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Add the actors to the renderer, set the background and size. ren1.AddActor(outlineActor) outlineActor.GetProperty().SetColor(colors.GetColor3d("Banana")) ren1.AddActor(isoActor) isoActor.VisibilityOn() ren1.AddActor(cut) n = 20 opacity = 1.0 / float(n) * 5.0 cut.GetProperty().SetOpacity(1) ren1.SetBackground(colors.GetColor3d("SlateGray")) renWin.SetSize(640, 480) ren1.GetActiveCamera().SetClippingRange(3.95297, 50) ren1.GetActiveCamera().SetFocalPoint(9.71821, 0.458166, 29.3999) ren1.GetActiveCamera().SetPosition(2.7439, -37.3196, 38.7167) ren1.GetActiveCamera().ComputeViewPlaneNormal() ren1.GetActiveCamera().SetViewUp(-0.16123, 0.264271, 0.950876) # Cut: generates n cut planes normal to camera's view plane. plane.SetNormal(ren1.GetActiveCamera().GetViewPlaneNormal()) plane.SetOrigin(ren1.GetActiveCamera().GetFocalPoint()) cutter.GenerateValues(n, -5, 5) clut.SetAlphaRange(opacity, opacity) renWin.Render() iren.Start()
def setEdgesPolydata(self): for e in self.edges: self.myscreen.removeActor(e) self.edges = [] self.edgePoints = vtk.vtkPoints() self.lineCells = vtk.vtkCellArray() self.colorLUT = vtk.vtkLookupTable() idx = 0 last_idx = 0 vd_edges = [] if self.offsetEdges == 0: vd_edges = self.vd.getVoronoiEdges() else: vd_edges = self.vd.getVoronoiEdgesOffset() for e in vd_edges: epts = e[0] # points etype = e[1] # type first = 1 segs = [] for p in epts: self.edgePoints.InsertNextPoint(p.x, p.y, 0) if first == 0: seg = [last_idx, idx] segs.append(seg) first = 0 last_idx = idx idx = idx + 1 # create line and cells for seg in segs: line = vtk.vtkLine() line.GetPointIds().SetId(0, seg[0]) line.GetPointIds().SetId(1, seg[1]) #print " indexes: ", seg[0]," to ",seg[1] self.lineCells.InsertNextCell(line) Colors = vtk.vtkUnsignedCharArray() self.colorLUT = vtk.vtkUnsignedCharArray() self.colorLUT.SetNumberOfComponents(3) self.colorLUT.SetName("Colors") # go through edges once more and set colors m = 0 for e in vd_edges: src_status = e[2] # src status trg_status = e[3] # trg status ecolor = self.edgeTypeColor(e[1], e[2], e[3]) for dummy in e[0]: # go through all the points self.colorLUT.InsertNextTuple3(255 * ecolor[0], 255 * ecolor[1], 255 * ecolor[2]) m = m + 1 linePolyData = vtk.vtkPolyData() linePolyData.SetPoints(self.edgePoints) linePolyData.SetLines(self.lineCells) linePolyData.GetPointData().SetScalars(self.colorLUT) linePolyData.Modified() linePolyData.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInput(linePolyData) self.edge_actor = vtk.vtkActor() self.edge_actor.SetMapper(mapper) self.myscreen.addActor(self.edge_actor) self.edges.append(self.edge_actor)
def _plotInternalCustomBoxfill(self): """Implements the logic to render a custom boxfill.""" self._mappers = [] tmpLevels = [] tmpColors = [] indices = self._gm.fillareaindices if indices is None: indices = [ 1, ] while len(indices) < len(self._contourColors): indices.append(indices[-1]) if len(self._contourLevels) > len(self._contourColors): raise RuntimeError( "You asked for %i levels but provided only %i colors\n" "Graphic Method: %s of type %s\nLevels: %s" % (len(self._contourLevels), len( self._contourColors), self._gm.name, self._gm.g_name), repr(self._contourLevels)) elif len(self._contourLevels) < len(self._contourColors) - 1: warnings.warn( "You asked for %i lgridevels but provided %i colors, " "extra ones will be ignored\nGraphic Method: %s of type %s" % (len(self._contourLevels), len( self._contourColors), self._gm.name, self._gm.g_name)) for i, l in enumerate(self._contourLevels): if i == 0: C = [ self._contourColors[i], ] if numpy.allclose(self._contourLevels[0][0], -1.e20): ## ok it's an extension arrow L = [self._scalarRange[0] - 1., self._contourLevels[0][1]] else: L = list(self._contourLevels[i]) I = [ indices[i], ] else: if l[0] == L[-1] and I[-1] == indices[i]: # Ok same type lets keep going if numpy.allclose(l[1], 1.e20): L.append(self._scalarRange[1] + 1.) else: L.append(l[1]) C.append(self._contourColors[i]) else: # ok we need new contouring tmpLevels.append(L) tmpColors.append(C) C = [ self._contourColors[i], ] L = self._contourLevels[i] I = [ indices[i], ] tmpLevels.append(L) tmpColors.append(C) luts = [] cots = [] geos = [] wholeDataMin, wholeDataMax = vcs.minmax(self._originalData1) for i, l in enumerate(tmpLevels): # Ok here we are trying to group together levels can be, a join will # happen if: next set of levels contnues where one left off AND # pattern is identical # TODO this should really just be a single polydata/mapper/actor: for j, color in enumerate(tmpColors[i]): mapper = vtk.vtkPolyDataMapper() lut = vtk.vtkLookupTable() th = vtk.vtkThreshold() th.ThresholdBetween(l[j], l[j + 1]) th.SetInputConnection(self._vtkPolyDataFilter.GetOutputPort()) geoFilter2 = vtk.vtkDataSetSurfaceFilter() geoFilter2.SetInputConnection(th.GetOutputPort()) geos.append(geoFilter2) mapper.SetInputConnection(geoFilter2.GetOutputPort()) lut.SetNumberOfTableValues(1) r, g, b = self._colorMap.index[color] lut.SetTableValue(0, r / 100., g / 100., b / 100.) mapper.SetLookupTable(lut) mapper.SetScalarRange(l[j], l[j + 1]) luts.append([lut, [l[j], l[j + 1], False]]) ## Store the mapper only if it's worth it? ## Need to do it with the whole slab min/max for animation # purposes if not (l[j + 1] < wholeDataMin or l[j] > wholeDataMax): self._mappers.append(mapper) self._resultDict["vtk_backend_luts"] = luts if len(cots) > 0: self._resultDict["vtk_backend_contours"] = cots if len(geos) > 0: self._resultDict["vtk_backend_geofilters"] = geos
def create(self, filename, orie='coronal', maxint=1000, op=0.99): # set up the source source = vtk.vtkNIFTIImageReader() source.SetFileName(filename) self.source = source # Calculate the center of the volume source.Update() (xMin, xMax, yMin, yMax, zMin, zMax) = source.GetExecutive().GetWholeExtent( source.GetOutputInformation(0)) (xSpacing, ySpacing, zSpacing) = source.GetOutput().GetSpacing() (x0, y0, z0) = source.GetOutput().GetOrigin() self.center = [ x0 + xSpacing * 0.5 * (xMin + xMax), y0 + ySpacing * 0.5 * (yMin + yMax), z0 + zSpacing * 0.5 * (zMin + zMax) ] # Matrices for axial, coronal, sagittal, oblique view orientations orie_mat = _get_orie_mat(self, orie=orie) # Extract a slice in the desired orientation self.reslice = vtk.vtkImageReslice() self.reslice.SetInputConnection(source.GetOutputPort()) self.reslice.SetOutputDimensionality(2) self.reslice.SetResliceAxes(orie_mat) self.reslice.SetInterpolationModeToLinear() # Create a greyscale lookup table if filename == 'T1w_acpc_dc_restore_brain.nii.gz': table = vtk.vtkLookupTable() table.SetRange(0, maxint) # image intensity range table.SetValueRange(0.0, 1.0) # from black to white table.SetSaturationRange(0.0, 0.0) # no color saturation table.SetRampToLinear() table.Build() # Map the image through the lookup table color = vtk.vtkImageMapToColors() color.SetLookupTable(table) color.SetInputConnection(self.reslice.GetOutputPort()) # Display the image actor = vtk.vtkImageActor() actor.GetMapper().SetInputConnection(color.GetOutputPort()) actor.GetProperty().SetOpacity(op) else: table = vtk.vtkLookupTable() table.SetNumberOfTableValues(2) table.Build() nc = vtk.vtkNamedColors() table.SetTableValue(0, nc.GetColor4d("Black")) table.SetTableValue(1, nc.GetColor4d(self.colour)) color = vtk.vtkImageMapToColors() color.SetLookupTable(table) color.SetInputConnection(self.reslice.GetOutputPort()) actor = vtk.vtkImageActor() actor.GetMapper().SetInputConnection(color.GetOutputPort()) actor.GetProperty().SetOpacity(op) return actor, self.center, self.reslice
def tensor(coeff, order, position=(0, 0, 0), radius=0.5, thetares=20, phires=20, opacity=1, tessel=0): """ Generate a generic tensor actor. """ # Create a sphere that we will deform sphere = vtk.vtkSphereSource() sphere.SetRadius(radius) sphere.SetLatLongTessellation(tessel) sphere.SetThetaResolution(thetares) sphere.SetPhiResolution(phires) # Get the polydata poly = sphere.GetOutput() poly.Update() # Get the mesh numPts = poly.GetNumberOfPoints() mesh = numpy.zeros((numPts, 3), dtype=numpy.single) for i in range(numPts): mesh[i, :] = (poly.GetPoint(i)[0], poly.GetPoint(i)[1], poly.GetPoint(i)[2]) # Deform mesh design_matrix = construct_matrix_of_monomials(mesh, order) signal = numpy.dot(design_matrix, coeff) #signal = np.maximum(signal, 0.0) signal /= signal.max() signal *= 0.5 scalars = vtk.vtkFloatArray() pts = vtk.vtkPoints() pts.SetNumberOfPoints(numPts) for i in range(numPts): pts.SetPoint(i, signal[i] * mesh[i, 0], signal[i] * mesh[i, 1], signal[i] * mesh[i, 2]) scalars.InsertTuple1(i, signal[i]) poly.SetPoints(pts) poly.GetPointData().SetScalars(scalars) poly.Update() lut = vtk.vtkLookupTable() lut.SetHueRange(0.667, 0.0) lut.Build() spherem = vtk.vtkPolyDataMapper() spherem.SetInput(poly) spherem.SetLookupTable(lut) spherem.ScalarVisibilityOn() spherem.SetColorModeToMapScalars() spherem.SetScalarRange(0.0, 0.5) actor = vtk.vtkActor() actor.SetMapper(spherem) actor.SetPosition(position) actor.GetProperty().SetOpacity(opacity) return actor
def displaySurfaces(self, progress_callback): """ Create the VTK data structures and display a 3D surface based on the input image. :param (function) progress_callback: Function to emit progress signals """ # Points coordinates structure triangle_vertices = vtk.vtkPoints() # associate the points to triangles triangle = vtk.vtkTriangle() trianglePointIds = triangle.GetPointIds() # put all triangles in an array triangles = vtk.vtkCellArray() surface_data = vtk.vtkIntArray() surface_data.SetNumberOfComponents(1) surface_data.SetName("SurfaceId") isTriangle = 0 nTriangle = 0 surface = 0 # associate each coordinate with a point: 3 coordinates are needed for a point # in 3D. Additionally we perform a shift from image coordinates (pixel) which # is the default of the Contour Tree Algorithm to the World Coordinates. origin = self.origin spacing = self.spacing # augmented matrix for affine transformations mScaling = numpy.asarray([ spacing[0], 0, 0, 0, 0, spacing[1], 0, 0, 0, 0, spacing[2], 0, 0, 0, 0, 1 ]).reshape((4, 4)) mShift = numpy.asarray([ 1, 0, 0, origin[0], 0, 1, 0, origin[1], 0, 0, 1, origin[2], 0, 0, 0, 1 ]).reshape((4, 4)) mTransform = numpy.dot(mScaling, mShift) point_count = 0 surf_list = self.segmentor.getSurfaces() # Calculate the increment for each of the surfaces increment = 60.0 / len(surf_list) for n, surf in enumerate(surf_list, 1): print("Image-to-world coordinate trasformation ... %d" % surface) for point in surf: world_coord = numpy.dot(mTransform, point) triangle_vertices.InsertNextPoint(world_coord[0], world_coord[1], world_coord[2]) # The id of the vertex of the triangle (0,1,2) is linked to # the id of the points in the list, so in facts we just link id-to-id trianglePointIds.SetId(isTriangle, point_count) isTriangle += 1 point_count += 1 if (isTriangle == 3): isTriangle = 0 # insert the current triangle in the triangles array triangles.InsertNextCell(triangle) surface_data.InsertNextValue(surface) progress_callback.emit(int(n * increment + 30)) surface += 1 # polydata object trianglePolyData = vtk.vtkPolyData() trianglePolyData.SetPoints(triangle_vertices) trianglePolyData.SetPolys(triangles) trianglePolyData.GetCellData().AddArray(surface_data) self.viewer3DWidget.viewer.displayPolyData(trianglePolyData) actors = self.viewer3DWidget.viewer.actors if self.surfaceColourCheck.isChecked(): # Change the colour of the polydata actors named_colours = vtk.vtkNamedColors() all_colours = named_colours.GetColorNames().split('\n') lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(surface) lut.Build() for i in range(surface): R, G, B = named_colours.GetColor3d(all_colours[i]) lut.SetTableValue(i, R, G, B) actors[1][0].GetMapper().SetLookupTable(lut) actors[1][0].GetMapper().SetScalarRange(0, surface) actors[1][0].GetMapper().SetScalarModeToUseCellFieldData() actors[1][0].GetMapper().SelectColorArray('SurfaceId') actors[1][0].GetMapper().Update() self.viewer3DWidget.viewer.renWin.Render()
def testVolumePicker(self): # volume render a medical data set # renderer and interactor ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iRen = vtk.vtkRenderWindowInteractor() iRen.SetRenderWindow(renWin) # read the volume v16 = vtk.vtkVolume16Reader() v16.SetDataDimensions(64, 64) v16.SetImageRange(1, 93) v16.SetDataByteOrderToLittleEndian() v16.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter") v16.SetDataSpacing(3.2, 3.2, 1.5) #--------------------------------------------------------- # set up the volume rendering rayCastFunction = vtk.vtkVolumeRayCastCompositeFunction() volumeMapper = vtk.vtkVolumeRayCastMapper() volumeMapper.SetInputConnection(v16.GetOutputPort()) volumeMapper.SetVolumeRayCastFunction(rayCastFunction) volumeColor = vtk.vtkColorTransferFunction() volumeColor.AddRGBPoint(0, 0.0, 0.0, 0.0) volumeColor.AddRGBPoint(180, 0.3, 0.1, 0.2) volumeColor.AddRGBPoint(1000, 1.0, 0.7, 0.6) volumeColor.AddRGBPoint(2000, 1.0, 1.0, 0.9) volumeScalarOpacity = vtk.vtkPiecewiseFunction() volumeScalarOpacity.AddPoint(0, 0.0) volumeScalarOpacity.AddPoint(180, 0.0) volumeScalarOpacity.AddPoint(1000, 0.2) volumeScalarOpacity.AddPoint(2000, 0.8) volumeGradientOpacity = vtk.vtkPiecewiseFunction() volumeGradientOpacity.AddPoint(0, 0.0) volumeGradientOpacity.AddPoint(90, 0.5) volumeGradientOpacity.AddPoint(100, 1.0) volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(volumeColor) volumeProperty.SetScalarOpacity(volumeScalarOpacity) volumeProperty.SetGradientOpacity(volumeGradientOpacity) volumeProperty.SetInterpolationTypeToLinear() volumeProperty.ShadeOn() volumeProperty.SetAmbient(0.6) volumeProperty.SetDiffuse(0.6) volumeProperty.SetSpecular(0.1) volume = vtk.vtkVolume() volume.SetMapper(volumeMapper) volume.SetProperty(volumeProperty) #--------------------------------------------------------- # Do the surface rendering boneExtractor = vtk.vtkMarchingCubes() boneExtractor.SetInputConnection(v16.GetOutputPort()) boneExtractor.SetValue(0, 1150) boneNormals = vtk.vtkPolyDataNormals() boneNormals.SetInputConnection(boneExtractor.GetOutputPort()) boneNormals.SetFeatureAngle(60.0) boneStripper = vtk.vtkStripper() boneStripper.SetInputConnection(boneNormals.GetOutputPort()) boneMapper = vtk.vtkPolyDataMapper() boneMapper.SetInputConnection(boneStripper.GetOutputPort()) boneMapper.ScalarVisibilityOff() boneProperty = vtk.vtkProperty() boneProperty.SetColor(1.0, 1.0, 0.9) bone = vtk.vtkActor() bone.SetMapper(boneMapper) bone.SetProperty(boneProperty) #--------------------------------------------------------- # Create an image actor table = vtk.vtkLookupTable() table.SetRange(0, 2000) table.SetRampToLinear() table.SetValueRange(0, 1) table.SetHueRange(0, 0) table.SetSaturationRange(0, 0) mapToColors = vtk.vtkImageMapToColors() mapToColors.SetInputConnection(v16.GetOutputPort()) mapToColors.SetLookupTable(table) imageActor = vtk.vtkImageActor() imageActor.GetMapper().SetInputConnection(mapToColors.GetOutputPort()) imageActor.SetDisplayExtent(32, 32, 0, 63, 0, 92) #--------------------------------------------------------- # make a transform and some clipping planes transform = vtk.vtkTransform() transform.RotateWXYZ(-20, 0.0, -0.7, 0.7) volume.SetUserTransform(transform) bone.SetUserTransform(transform) imageActor.SetUserTransform(transform) c = volume.GetCenter() volumeClip = vtk.vtkPlane() volumeClip.SetNormal(0, 1, 0) volumeClip.SetOrigin(c) boneClip = vtk.vtkPlane() boneClip.SetNormal(0, 0, 1) boneClip.SetOrigin(c) volumeMapper.AddClippingPlane(volumeClip) boneMapper.AddClippingPlane(boneClip) #--------------------------------------------------------- ren.AddViewProp(volume) ren.AddViewProp(bone) ren.AddViewProp(imageActor) camera = ren.GetActiveCamera() camera.SetFocalPoint(c) camera.SetPosition(c[0] + 500, c[1] - 100, c[2] - 100) camera.SetViewUp(0, 0, -1) ren.ResetCameraClippingRange() renWin.Render() #--------------------------------------------------------- # the cone should point along the Z axis coneSource = vtk.vtkConeSource() coneSource.CappingOn() coneSource.SetHeight(12) coneSource.SetRadius(5) coneSource.SetResolution(31) coneSource.SetCenter(6, 0, 0) coneSource.SetDirection(-1, 0, 0) #--------------------------------------------------------- picker = vtk.vtkVolumePicker() picker.SetTolerance(1.0e-6) picker.SetVolumeOpacityIsovalue(0.01) # This should usually be left alone, but is used here to increase coverage picker.UseVolumeGradientOpacityOn() # A function to point an actor along a vector def PointCone(actor, n): if n[0] < 0.0: actor.RotateWXYZ(180, 0, 1, 0) actor.RotateWXYZ(180, (n[0] - 1.0) * 0.5, n[1] * 0.5, n[2] * 0.5) else: actor.RotateWXYZ(180, (n[0] + 1.0) * 0.5, n[1] * 0.5, n[2] * 0.5) # Pick the actor picker.Pick(192, 103, 0, ren) #print picker p = picker.GetPickPosition() n = picker.GetPickNormal() coneActor1 = vtk.vtkActor() coneActor1.PickableOff() coneMapper1 = vtk.vtkDataSetMapper() coneMapper1.SetInputConnection(coneSource.GetOutputPort()) coneActor1.SetMapper(coneMapper1) coneActor1.GetProperty().SetColor(1, 0, 0) coneActor1.SetPosition(p) PointCone(coneActor1, n) ren.AddViewProp(coneActor1) # Pick the volume picker.Pick(90, 180, 0, ren) p = picker.GetPickPosition() n = picker.GetPickNormal() coneActor2 = vtk.vtkActor() coneActor2.PickableOff() coneMapper2 = vtk.vtkDataSetMapper() coneMapper2.SetInputConnection(coneSource.GetOutputPort()) coneActor2.SetMapper(coneMapper2) coneActor2.GetProperty().SetColor(1, 0, 0) coneActor2.SetPosition(p) PointCone(coneActor2, n) ren.AddViewProp(coneActor2) # Pick the image picker.Pick(200, 200, 0, ren) p = picker.GetPickPosition() n = picker.GetPickNormal() coneActor3 = vtk.vtkActor() coneActor3.PickableOff() coneMapper3 = vtk.vtkDataSetMapper() coneMapper3.SetInputConnection(coneSource.GetOutputPort()) coneActor3.SetMapper(coneMapper3) coneActor3.GetProperty().SetColor(1, 0, 0) coneActor3.SetPosition(p) PointCone(coneActor3, n) ren.AddViewProp(coneActor3) # Pick a clipping plane picker.PickClippingPlanesOn() picker.Pick(145, 160, 0, ren) p = picker.GetPickPosition() n = picker.GetPickNormal() coneActor4 = vtk.vtkActor() coneActor4.PickableOff() coneMapper4 = vtk.vtkDataSetMapper() coneMapper4.SetInputConnection(coneSource.GetOutputPort()) coneActor4.SetMapper(coneMapper4) coneActor4.GetProperty().SetColor(1, 0, 0) coneActor4.SetPosition(p) PointCone(coneActor4, n) ren.AddViewProp(coneActor4) ren.ResetCameraClippingRange() # render and interact with data renWin.Render() img_file = "VolumePicker.png" vtk.test.Testing.compareImage( iRen.GetRenderWindow(), vtk.test.Testing.getAbsImagePath(img_file), threshold=25) vtk.test.Testing.interact()
def line(lines, scalar, lut=None, opacity=1, linewidth=1): """ Create a line actor for one or more lines. Parameters ---------- lines : list a list of array representing a line as 3d points (N, 3) scalar : a float 0 <= scalar <= 1 to associate a color to the bloc of lines. opacity : float (default = 1) the transparency of the bloc of lines: 0 <= transparency <= 1. linewidth : float (default = 1) the line thickness. Returns ---------- actor: vtkActor the bloc of lines actor. """ # Consteruct le lookup table if necessary if lut is None: lut = vtk.vtkLookupTable() lut.SetHueRange(0.667, 0.0) lut.Build() # If one line is passed as a numpy array, create virtually a list around # this structure if not isinstance(lines, types.ListType): lines = [lines] # Create vtk structures vtk_points = vtk.vtkPoints() vtk_line = vtk.vtkCellArray() vtk_scalars = vtk.vtkFloatArray() # Go through all lines for the rendering point_id = 0 for line in lines: # Get the line size nb_of_points, line_dim = line.shape # Associate one scalar to each point of the line for color rendering scalars = [scalar] * nb_of_points # Fill the vtk structure for the curretn line for point_position in range(nb_of_points - 1): # Get the segment [p0, p1] p0 = line[point_position] p1 = line[point_position + 1] # Set line points vtk_points.InsertNextPoint(p0) vtk_points.InsertNextPoint(p1) # Set color property vtk_scalars.SetNumberOfComponents(1) vtk_scalars.InsertNextTuple1(scalars[point_position]) vtk_scalars.InsertNextTuple1(scalars[point_position]) # Set line segment vtk_line.InsertNextCell(2) vtk_line.InsertCellPoint(point_id) vtk_line.InsertCellPoint(point_id + 1) point_id += 2 # Create the line polydata polydata = vtk.vtkPolyData() polydata.SetPoints(vtk_points) polydata.SetLines(vtk_line) polydata.GetPointData().SetScalars(vtk_scalars) # Create the line mapper mapper = vtk.vtkPolyDataMapper() mapper.SetInput(polydata) mapper.SetLookupTable(lut) mapper.SetColorModeToMapScalars() mapper.SetScalarRange(0.0, 1.0) mapper.SetScalarModeToUsePointData() # Create the line actor actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetOpacity(opacity) actor.GetProperty().SetLineWidth(linewidth) return actor
def draw_scene(int_filename, color_mode=0, screen_name=None): ############################################################################### # read polydata file # offscreen = False draw_axes = False segs = [] segs_mapper = [] segs_actor = [] transforms = [] transforms_filter = [] seg_fileformat = '/mnt/data1/bah2015/seg2/seg%05d.vtk' # seg_fileformat = '/media/nebula/data/bah/vtk/seg%05d.vtk' # int_filename = '../matching_area/result.txt' int_data = read_intensity_data(int_filename) int_sum = sum(int_data.values()) int_average = int_sum / 39 int_data_sorted = {} transform = vtk.vtkTransform() transform.RotateWXYZ(90, 0, 1, 0) transformFilter = vtk.vtkTransformPolyDataFilter() transformFilter.SetTransform(transform) for i in range(1, 39): segs.append(vtk.vtkPolyDataReader()) segs[-1].SetFileName(seg_fileformat % i) transforms.append(vtk.vtkTransform()) # transforms[-1].RotateWXYZ(90., 0, 1, 0) transforms_filter.append(vtk.vtkTransformPolyDataFilter()) transforms_filter[-1].SetTransform(transforms[-1]) transforms_filter[-1].SetInputConnection(segs[-1].GetOutputPort()) transforms_filter[-1].Update() segs_mapper.append(vtk.vtkPolyDataMapper()) # segs_mapper[-1].SetInputConnection(segs[-1].GetOutputPort()) segs_mapper[-1].SetInputConnection(transforms_filter[-1].GetOutputPort()) segs_actor.append(vtk.vtkActor()) segs_actor[-1].SetMapper(segs_mapper[-1]) segs_actor[-1].GetProperty().SetOpacity(0.1) # segs_actor[-1].GetProperty().SetColor(color[0], color[1], color[2]) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(64) lut.SetHueRange(0.66667, 0.0) lut.SetSaturationRange(1, 1) lut.SetValueRange(1, 1) lut.Build() scalar_bar = vtk.vtkScalarBarActor() scalar_bar.SetLookupTable(lut) scalar_bar.SetNumberOfLabels(4) i = 0 for k, v in sorted(int_data.items(), key=lambda x: x[1], reverse=True): if i < 6: segs_actor[k - 1].GetProperty().SetOpacity(0.7) rgb = [0.0, 0.0, 0.0] val = float(v - int_average) / (max(int_data.values()) - int_average) lut.GetColor(val, rgb) segs_actor[k - 1].GetProperty().SetColor(rgb) print(' Rank %d : %s (%d) = %d (%f)' % (i + 1, LABEL_NAMES[k - 1], k, v, val)) # print color i += 1 # int_data_sorted[k] = v # print 'Lank %5d : %d (%d)' % (i, k, v) ############################################################################### # draw axis # if draw_axes: axesActor = vtk.vtkAxesActor() ############################################################################### # prepare rendering # ren = vtk.vtkRenderer() ren.SetBackground(0.0, 0.0, 0.0) if draw_axes: ren.AddActor(axesActor) for seg in segs_actor: ren.AddActor(seg) ren.AddActor(scalar_bar) renWin = vtk.vtkRenderWindow() if offscreen: renWin.SetOffScreenRendering(True) renWin.AddRenderer(ren) renWin.SetWindowName('Mouse Brain Viewer 2 + (%s)' % screen_name) renWin.SetSize(1600, 1600) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) iren.Initialize() renWin.Render() get_screenshot(renWin, screen_name + '_1.png') for trans in transforms: trans.RotateWXYZ(90., 0, 1, 0) for trans_filter in transforms_filter: trans_filter.Update() renWin.Render() get_screenshot(renWin, screen_name + '_2.png') for trans in transforms: trans.RotateWXYZ(90., 0, 1, 0) for trans_filter in transforms_filter: trans_filter.Update() renWin.Render() get_screenshot(renWin, screen_name + '_3.png')
def AddASDNeigh_actors(self, ren, renWin, mode, viz_type, iren): # Reading the data for the nieghbours ASD_data = ASDVTKReading.ASDReading() ASD_data.ReadingWrapper(mode, viz_type) # Set the maximum number of entried in the slider to be equal to the number of atoms ######################################################################## # Data structures for the atoms in the neighbour map ######################################################################## AtomGrid = vtk.vtkPolyData() AtomGrid.SetPoints(ASD_data.coord) ASDNeighActors.SLMax = AtomGrid.GetNumberOfPoints() # Atom sphere Atom = vtk.vtkSphereSource() Atom.SetRadius(0.50) Atom.SetThetaResolution(10) Atom.SetPhiResolution(10) # Atom glyph Atoms = vtk.vtkGlyph3DMapper() Atoms.SetInputData(AtomGrid) Atoms.SetSourceConnection(Atom.GetOutputPort()) Atoms.SetScaleFactor(0.5) Atoms.ClampingOn() Atoms.SetScaleModeToNoDataScaling() Atoms.SetColorModeToMapScalars() Atoms.Update() # Atoms actors ASDNeighActors.AtomsActor = vtk.vtkLODActor() ASDNeighActors.AtomsActor.SetMapper(Atoms) ASDNeighActors.AtomsActor.GetProperty().SetOpacity(0.9) ASDNeighActors.AtomsActor.GetProperty().SetColor(0.5, 0.5, 0.5) ######################################################################## # Data structures for the neighbours in the neighbour mapper ######################################################################## #Grid for neighbours ASDNeighActors.NeighGrid = vtk.vtkPolyData() ASDNeighActors.NeighGrid.SetPoints(ASD_data.neighs) ASDNeighActors.NeighGrid.GetPointData().SetScalars(ASD_data.nTypes) ASDNeighActors.NumNeigh = ASDNeighActors.NeighGrid.GetNumberOfPoints() #Neighbour glyphs ASDNeighActors.Neigh = vtk.vtkSphereSource() ASDNeighActors.Neigh.SetRadius(0.50) ASDNeighActors.Neigh.SetThetaResolution(20) ASDNeighActors.Neigh.SetPhiResolution(20) # Set up Neighbour glyphs ASDNeighActors.Neighs = vtk.vtkGlyph3DMapper() ASDNeighActors.Neighs.SetInputData(ASDNeighActors.NeighGrid) ASDNeighActors.Neighs.SetSourceConnection( ASDNeighActors.Neigh.GetOutputPort()) ASDNeighActors.Neighs.SetScaleFactor(1.25) ASDNeighActors.Neighs.SetColorModeToMapScalars() ASDNeighActors.Neighs.SetScaleModeToNoDataScaling() ASDNeighActors.Neighs.SetScalarRange( ASDNeighActors.NeighGrid.GetPointData().GetScalars().GetRange()) # Color lookup table for neighbours lut = vtk.vtkLookupTable() lut.SetNumberOfColors(2) lut.SetTableValue(0, 0.0, 1.0, 0.0, 0.5) lut.SetTableValue(1, 0.0, 0.0, 1.0, 0.5) lut.SetTableRange(ASD_data.nTypes.GetRange()) lut.Build() # Fill up Lookup Table with appropiate colors ASDNeighActors.Neighs.SetLookupTable(lut) ASDNeighActors.Neighs.Update() # Neighbour actors ASDNeighActors.NeighActor = vtk.vtkLODActor() ASDNeighActors.NeighActor.SetMapper(ASDNeighActors.Neighs) ASDNeighActors.NeighActor.GetProperty().SetSpecularColor(0.4, 0.8, 0.4) ASDNeighActors.NeighActor.GetProperty().SetSpecular(0.3) ASDNeighActors.NeighActor.GetProperty().SetSpecularPower(60) ASDNeighActors.NeighActor.GetProperty().SetAmbient(0.2) ASDNeighActors.NeighActor.GetProperty().SetDiffuse(0.8) # Setting up information needed for the camera self.xmin, self.xmax = self.AtomsActor.GetXRange() self.ymin, self.ymax = self.AtomsActor.GetYRange() self.zmin, self.zmax = self.AtomsActor.GetZRange() self.xmid = (self.xmin + self.xmax) / 2 self.ymid = (self.ymin + self.ymax) / 2 self.zmid = (self.zmin + self.zmax) / 2 self.height = max(self.xmax, self.ymax, self.zmax) * 1.75 # Defining the camera directions ren.GetActiveCamera().Azimuth(0) ren.GetActiveCamera().Elevation(0) ren.GetActiveCamera().SetFocalPoint(self.xmid, self.ymid, self.zmid) ren.GetActiveCamera().SetPosition(self.xmid, self.ymid, self.height) # Adding the actors for the neighbour mapping ren.AddActor(ASDNeighActors.NeighActor) ren.AddActor(ASDNeighActors.AtomsActor) iren.Start() renWin.Render()
def __init__(self, reader, orientation, min_value=0, max_value=2000): #xmin xmax ymin ymax zmin zmax self.bounds = reader.GetExecutive().GetWholeExtent( reader.GetOutputInformation(0)) #x y z self.spacing = (xSpacing, ySpacing, zSpacing) = reader.GetOutput().GetSpacing() self.origin = reader.GetOutput().GetOrigin() xMin, xMax, yMin, yMax, zMin, zMax = self.bounds xspacing, ySpacing, zSpacing = self.spacing x0, y0, z0 = self.origin self.center = [ x0 + xSpacing * 0.5 * (xMin + xMax), y0 + ySpacing * 0.5 * (yMin + yMax), z0 + zSpacing * 0.5 * (zMin + zMax) ] # Matrices for axial, coronal, sagittal, oblique view orientations self.axial = vtk.vtkMatrix4x4() self.axial.DeepCopy((1, 0, 0, self.center[0], 0, 1, 0, self.center[1], 0, 0, 1, self.center[2], 0, 0, 0, 1)) self.coronal = vtk.vtkMatrix4x4() self.coronal.DeepCopy( (1, 0, 0, self.center[0], 0, 0, 1, self.center[1], 0, -1, 0, self.center[2], 0, 0, 0, 1)) self.sagittal = vtk.vtkMatrix4x4() self.sagittal.DeepCopy( (0, 0, -1, self.center[0], 1, 0, 0, self.center[1], 0, -1, 0, self.center[2], 0, 0, 0, 1)) # Extract a slice in the desired orientation self.reslice = vtk.vtkImageReslice() self.reslice.SetInputConnection(reader.GetOutputPort()) self.reslice.SetOutputDimensionality(2) if orientation == 'sagittal': self.reslice.SetResliceAxes(self.sagittal) elif orientation == 'coronal': self.reslice.SetResliceAxes(self.coronal) else: self.reslice.SetResliceAxes(self.axial) self.reslice.SetInterpolationModeToLinear() # Create a greyscale lookup table self.table = vtk.vtkLookupTable() self.table.SetRange(min_value, max_value) # image intensity range self.table.SetValueRange(0.0, 1.0) # from black to white self.table.SetSaturationRange(0.0, 0.0) # no color saturation self.table.SetRampToLinear() self.table.Build() # Map the image through the lookup self.table self.color = vtk.vtkImageMapToColors() self.color.SetLookupTable(self.table) self.color.SetInputConnection(self.reslice.GetOutputPort()) # Display the image self.actor = vtk.vtkImageActor() self.actor.GetMapper().SetInputConnection(self.color.GetOutputPort()) self.slicing = False
geometry.SetInputData(reflection) print('With Geometry Filter (HTG to NS)') # Shrink Filter if True: print('With Shrink Filter (NS)') # En 3D, le shrink ne doit pas se faire sur la geometrie car elle ne represente que la peau shrink = vtk.vtkShrinkFilter() shrink.SetInputConnection(geometry.GetOutputPort()) shrink.SetShrinkFactor(.8) else: print('No Shrink Filter (NS)') shrink = geometry # LookupTable lut = vtk.vtkLookupTable() lut.SetHueRange(0.66, 0) lut.UsingLogScale() lut.Build() # Mappers mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(geometry.GetOutputPort()) mapper.SetLookupTable(lut) mapper.SetColorModeToMapScalars() mapper.SetScalarModeToUseCellFieldData() mapper.SelectColorArray('scalar') dataRange = [1, 53] # Forced for compare with 3DMask mapper.SetScalarRange(dataRange[0], dataRange[1])
def main(args): # Demonstrate generation of extruded objects from a segmentation map, where # the extrusion is trimmed by a terrain surface. parser = argparse.ArgumentParser( description= 'Generate extruded buildings given a segmentation map, DSM and DTM') parser.add_argument("segmentation", help="Image with labeled buildings") parser.add_argument("dsm", help="Digital surface model (DSM)") parser.add_argument("dtm", help="Digital terain model (DTM)") parser.add_argument("destination", help="Extruded buildings polygonal file (.vtp)") parser.add_argument( '-l', "--label", type=int, nargs="*", help="Label value(s) used for buildings outlines." "If not specified, [6, 17] (buildings, roads) are used.") parser.add_argument("--no_decimation", action="store_true", help="Do not decimate the contours") parser.add_argument("--no_render", action="store_true", help="Do not render") parser.add_argument("--debug", action="store_true", help="Save intermediate results") args = parser.parse_args(args) # Read the terrain data print("Reading and warping the DTM ...") dtmReader = vtk.vtkGDALRasterReader() dtmReader.SetFileName(args.dtm) dtmC2p = vtk.vtkCellDataToPointData() dtmC2p.SetInputConnection(dtmReader.GetOutputPort()) dtmC2p.Update() # Range of terrain data lo = dtmC2p.GetOutput().GetScalarRange()[0] hi = dtmC2p.GetOutput().GetScalarRange()[1] # Convert the terrain into a polydata. surface = vtk.vtkImageDataGeometryFilter() surface.SetInputConnection(dtmC2p.GetOutputPort()) # Make sure the polygons are planar, so need to use triangles. tris = vtk.vtkTriangleFilter() tris.SetInputConnection(surface.GetOutputPort()) # Warp the surface by scalar values warp = vtk.vtkWarpScalar() warp.SetInputConnection(tris.GetOutputPort()) warp.SetScaleFactor(1) warp.UseNormalOn() warp.SetNormal(0, 0, 1) warp.Update() # Read the segmentation of buildings. Original data in GDAL is cell data. # Point data is interpolated. print("Reading the segmentation ...") segmentationReader = vtk.vtkGDALRasterReader() segmentationReader.SetFileName(args.segmentation) segmentationC2p = vtk.vtkCellDataToPointData() segmentationC2p.SetInputConnection(segmentationReader.GetOutputPort()) segmentationC2p.PassCellDataOn() segmentationC2p.Update() segmentation = segmentationC2p.GetOutput() if (args.debug): segmentationWriter = vtk.vtkXMLImageDataWriter() segmentationWriter.SetFileName("segmentation.vti") segmentationWriter.SetInputConnection(segmentationC2p.GetOutputPort()) segmentationWriter.Update() segmentation = segmentationC2p.GetOutput() sb = segmentation.GetBounds() print("segmentation bounds: \t{}".format(sb)) # Extract polygons # as an alternative, could use vtk.vtkMarchingSquares() contours = vtk.vtkDiscreteFlyingEdges2D() contours.SetInputConnection(segmentationC2p.GetOutputPort()) # default labels # 2 -- no building # 6 -- building # 17 -- road or highway # 65 -- don't score labels = [6, 17] if (args.label): labels = args.label if (args.debug): scalarName = segmentation.GetCellData().GetScalars().GetName() segmentationNp = dsa.WrapDataObject(segmentation) scalars = segmentationNp.CellData[scalarName] allLabels = numpy.unique(scalars) print("Contouring on labels: {} of {}".format(labels, allLabels)) else: print("Contouring on labels: {}".format(labels)) contours.SetNumberOfContours(len(labels)) for i in range(len(labels)): contours.SetValue(i, labels[i]) if (args.debug): contoursWriter = vtk.vtkXMLPolyDataWriter() contoursWriter.SetFileName("contours.vtp") contoursWriter.SetInputConnection(contours.GetOutputPort()) contoursWriter.Update() contoursData = contours.GetOutput() cb = contoursData.GetBounds() print("contours bounds: \t{}".format(cb)) if (not args.no_decimation): print("Decimating the contours ...") # combine lines into a polyline stripperContours = vtk.vtkStripper() stripperContours.SetInputConnection(contours.GetOutputPort()) stripperContours.SetMaximumLength(3000) if (args.debug): stripperWriter = vtk.vtkXMLPolyDataWriter() stripperWriter.SetFileName("stripper.vtp") stripperWriter.SetInputConnection(stripperContours.GetOutputPort()) stripperWriter.Update() # decimate polylines decimateContours = vtk.vtkDecimatePolylineFilter() decimateContours.SetMaximumError(0.01) decimateContours.SetInputConnection(stripperContours.GetOutputPort()) if (args.debug): decimateWriter = vtk.vtkXMLPolyDataWriter() decimateWriter.SetFileName("decimate.vtp") decimateWriter.SetInputConnection(decimateContours.GetOutputPort()) decimateWriter.Update() contours = decimateContours # Create loops print("Creating the loops ...") loops = vtk.vtkContourLoopExtraction() loops.SetInputConnection(contours.GetOutputPort()) if (args.debug): loopsWriter = vtk.vtkXMLPolyDataWriter() loopsWriter.SetFileName("loops.vtp") loopsWriter.SetInputConnection(loops.GetOutputPort()) loopsWriter.Update() # Read the DSM print("Reading the DSM ...") dsmReader = vtk.vtkGDALRasterReader() dsmReader.SetFileName(args.dsm) dsmC2p = vtk.vtkCellDataToPointData() dsmC2p.SetInputConnection(dsmReader.GetOutputPort()) dsmC2p.Update() print("Extruding the buildings ...") fit = vtk.vtkFitToHeightMapFilter() fit.SetInputConnection(loops.GetOutputPort()) fit.SetHeightMapConnection(dsmC2p.GetOutputPort()) fit.UseHeightMapOffsetOn() fit.SetFittingStrategyToPointMaximumHeight() if (args.debug): fitWriter = vtk.vtkXMLPolyDataWriter() fitWriter.SetFileName("fit.vtp") fitWriter.SetInputConnection(fit.GetOutputPort()) fitWriter.Update() # Extrude polygon down to surface extrude = vtk.vtkTrimmedExtrusionFilter() extrude.SetInputConnection(fit.GetOutputPort()) extrude.SetTrimSurfaceConnection(warp.GetOutputPort()) extrude.SetExtrusionDirection(0, 0, 1) extrude.CappingOn() extrudeWriter = vtk.vtkXMLPolyDataWriter() extrudeWriter.SetFileName(args.destination) extrudeWriter.SetInputConnection(extrude.GetOutputPort()) extrudeWriter.Update() if (not args.no_render): # Create the RenderWindow, Renderer # ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # Create pipeline. Load terrain data. lut = vtk.vtkLookupTable() lut.SetHueRange(0.6, 0) lut.SetSaturationRange(1.0, 0) lut.SetValueRange(0.5, 1.0) # Show the terrain dtmMapper = vtk.vtkPolyDataMapper() dtmMapper.SetInputConnection(warp.GetOutputPort()) dtmMapper.SetScalarRange(lo, hi) dtmMapper.SetLookupTable(lut) dtmActor = vtk.vtkActor() dtmActor.SetMapper(dtmMapper) # show the buildings trisExtrude = vtk.vtkTriangleFilter() trisExtrude.SetInputConnection(extrude.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(trisExtrude.GetOutputPort()) mapper.ScalarVisibilityOff() actor = vtk.vtkActor() actor.SetMapper(mapper) # Render it ren.AddActor(dtmActor) ren.AddActor(actor) ren.GetActiveCamera().Elevation(-60) ren.ResetCamera() renWin.Render() iren.Start()
def createPipeline(srcLats, srcLons, dstLats, dstLons, nitersData, radius=1.0): # create the src grid pipeline srcN0, srcN1 = srcLats.shape srcNumPts = srcN0 * srcN1 srcSg = vtk.vtkStructuredGrid() srcPt = vtk.vtkPoints() srcPt.SetNumberOfPoints(srcNumPts) k = 0 for i1 in range(srcN1): for i0 in range(srcN0): r = radius * 1.05 x = r * math.cos(srcLats[i0, i1] * math.pi / 180.) * math.cos( srcLons[i0, i1] * math.pi / 180.) y = r * math.cos(srcLats[i0, i1] * math.pi / 180.) * math.sin( srcLons[i0, i1] * math.pi / 180.) z = r * math.sin(srcLats[i0, i1] * math.pi / 180.) srcPt.SetPoint(k, x, y, z) k += 1 srcSg.SetDimensions(1, srcN0, srcN1) srcSg.SetPoints(srcPt) srcEd = vtk.vtkExtractEdges() srcEt = vtk.vtkTubeFilter() srcEm = vtk.vtkPolyDataMapper() srcEa = vtk.vtkActor() srcEt.SetRadius(0.005) srcEd.SetInputData(srcSg) srcEt.SetInputConnection(srcEd.GetOutputPort()) srcEm.SetInputConnection(srcEt.GetOutputPort()) srcEa.SetMapper(srcEm) srcEa.GetProperty().SetColor(0., 1., 0.) #srcEa.GetProperty().SetOpacity(0.5) dstN0, dstN1 = dstLats.shape numPoints = dstN0 * dstN1 sg = vtk.vtkStructuredGrid() pt = vtk.vtkPoints() pt.SetNumberOfPoints(numPoints) ar = vtk.vtkDoubleArray() numPts = nitersData.shape[0] * nitersData.shape[1] ar.SetNumberOfComponents(1) ar.SetNumberOfTuples(numPts) #ar.SetVoidArray(nitersData, 1, 1) k = 0 for i1 in range(dstN1): for i0 in range(dstN0): elev = 0.0 #0.10 * math.log10(nitersData[i0, i1]) r = radius * (1. + elev) x = r * math.cos(dstLats[i0, i1] * math.pi / 180.) * math.cos( dstLons[i0, i1] * math.pi / 180.) y = r * math.cos(dstLats[i0, i1] * math.pi / 180.) * math.sin( dstLons[i0, i1] * math.pi / 180.) z = r * math.sin(dstLats[i0, i1] * math.pi / 180.) pt.SetPoint(k, x, y, z) ar.SetTuple(k, (float(nitersData[i0, i1]), )) k += 1 sg = vtk.vtkStructuredGrid() sg.SetDimensions(1, dstN0, dstN1) sg.SetPoints(pt) sg.GetPointData().SetScalars(ar) lu = vtk.vtkLookupTable() lu.SetScaleToLog10() #lu.SetTableRange(1, 10) lu.SetNumberOfColors(256) lu.SetHueRange(0.666, 0.) lu.Build() # add a scalar bar sb = vtk.vtkScalarBarActor() sb.SetLookupTable(lu) sb.SetTitle("Number of iters") sb.SetNumberOfLabels(4) # show the dst grid dstEd = vtk.vtkExtractEdges() dstEt = vtk.vtkTubeFilter() dstEm = vtk.vtkPolyDataMapper() dstEa = vtk.vtkActor() dstEt.SetRadius(0.005) dstEd.SetInputData(sg) dstEt.SetInputConnection(dstEd.GetOutputPort()) dstEm.SetInputConnection(dstEt.GetOutputPort()) dstEa.SetMapper(dstEm) dstEa.GetProperty().SetColor(1., 0., 0.) #dstEa.GetProperty().SetOpacity(0.5) # show number of iterations as a color plot mp = vtk.vtkDataSetMapper() mp.SetInputData(sg) mp.SetLookupTable(lu) mp.SetScalarRange(1, args.nitermax) ac = vtk.vtkActor() ac.SetMapper(mp) return { 'actors': [ ac, sb, ], 'stuff': (sg, pt, mp, ar, lu, srcSg, srcPt, srcEd, srcEt, srcEm, dstEd, dstEt, dstEm) }
def extract_branches(self): '''Extract branches from the centerlines based on CenterlinesIds. ''' print("[centerlines] ========== extract_branches ==========") data_array = self.geometry.GetPointData().GetArray(self.cids_array_name) num_centerlines = self.get_centerline_info() min_id = 0 max_id = num_centerlines-1 cid_list = list(range(min_id,max_id+1)) print("[extract_branches] Centerline IDs: {0:s}".format(str(cid_list))) self.cid_list = cid_list # Create a color lookup table for branch geometry. self.lut = vtk.vtkLookupTable() self.lut.SetTableRange(min_id, max_id+1) self.lut.SetHueRange(0, 1) self.lut.SetSaturationRange(1, 1) self.lut.SetValueRange(1, 1) self.lut.Build() max_radius_data = self.geometry.GetPointData().GetArray(self.max_radius_array_name) num_lines = self.geometry.GetNumberOfLines() num_points = self.geometry.GetNumberOfPoints() points = self.geometry.GetPoints() print("[centerlines] Number of centerline lines: {0:d}".format(num_lines)) print("[centerlines] Number of centerline points: {0:d}".format(num_points)) # Find the longest branch. max_num_lines = 0 longest_cid = None for cid in range(min_id,max_id+1): branch_geom = self.extract_branch_geom(cid) if branch_geom.GetNumberOfLines() > max_num_lines: max_num_lines = branch_geom.GetNumberOfLines() longest_cid = cid print("\n[centerlines] Longest branch cid: {0:d} Number of lines: {1:d}".format(longest_cid, max_num_lines)) self.longest_cid = longest_cid # Create cell_id -> centerline id map. cell_cids = defaultdict(list) for cid in cid_list: #print("\n---------- cid {0:d} ----------".format(cid)) for i in range(num_lines): cell = self.geometry.GetCell(i) cell_pids = cell.GetPointIds() num_ids = cell_pids.GetNumberOfIds() pid1 = cell_pids.GetId(0) pid2 = cell_pids.GetId(1) value1 = int(data_array.GetComponent(pid1, cid)) value2 = int(data_array.GetComponent(pid2, cid)) if (value1 == 1) or (value2 == 1): cell_cids[i].append(cid) #_for j in range(num_ids) #_for i in range(num_lines) #_for cid in range(min_id,max_id+1) # Determine branch cells. branch_cells = defaultdict(list) for cid in cid_list: for i in range(num_lines): cids = cell_cids[i] if longest_cid in cids: if i not in branch_cells[longest_cid]: branch_cells[longest_cid].append(i) else: if (len(cids) == 1) and (cids[0] == cid): branch_cells[cid].append(i) if cid in cell_cids[i]: cell_cids[i].remove(cid) #_for j in range(num_ids) #_for cid in cid_list # Create branch geomerty. self.branches = [] end_point_ids = self.ends_node_ids for cid in cid_list: self.branches.append( self.create_branch(cid, branch_cells, end_point_ids) )
def vtk_scalar_actor(filename): import vtk colobar_agros2d = [[ 0.125500, 0.162200, 0.960000 ], [ 0.132175, 0.167787, 0.954839 ], [ 0.138849, 0.173373, 0.949678 ], [ 0.145524, 0.178960, 0.944518 ], [ 0.152198, 0.184547, 0.939357 ], [ 0.158873, 0.190133, 0.934196 ], [ 0.165547, 0.195720, 0.929035 ], [ 0.172222, 0.201307, 0.923875 ], [ 0.178896, 0.206893, 0.918714 ], [ 0.185571, 0.212480, 0.913553 ], [ 0.192245, 0.218067, 0.908392 ], [ 0.198920, 0.223653, 0.903231 ], [ 0.205594, 0.229240, 0.898071 ], [ 0.212269, 0.234827, 0.892910 ], [ 0.218943, 0.240413, 0.887749 ], [ 0.225618, 0.246000, 0.882588 ], [ 0.232292, 0.251587, 0.877427 ], [ 0.238967, 0.257173, 0.872267 ], [ 0.245641, 0.262760, 0.867106 ], [ 0.252316, 0.268347, 0.861945 ], [ 0.258990, 0.273933, 0.856784 ], [ 0.265665, 0.279520, 0.851624 ], [ 0.272339, 0.285107, 0.846463 ], [ 0.279014, 0.290693, 0.841302 ], [ 0.285688, 0.296280, 0.836141 ], [ 0.292363, 0.301867, 0.830980 ], [ 0.299037, 0.307453, 0.825820 ], [ 0.305712, 0.313040, 0.820659 ], [ 0.312386, 0.318627, 0.815498 ], [ 0.319061, 0.324213, 0.810337 ], [ 0.325735, 0.329800, 0.805176 ], [ 0.332410, 0.335387, 0.800016 ], [ 0.339084, 0.340973, 0.794855 ], [ 0.345759, 0.346560, 0.789694 ], [ 0.352433, 0.352147, 0.784533 ], [ 0.359108, 0.357733, 0.779373 ], [ 0.365782, 0.363320, 0.774212 ], [ 0.372457, 0.368907, 0.769051 ], [ 0.379131, 0.374493, 0.763890 ], [ 0.385806, 0.380080, 0.758729 ], [ 0.392480, 0.385667, 0.753569 ], [ 0.399155, 0.391253, 0.748408 ], [ 0.405829, 0.396840, 0.743247 ], [ 0.412504, 0.402427, 0.738086 ], [ 0.419178, 0.408013, 0.732925 ], [ 0.425853, 0.413600, 0.727765 ], [ 0.432527, 0.419187, 0.722604 ], [ 0.439202, 0.424773, 0.717443 ], [ 0.445876, 0.430360, 0.712282 ], [ 0.452551, 0.435947, 0.707122 ], [ 0.459225, 0.441533, 0.701961 ], [ 0.465900, 0.447120, 0.696800 ], [ 0.472575, 0.452707, 0.691639 ], [ 0.479249, 0.458293, 0.686478 ], [ 0.485924, 0.463880, 0.681318 ], [ 0.492598, 0.469467, 0.676157 ], [ 0.499273, 0.475053, 0.670996 ], [ 0.505947, 0.480640, 0.665835 ], [ 0.512622, 0.486227, 0.660675 ], [ 0.519296, 0.491813, 0.655514 ], [ 0.525971, 0.497400, 0.650353 ], [ 0.532645, 0.502987, 0.645192 ], [ 0.539320, 0.508573, 0.640031 ], [ 0.545994, 0.514160, 0.634871 ], [ 0.552669, 0.519747, 0.629710 ], [ 0.559343, 0.525333, 0.624549 ], [ 0.566018, 0.530920, 0.619388 ], [ 0.572692, 0.536507, 0.614227 ], [ 0.579367, 0.542093, 0.609067 ], [ 0.586041, 0.547680, 0.603906 ], [ 0.592716, 0.553267, 0.598745 ], [ 0.599390, 0.558853, 0.593584 ], [ 0.606065, 0.564440, 0.588424 ], [ 0.612739, 0.570027, 0.583263 ], [ 0.619414, 0.575613, 0.578102 ], [ 0.626088, 0.581200, 0.572941 ], [ 0.632763, 0.586787, 0.567780 ], [ 0.639437, 0.592373, 0.562620 ], [ 0.646112, 0.597960, 0.557459 ], [ 0.652786, 0.603547, 0.552298 ], [ 0.659461, 0.609133, 0.547137 ], [ 0.666135, 0.614720, 0.541976 ], [ 0.672810, 0.620307, 0.536816 ], [ 0.679484, 0.625893, 0.531655 ], [ 0.686159, 0.631480, 0.526494 ], [ 0.692833, 0.637067, 0.521333 ], [ 0.699508, 0.642653, 0.516173 ], [ 0.706182, 0.648240, 0.511012 ], [ 0.712857, 0.653827, 0.505851 ], [ 0.719531, 0.659413, 0.500690 ], [ 0.726206, 0.665000, 0.495529 ], [ 0.732880, 0.670587, 0.490369 ], [ 0.739555, 0.676173, 0.485208 ], [ 0.746229, 0.681760, 0.480047 ], [ 0.752904, 0.687347, 0.474886 ], [ 0.759578, 0.692933, 0.469725 ], [ 0.766253, 0.698520, 0.464565 ], [ 0.772927, 0.704107, 0.459404 ], [ 0.779602, 0.709693, 0.454243 ], [ 0.786276, 0.715280, 0.449082 ], [ 0.792951, 0.720867, 0.443922 ], [ 0.799625, 0.726453, 0.438761 ], [ 0.806300, 0.732040, 0.433600 ], [ 0.812975, 0.737627, 0.428439 ], [ 0.819649, 0.743213, 0.423278 ], [ 0.826324, 0.748800, 0.418118 ], [ 0.832998, 0.754387, 0.412957 ], [ 0.839673, 0.759973, 0.407796 ], [ 0.846347, 0.765560, 0.402635 ], [ 0.853022, 0.771147, 0.397475 ], [ 0.859696, 0.776733, 0.392314 ], [ 0.866371, 0.782320, 0.387153 ], [ 0.873045, 0.787907, 0.381992 ], [ 0.879720, 0.793493, 0.376831 ], [ 0.886394, 0.799080, 0.371671 ], [ 0.893069, 0.804667, 0.366510 ], [ 0.899743, 0.810253, 0.361349 ], [ 0.906418, 0.815840, 0.356188 ], [ 0.913092, 0.821427, 0.351027 ], [ 0.919767, 0.827013, 0.345867 ], [ 0.926441, 0.832600, 0.340706 ], [ 0.933116, 0.838187, 0.335545 ], [ 0.939790, 0.843773, 0.330384 ], [ 0.946465, 0.849360, 0.325224 ], [ 0.953139, 0.854947, 0.320063 ], [ 0.959814, 0.860533, 0.314902 ], [ 0.966488, 0.866120, 0.309741 ], [ 0.973163, 0.871707, 0.304580 ], [ 0.976435, 0.871778, 0.301400 ], [ 0.976306, 0.866334, 0.300200 ], [ 0.976176, 0.860890, 0.299000 ], [ 0.976047, 0.855446, 0.297800 ], [ 0.975918, 0.850002, 0.296600 ], [ 0.975788, 0.844558, 0.295400 ], [ 0.975659, 0.839115, 0.294200 ], [ 0.975529, 0.833671, 0.293000 ], [ 0.975400, 0.828227, 0.291800 ], [ 0.975271, 0.822783, 0.290600 ], [ 0.975141, 0.817339, 0.289400 ], [ 0.975012, 0.811895, 0.288200 ], [ 0.974882, 0.806451, 0.287000 ], [ 0.974753, 0.801007, 0.285800 ], [ 0.974624, 0.795563, 0.284600 ], [ 0.974494, 0.790119, 0.283400 ], [ 0.974365, 0.784675, 0.282200 ], [ 0.974235, 0.779231, 0.281000 ], [ 0.974106, 0.773787, 0.279800 ], [ 0.973976, 0.768344, 0.278600 ], [ 0.973847, 0.762900, 0.277400 ], [ 0.973718, 0.757456, 0.276200 ], [ 0.973588, 0.752012, 0.275000 ], [ 0.973459, 0.746568, 0.273800 ], [ 0.973329, 0.741124, 0.272600 ], [ 0.973200, 0.735680, 0.271400 ], [ 0.973071, 0.730236, 0.270200 ], [ 0.972941, 0.724792, 0.269000 ], [ 0.972812, 0.719348, 0.267800 ], [ 0.972682, 0.713904, 0.266600 ], [ 0.972553, 0.708460, 0.265400 ], [ 0.972424, 0.703016, 0.264200 ], [ 0.972294, 0.697573, 0.263000 ], [ 0.972165, 0.692129, 0.261800 ], [ 0.972035, 0.686685, 0.260600 ], [ 0.971906, 0.681241, 0.259400 ], [ 0.971776, 0.675797, 0.258200 ], [ 0.971647, 0.670353, 0.257000 ], [ 0.971518, 0.664909, 0.255800 ], [ 0.971388, 0.659465, 0.254600 ], [ 0.971259, 0.654021, 0.253400 ], [ 0.971129, 0.648577, 0.252200 ], [ 0.971000, 0.643133, 0.251000 ], [ 0.970871, 0.637689, 0.249800 ], [ 0.970741, 0.632245, 0.248600 ], [ 0.970612, 0.626802, 0.247400 ], [ 0.970482, 0.621358, 0.246200 ], [ 0.970353, 0.615914, 0.245000 ], [ 0.970224, 0.610470, 0.243800 ], [ 0.970094, 0.605026, 0.242600 ], [ 0.969965, 0.599582, 0.241400 ], [ 0.969835, 0.594138, 0.240200 ], [ 0.969706, 0.588694, 0.239000 ], [ 0.969576, 0.583250, 0.237800 ], [ 0.969447, 0.577806, 0.236600 ], [ 0.969318, 0.572362, 0.235400 ], [ 0.969188, 0.566918, 0.234200 ], [ 0.969059, 0.561475, 0.233000 ], [ 0.968929, 0.556031, 0.231800 ], [ 0.968800, 0.550587, 0.230600 ], [ 0.968671, 0.545143, 0.229400 ], [ 0.968541, 0.539699, 0.228200 ], [ 0.968412, 0.534255, 0.227000 ], [ 0.968282, 0.528811, 0.225800 ], [ 0.968153, 0.523367, 0.224600 ], [ 0.968024, 0.517923, 0.223400 ], [ 0.967894, 0.512479, 0.222200 ], [ 0.967765, 0.507035, 0.221000 ], [ 0.967635, 0.501591, 0.219800 ], [ 0.967506, 0.496147, 0.218600 ], [ 0.967376, 0.490704, 0.217400 ], [ 0.967247, 0.485260, 0.216200 ], [ 0.967118, 0.479816, 0.215000 ], [ 0.966988, 0.474372, 0.213800 ], [ 0.966859, 0.468928, 0.212600 ], [ 0.966729, 0.463484, 0.211400 ], [ 0.966600, 0.458040, 0.210200 ], [ 0.966471, 0.452596, 0.209000 ], [ 0.966341, 0.447152, 0.207800 ], [ 0.966212, 0.441708, 0.206600 ], [ 0.966082, 0.436264, 0.205400 ], [ 0.965953, 0.430820, 0.204200 ], [ 0.965824, 0.425376, 0.203000 ], [ 0.965694, 0.419933, 0.201800 ], [ 0.965565, 0.414489, 0.200600 ], [ 0.965435, 0.409045, 0.199400 ], [ 0.965306, 0.403601, 0.198200 ], [ 0.965176, 0.398157, 0.197000 ], [ 0.965047, 0.392713, 0.195800 ], [ 0.964918, 0.387269, 0.194600 ], [ 0.964788, 0.381825, 0.193400 ], [ 0.964659, 0.376381, 0.192200 ], [ 0.964529, 0.370937, 0.191000 ], [ 0.964400, 0.365493, 0.189800 ], [ 0.964271, 0.360049, 0.188600 ], [ 0.964141, 0.354605, 0.187400 ], [ 0.964012, 0.349162, 0.186200 ], [ 0.963882, 0.343718, 0.185000 ], [ 0.963753, 0.338274, 0.183800 ], [ 0.963624, 0.332830, 0.182600 ], [ 0.963494, 0.327386, 0.181400 ], [ 0.963365, 0.321942, 0.180200 ], [ 0.963235, 0.316498, 0.179000 ], [ 0.963106, 0.311054, 0.177800 ], [ 0.962976, 0.305610, 0.176600 ], [ 0.962847, 0.300166, 0.175400 ], [ 0.962718, 0.294722, 0.174200 ], [ 0.962588, 0.289278, 0.173000 ], [ 0.962459, 0.283835, 0.171800 ], [ 0.962329, 0.278391, 0.170600 ], [ 0.962200, 0.272947, 0.169400 ], [ 0.962071, 0.267503, 0.168200 ], [ 0.961941, 0.262059, 0.167000 ], [ 0.961812, 0.256615, 0.165800 ], [ 0.961682, 0.251171, 0.164600 ], [ 0.961553, 0.245727, 0.163400 ], [ 0.961424, 0.240283, 0.162200 ], [ 0.961294, 0.234839, 0.161000 ], [ 0.961165, 0.229395, 0.159800 ], [ 0.961035, 0.223951, 0.158600 ], [ 0.960906, 0.218507, 0.157400 ], [ 0.960776, 0.213064, 0.156200 ], [ 0.960647, 0.207620, 0.155000 ], [ 0.960518, 0.202176, 0.153800 ], [ 0.960388, 0.196732, 0.152600 ], [ 0.960259, 0.191288, 0.151400 ], [ 0.960129, 0.185844, 0.150200 ], [ 0.960000, 0.180400, 0.149000 ]] # read the source file. reader = vtk.vtkUnstructuredGridReader() reader.SetFileName(filename) reader.Update() output = reader.GetOutput() scalar_range = output.GetScalarRange() # create own palette lut = vtk.vtkLookupTable() lut.SetRange(scalar_range) for i in range(len(colobar_agros2d)): lut.SetTableValue(i, colobar_agros2d[i][0], colobar_agros2d[i][1], colobar_agros2d[i][2]) lut.Build() # create the mapper that corresponds the objects of the vtk file into graphics elements mapper = vtk.vtkDataSetMapper() mapper.SetInput(output) mapper.SetScalarRange(scalar_range) mapper.SetLookupTable(lut) # actor actor = vtk.vtkActor() actor.SetMapper(mapper) return actor