def createItemToolbar(self): """ Method to create a toolbar for the window that allows use to select processed channel """ # Pass flag force which indicates that we do want an item toolbar # although we only have one input channel n = GUI.FilterBasedTaskPanel.FilterBasedTaskPanel.createItemToolbar(self, force=1) for i, tid in enumerate(self.toolIds): self.dataUnit.setOutputChannel(i, 0) self.toolMgr.toggleTool(tid, 0) ctf = vtk.vtkColorTransferFunction() ctf.AddRGBPoint(0, 0, 0, 0) ctf.AddRGBPoint(255, 1, 1, 1) imagedata = self.itemMips[0] ctf = vtk.vtkColorTransferFunction() ctf.AddRGBPoint(0, 0, 0, 0) ctf.AddRGBPoint(255, 1, 1, 1) maptocolor = vtk.vtkImageMapToColors() maptocolor.SetInput(imagedata) maptocolor.SetLookupTable(ctf) maptocolor.SetOutputFormatToRGB() maptocolor.Update() imagedata = maptocolor.GetOutput() bmp = lib.ImageOperations.vtkImageDataToWxImage(imagedata).ConvertToBitmap() bmp = self.getChannelItemBitmap(bmp, (255, 255, 255)) toolid = wx.NewId() name = "Manipulation" self.toolMgr.addChannelItem(name, bmp, toolid, lambda e, x=n, s=self: s.setPreviewedData(e, x)) self.toolIds.append(toolid) self.dataUnit.setOutputChannel(len(self.toolIds), 1) self.toolMgr.toggleTool(toolid, 1)
def onSetSelectedObjects(self, obj, event, objects, isROI = 0): """ An event handler for highlighting selected objects """ if not self.ctf: self.ctf = self.dataUnit.getColorTransferFunction() if not objects: self.dataUnit.getSettings().set("ColorTransferFunction", self.ctf) lib.messenger.send(None, "data_changed", 0) return if not isROI: # Since these object id's come from the list indices, instead of being the actual # intensity values, we need to add 2 to each object value to account for the # pseudo objects 0 and 1 produced by the segmentation results objects = [x + 2 for x in objects] self.selections = objects ctf = vtk.vtkColorTransferFunction() minval, maxval = self.ctf.GetRange() hv = 0.4 ctf.AddRGBPoint(0, 0, 0, 0) ctf.AddRGBPoint(1, 0, 0, 0) ctf.AddRGBPoint(2, hv, hv, hv) ctf.AddRGBPoint(maxval, hv, hv, hv) for obj in objects: val = [0, 0, 0] if obj - 1 not in objects: ctf.AddRGBPoint(obj - 1, hv, hv, hv) ctf.AddRGBPoint(obj, 0.0, 1.0, 0.0) if obj + 1 not in objects: ctf.AddRGBPoint(obj + 1, hv, hv, hv) print "Setting CTF where highlighted=", objects self.dataUnit.getSettings().set("ColorTransferFunction", ctf) lib.messenger.send(None, "data_changed", 0)
def __init__(self, n = -1): """ Method: __init__ Constructor """ DataUnitSettings.__init__(self, n) self.set("Type", "Colocalization") self.registerCounted("ColocalizationLowerThreshold", 1) self.registerCounted("ColocalizationUpperThreshold", 1) self.register("ColocalizationDepth", 1) self.register("CalculateThresholds") for i in ["PValue", "RObserved", "RRandMean", "RRandSD", "NumIterations", "ColocCount", "Method", "PSF", "Ch1ThresholdMax", "Ch2ThresholdMax", "PearsonImageAbove", "PearsonImageBelow", "PearsonWholeImage", "M1", "M2", "ThresholdM1", "ThresholdM2", "Slope", "Intercept", "K1", "K2", "DiffStainIntCh1", "DiffStainIntCh2", "DiffStainVoxelsCh1", "DiffStainVoxelsCh2", "ColocAmount", "ColocPercent", "PercentageVolumeCh1", "PercentageTotalCh1", "PercentageTotalCh2", "PercentageVolumeCh2", "PercentageMaterialCh1", "PercentageMaterialCh2", "SumOverThresholdCh1", "SumOverThresholdCh2", "SumCh1", "SumCh2", "NonZeroCh1", "NonZeroCh2", "OverThresholdCh1", "OverThresholdCh2", "Ch2Lambda"]: self.register(i, 1) self.register("OutputScalar", 1) #self.register("ColocalizationColorTransferFunction",1) ctf = vtk.vtkColorTransferFunction() ctf.AddRGBPoint(0, 0, 0, 0) ctf.AddRGBPoint(255, 1.0, 1.0, 1.0) self.set("ColorTransferFunction", ctf) # This is used purely for remembering the ctf the user has set self.register("ColocalizationColorTransferFunction", 1)
def __init__(self, img, color): self.volume = vtk.vtkVolume() self.__color = color dataImporter = vtk.vtkImageImport() simg = np.ascontiguousarray(img, np.uint8) dataImporter.CopyImportVoidPointer(simg.data, len(simg.data)) dataImporter.SetDataScalarTypeToUnsignedChar() dataImporter.SetNumberOfScalarComponents(1) dataImporter.SetDataExtent(0, simg.shape[2]-1, 0, simg.shape[1]-1, 0, simg.shape[0]-1) dataImporter.SetWholeExtent(0, simg.shape[2]-1, 0, simg.shape[1]-1, 0, simg.shape[0]-1) self.__smoother = vtk.vtkImageGaussianSmooth() self.__smoother.SetStandardDeviation(1, 1, 1) self.__smoother.SetInputConnection(dataImporter.GetOutputPort()) volumeMapper = vtk.vtkSmartVolumeMapper() volumeMapper.SetInputConnection(self.__smoother.GetOutputPort()) self.__volumeProperty = vtk.vtkVolumeProperty() self.__colorFunc = vtk.vtkColorTransferFunction() self.__alpha = vtk.vtkPiecewiseFunction() for i in range(256): self.__colorFunc.AddRGBPoint(i, i * color[0], i * color[1], i * color[2]) self.__alpha.AddPoint(5, .01) self.__alpha.AddPoint(10, .03) self.__alpha.AddPoint(50, .1) self.__alpha.AddPoint(150, .2) self.__volumeProperty.SetColor(self.__colorFunc) self.__volumeProperty.SetScalarOpacity(self.__alpha) self.volume.SetMapper(volumeMapper) self.volume.SetProperty(self.__volumeProperty)
def testGetRangeNoArg(self): cmap = vtk.vtkColorTransferFunction() crange = cmap.GetRange() self.assertEqual(len(crange), 2) self.assertEqual(crange[0], 0.0) self.assertEqual(crange[1], 0.0)
def _createPipeline(self): # setup our pipeline self._splatMapper = vtkdevide.vtkOpenGLVolumeShellSplatMapper() self._splatMapper.SetOmegaL(0.9) self._splatMapper.SetOmegaH(0.9) # high-quality rendermode self._splatMapper.SetRenderMode(0) self._otf = vtk.vtkPiecewiseFunction() self._otf.AddPoint(0.0, 0.0) self._otf.AddPoint(0.9, 0.0) self._otf.AddPoint(1.0, 1.0) self._ctf = vtk.vtkColorTransferFunction() self._ctf.AddRGBPoint(0.0, 0.0, 0.0, 0.0) self._ctf.AddRGBPoint(0.9, 0.0, 0.0, 0.0) self._ctf.AddRGBPoint(1.0, 1.0, 0.937, 0.859) self._volumeProperty = vtk.vtkVolumeProperty() self._volumeProperty.SetScalarOpacity(self._otf) self._volumeProperty.SetColor(self._ctf) self._volumeProperty.ShadeOn() self._volumeProperty.SetAmbient(0.1) self._volumeProperty.SetDiffuse(0.7) self._volumeProperty.SetSpecular(0.2) self._volumeProperty.SetSpecularPower(10) self._volume = vtk.vtkVolume() self._volume.SetProperty(self._volumeProperty) self._volume.SetMapper(self._splatMapper)
def originalObject(self): colorTransferFunction = vtkColorTransferFunction() for index in range(len(self.nodes)): value = self.nodes[index] colorTransferFunction.AddRGBPoint(value[0], value[1], value[2], value[3], value[4], value[5]) return colorTransferFunction
def updateTransferFunction(self): r, g, b = self.color # Transfer functions and properties if not self.colorFunction: self.colorFunction = vtkColorTransferFunction() else: self.colorFunction.RemoveAllPoints() self.colorFunction.AddRGBPoint(self.minimum, r*0.7, g*0.7, b*0.7) self.colorFunction.AddRGBPoint(self.maximum, r, g, b) if not self.opacityFunction: self.opacityFunction = vtkPiecewiseFunction() else: self.opacityFunction.RemoveAllPoints() self.opacityFunction.AddPoint(self.minimum, 0) self.opacityFunction.AddPoint(self.lowerBound, 0) self.opacityFunction.AddPoint(self.lowerBound+0.0001, self.opacity) self.opacityFunction.AddPoint(self.upperBound-0.0001, self.opacity) self.opacityFunction.AddPoint(self.upperBound, 0) self.opacityFunction.AddPoint(self.maximum+0.0001, 0) self.volProp.SetColor(self.colorFunction) self.volProp.SetScalarOpacity(self.opacityFunction) self.updatedTransferFunction.emit()
def volumeRender(reader,ren,renWin): #Create transfer mapping scalar value to opacity opacityTransferFunction = vtk.vtkPiecewiseFunction() opacityTransferFunction.AddPoint(1, 0.0) opacityTransferFunction.AddPoint(100, 0.1) opacityTransferFunction.AddPoint(255,1.0) colorTransferFunction = vtk.vtkColorTransferFunction() colorTransferFunction.AddRGBPoint(0.0,0.0,0.0,0.0) colorTransferFunction.AddRGBPoint(64.0,1.0,0.0,0.0) colorTransferFunction.AddRGBPoint(128.0,0.0,0.0,1.0) colorTransferFunction.AddRGBPoint(192.0,0.0,1.0,0.0) colorTransferFunction.AddRGBPoint(255.0,0.0,0.2,0.0) volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(colorTransferFunction) volumeProperty.SetScalarOpacity(opacityTransferFunction) volumeProperty.ShadeOn() volumeProperty.SetInterpolationTypeToLinear() compositeFunction = vtk.vtkVolumeRayCastCompositeFunction() volumeMapper = vtk.vtkFixedPointVolumeRayCastMapper() volumeMapper.SetInputConnection(reader.GetOutputPort()) volume = vtk.vtkVolume() volume.SetMapper(volumeMapper) volume.SetProperty(volumeProperty) ren.RemoveAllViewProps() ren.AddVolume(volume) ren.SetBackground(1,1,1) renWin.Render()
def __init__(self, name, image_data): if not isinstance(image_data, vtk.vtkImageData): raise TypeError("input has to be vtkImageData") self.name = name # Create transfer mapping scalar value to opacity. opacity_function = vtk.vtkPiecewiseFunction() opacity_function.AddPoint(0, 0.0) opacity_function.AddPoint(127, 0.0) opacity_function.AddPoint(128, 0.2) opacity_function.AddPoint(255, 0.2) # Create transfer mapping scalar value to color. color_function = vtk.vtkColorTransferFunction() color_function.SetColorSpaceToHSV() color_function.AddHSVPoint(0, 0.0, 0.0, 0.0) color_function.AddHSVPoint(127, 0.0, 0.0, 0.0) color_function.AddHSVPoint(128, 0.0, 0.0, 1.0) color_function.AddHSVPoint(255, 0.0, 0.0, 1.0) volume_property = vtk.vtkVolumeProperty() volume_property.SetColor(color_function) volume_property.SetScalarOpacity(opacity_function) volume_property.ShadeOn() volume_property.SetInterpolationTypeToLinear() volume_mapper = vtk.vtkSmartVolumeMapper() volume_mapper.SetInputData(image_data) self.volume = vtk.vtkVolume() self.volume.SetMapper(volume_mapper) self.volume.SetProperty(volume_property)
def TestColorTransferFunction(int , char): # Set up a 2D scene, add an XY chart to it view = vtk.vtkContextView() view.GetRenderer().SetBackground(1.0, 1.0, 1.0) view.GetRenderWindow().SetSize(400, 300) chart = vtk.vtkChartXY() chart.SetTitle('Chart') view.GetScene().AddItem(chart) colorTransferFunction = vtk.vtkColorTransferFunction() colorTransferFunction.AddHSVSegment(50.,0.,1.,1.,85.,0.3333,1.,1.) colorTransferFunction.AddHSVSegment(85.,0.3333,1.,1.,170.,0.6666,1.,1.) colorTransferFunction.AddHSVSegment(170.,0.6666,1.,1.,200.,0.,1.,1.) colorTransferFunction.Build() colorTransferItem = vtk.vtkColorTransferFunctionItem() colorTransferItem.SetColorTransferFunction(colorTransferFunction) chart.AddPlot(colorTransferItem) controlPointsItem = vtk.vtkColorTransferControlPointsItem() controlPointsItem.SetColorTransferFunction(colorTransferFunction) controlPointsItem.SetUserBounds(0., 255., 0., 1.) chart.AddPlot(controlPointsItem) # Finally render the scene and compare the image to a reference image view.GetRenderWindow().SetMultiSamples(1) if view.GetContext().GetDevice().IsA( "vtkOpenGLContextDevice2D") : view.GetInteractor().Initialize() view.GetInteractor().Start() else: print 'GL version 2 or higher is required.' return EXIT_SUCCESS
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 Create8bColorTable(self, scale): if self.color_transfer: color_transfer = self.color_transfer else: color_transfer = vtk.vtkColorTransferFunction() color_transfer.RemoveAllPoints() color_preset = self.config['CLUT'] if color_preset != "No CLUT": p = plistlib.readPlist( os.path.join(const.RAYCASTING_PRESETS_DIRECTORY, 'color_list', color_preset + '.plist')) r = p['Red'] g = p['Green'] b = p['Blue'] colors = zip(r,g,b) else: # Grayscale from black to white colors = [(i, i, i) for i in xrange(256)] ww = self.config['ww'] wl = self.TranslateScale(scale, self.config['wl']) init = wl - ww/2.0 inc = ww / (len(colors) - 1.0) for n,rgb in enumerate(colors): color_transfer.AddRGBPoint(init + n * inc, *[i/255.0 for i in rgb]) self.color_transfer = color_transfer
def testGetRangeDoubleStarArg(self): cmap = vtk.vtkColorTransferFunction() localRange = [-1, -1] cmap.GetRange(localRange) self.assertEqual(localRange[0], 0.0) self.assertEqual(localRange[1], 0.0)
def volumeRender(img, tf=[],spacing=[1.0,1.0,1.0]): importer = numpy2VTK(img,spacing) # Transfer Functions opacity_tf = vtk.vtkPiecewiseFunction() color_tf = vtk.vtkColorTransferFunction() if len(tf) == 0: tf.append([img.min(),0,0,0,0]) tf.append([img.max(),1,1,1,1]) for p in tf: color_tf.AddRGBPoint(p[0], p[1], p[2], p[3]) opacity_tf.AddPoint(p[0], p[4]) volMapper = vtk.vtkGPUVolumeRayCastMapper() volMapper.SetInputConnection(importer.GetOutputPort()) # The property describes how the data will look volProperty = vtk.vtkVolumeProperty() volProperty.SetColor(color_tf) volProperty.SetScalarOpacity(opacity_tf) volProperty.ShadeOn() volProperty.SetInterpolationTypeToLinear() vol = vtk.vtkVolume() vol.SetMapper(volMapper) vol.SetProperty(volProperty) return [vol]
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 _setupColorFunction(self, minV, maxV): # Create a color transfer function to be used for both the balls and arrows. self._colorTransferFunction = vtk.vtkColorTransferFunction() self._colorTransferFunction.AddRGBPoint(minV, 1.0, 0.0, 0.0) self._colorTransferFunction.AddRGBPoint(0.5*(minV + maxV), 0.0, 1.0, 0.0) self._colorTransferFunction.AddRGBPoint(maxV, 0.0, 0.0, 1.0)
def GetDefaultColorMap(dataRange): colorMap = vtk.vtkColorTransferFunction() colorMap.SetColorSpaceToLab() colorMap.AddRGBPoint(dataRange[0], 0.865, 0.865, 0.865) colorMap.AddRGBPoint(dataRange[1], 0.706, 0.016, 0.150) colorMap.Build() return colorMap
def _create_pipeline(self): # setup our pipeline self._otf = vtk.vtkPiecewiseFunction() self._ctf = vtk.vtkColorTransferFunction() self._volume_property = vtk.vtkVolumeProperty() self._volume_property.SetScalarOpacity(self._otf) self._volume_property.SetColor(self._ctf) self._volume_property.ShadeOn() self._volume_property.SetAmbient(0.1) self._volume_property.SetDiffuse(0.7) self._volume_property.SetSpecular(0.2) self._volume_property.SetSpecularPower(10) self._volume_raycast_function = vtk.vtkVolumeRayCastMIPFunction() self._volume_mapper = vtk.vtkVolumeRayCastMapper() # can also used FixedPoint, but then we have to use: # SetBlendModeToMaximumIntensity() and not SetVolumeRayCastFunction #self._volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper() self._volume_mapper.SetVolumeRayCastFunction( self._volume_raycast_function) module_utils.setup_vtk_object_progress(self, self._volume_mapper, 'Preparing render.') self._volume = vtk.vtkVolume() self._volume.SetProperty(self._volume_property) self._volume.SetMapper(self._volume_mapper)
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 execute(self, inputs, update = 0, last = 0): """ Execute the filter with given inputs and return the output """ if not lib.ProcessingFilter.ProcessingFilter.execute(self, inputs): return None image = self.getInput(1) min,max = self.dataUnit.getSourceDataUnits()[0].getScalarRange() self.eventDesc="Thresholding image" if not self.parameters["Demonstrate"]: if self.origCtf: self.dataUnit.getSettings().set("ColorTransferFunction", self.origCtf) if self.gui: self.gui.histograms[0].setReplacementCTF(None) self.gui.histograms[0].updatePreview(renew = 1) self.vtkfilter.SetInput(image) self.vtkfilter.ThresholdBetween(self.parameters["LowerThreshold"],self.parameters["UpperThreshold"]) self.vtkfilter.SetReplaceIn(self.parameters["ReplaceIn"]) if self.parameters["ReplaceIn"]: self.vtkfilter.SetInValue(self.parameters["ReplaceInValue"]) self.vtkfilter.SetReplaceOut(self.parameters["ReplaceOut"]) if self.parameters["ReplaceOut"]: self.vtkfilter.SetOutValue(self.parameters["ReplaceOutValue"]) #if update: self.vtkfilter.Update() return self.vtkfilter.GetOutput() else: lower = self.parameters["LowerThreshold"] upper = self.parameters["UpperThreshold"] origCtf = self.dataUnit.getSourceDataUnits()[0].getColorTransferFunction() self.origCtf = origCtf ctf = vtk.vtkColorTransferFunction() ctf.AddRGBPoint(min, 0, 0, 0.0) if lower >= min + 1: ctf.AddRGBPoint(lower - 1, 0, 0, 1.0) ctf.AddRGBPoint(lower, 0, 0, 0) val = [0, 0, 0] origCtf.GetColor(max, val) r, g, b = val ctf.AddRGBPoint(upper, r, g, b) if upper <= max + 1: ctf.AddRGBPoint(upper + 1, 0, 0, 0) ctf.AddRGBPoint(max, 1.0, 0, 0) self.dataUnit.getSettings().set("ColorTransferFunction", ctf) if self.gui: self.gui.histograms[0].setReplacementCTF(ctf) self.gui.histograms[0].updatePreview(renew = 1) self.gui.histograms[0].Refresh() return image
def testGetRangeTwoDoubleStarArg(self): cmap = vtk.vtkColorTransferFunction() localMin = vtk.mutable(-1) localMax = vtk.mutable(-1) cmap.GetRange(localMin, localMax) self.assertEqual(localMin, 0.0) self.assertEqual(localMax, 0.0)
def rgb_fn(zipped_data): fn = vtk.vtkColorTransferFunction() for point, color in zipped_data: # Ensure float and not hexidecimal if any(type(x) is int or x > 1 for x in color): color = [float(i) / float(255) for i in color] fn.AddRGBPoint(point, *color) return fn
def UpdateColorBar(colorbar,mapper): if mapper.GetScalarMode() == 1: srange = mapper.GetInput().GetPointData().GetScalars().GetRange() else: srange = mapper.GetInput().GetCellData().GetScalars().GetRange() tc = vtk.vtkColorTransferFunction(); tc.SetColorSpaceToDiverging() tc.AddRGBPoint(srange[0],0,0,1); tc.AddRGBPoint(sum(srange)/len(srange),1,1,1) tc.AddRGBPoint(srange[1],1,0,0); mapper.SetLookupTable( tc ); colorbar.SetLookupTable( tc ); colorbar.SetNumberOfLabels(3); colorbar.SetLabelFormat('%3.3e');
def _on_new_image_attrib(self, attrib): ((w, h, num_channels), dtype) = attrib if self._image_handler.is_depth_image(): assert num_channels == 1, num_channels assert dtype in (np.uint16, np.float32), dtype # TODO(eric.cousineau): Delegate to outside of `ImageWidget`? # This is depth-image specific. # For now, just set arbitrary values. depth_range = self._get_depth_range() lower_color = (1, 1, 1) # White upper_color = (0, 0, 0) # Black nan_color = (0.5, 0.5, 1) # Light blue - No return. inf_color = (0.5, 0, 0.) # Dark red - Too far / too close. # Use `vtkColorTransferFunction` as it provides a more intuitive # interpolating interface for me (Eric) than `vtkLookupTable`, # since it permits direct specification of RGB values. coloring = vtk.vtkColorTransferFunction() coloring.AddRGBPoint(depth_range[0], *lower_color) coloring.AddRGBPoint(depth_range[1], *upper_color) coloring.SetNanColor(*nan_color) # @note `coloring.SetAboveRangeColor` doesn't seem to work? coloring.AddRGBPoint(depth_range[1] + 10000, *inf_color) coloring.SetClamping(True) coloring.SetScaleToLinear() self._depth_mapper = vtk.vtkImageMapToColors() self._depth_mapper.SetLookupTable(coloring) vtk_SetInputData(self._depth_mapper, self._image) vtk_SetInputData(self._image_actor, self._depth_mapper.GetOutput()) self._image_actor.GetMapper().SetInputConnection( self._depth_mapper.GetOutputPort()) else: # Direct connection. self._depth_mapper = None vtk_SetInputData(self._image_actor, self._image) # Must render first. self._view.render() # Fit image to view. # TODO(eric.cousineau): No idea why this is needed; it worked for # VTK 5, but no longer for VTK 6+? camera = self._view.camera() camera.ParallelProjectionOn() camera.SetFocalPoint(0, 0, 0) camera.SetPosition(0, 0, -1) camera.SetViewUp(0, -1, 0) self._view.resetCamera() image_height, image_width = get_vtk_image_shape(self._image)[:2] view_width, view_height = self._view.renderWindow().GetSize() aspect_ratio = float(view_width) / view_height parallel_scale = max(image_width / aspect_ratio, image_height) / 2.0 camera.SetParallelScale(parallel_scale)
def get_vtk_transfer_functions(self): of = vtk.vtkPiecewiseFunction() cf = vtk.vtkColorTransferFunction() for pt in self._pts: (scalar, opacity, color) = pt # Map scalar to tf range s = self._min_range + (self._max_range - self._min_range) * scalar of.AddPoint(s, opacity) cf.AddRGBPoint(s, color[0], color[1], color[2]) return (of,cf)
def getColorTransferFunction(self): """ Returns the ctf of the dataset series which this datasource operates on """ if not self.ctf: self.ctf = vtk.vtkColorTransferFunction() minval,maxval = self.getScalarRange() self.ctf.AddRGBPoint(minval, 0, 0, 0) self.ctf.AddRGBPoint(maxval, 0, 1, 0) return self.ctf
def watershedPalette(ctfLowerBound, ctfUpperBound, ignoreColors=2, filename=""): """ Returns a randomly created CTF. """ try: ctf = vtk.vtkColorTransferFunction() if filename: loadLUT(filename, ctf) except: ctf = vtk.vtkColorTransferFunction() ctfFileSize = ctf.GetSize() if ctfFileSize > 0: for i in range(0, ignoreColors): color = ctf.GetColor(i) ctf.AddRGBPoint(ctf.GetSize(), color[0], color[1], color[2]) for i in range(0, ignoreColors): ctf.AddRGBPoint(i, 0, 0, 0) if ctfLowerBound < 1: ctfLowerBound = 1 if ctfFileSize > 0 and ctf.GetSize() > ctfLowerBound: ctfLowerBound = ctf.GetSize() handle = vtkbxd.vtkHandleColorTransferFunction() handle.CreateRandomColorTransferFunction(ctf, ctfLowerBound, ctfUpperBound, 1.5) # for i in range(int(ctfLowerBound), int(ctfUpperBound)): # red = 0 # green = 0 # blue = 0 # while red + green + blue < 1.5: # red = random.random() # green = random.random() # blue = random.random() # ctf.AddRGBPoint(float(i), float(red), float(green), float(blue)) if ctf.GetSize() > ctfUpperBound: for i in xrange(ctfUpperBound, ctf.GetSize() - 1): ctf.RemovePoint(i) return ctf
def clearInfo(self): """ Clears the information from the info widget. """ self.htmlpage.SetPage("") #self.taskName.SetLabel("") ctf = vtk.vtkColorTransferFunction() ctf.AddRGBPoint(0,0,0,0) ctf.AddRGBPoint(255,1,1,1) self.colorBtn.setColorTransferFunction(ctf)
def __init__(self, reader): logging.info("begin Init ViewerVR") self._reader = reader #init VolumeRayCastMapper self._volumeMapper = vtk.vtkGPUVolumeRayCastMapper() self._volumeMapper.SetSampleDistance(self._volumeMapper.GetSampleDistance()/2) self._volumeMapper.SetBlendModeToComposite() self._volumeMapper.SetInputConnection(reader.GetOutputPort()) self._volumeColor = vtk.vtkColorTransferFunction() self._volumeScalarOpacity = vtk.vtkPiecewiseFunction() self._volumeGradientOpacity = vtk.vtkPiecewiseFunction() self._volumeProperty = vtk.vtkVolumeProperty() self._volume = vtk.vtkVolume() self._render = vtk.vtkRenderer() logging.info("End Init ViewerVR")
def GetPropertyActor(surf, property_name): #display property on surface point_data = vtk.vtkDoubleArray() point_data.SetNumberOfComponents(1) with open(property_name) as property_file: for line in property_file: point_val = float(line[:-1]) point_data.InsertNextTuple([point_val]) surf.GetPointData().SetScalars(point_data) surf_actor = GetActor(surf) surf_actor.GetProperty().LightingOff() surf_actor.GetProperty().ShadingOff() surf_actor.GetProperty().SetInterpolationToFlat() surfMapper = surf_actor.GetMapper() surfMapper.SetUseLookupTableScalarRange(True) #build lookup table number_of_colors = 512 low_range = 0 high_range = 1 lut = vtk.vtkLookupTable() lut.SetTableRange(low_range, high_range) lut.SetNumberOfColors(number_of_colors) #Color transfer function ctransfer = vtk.vtkColorTransferFunction() ctransfer.AddRGBPoint(0.0, 1.0, 1.0, 0.0) # Yellow ctransfer.AddRGBPoint(0.5, 1.0, 0.0, 0.0) # Red #Calculated new colors for LUT via color transfer function for i in range(number_of_colors): new_colour = ctransfer.GetColor( (i * ((high_range - low_range) / number_of_colors))) lut.SetTableValue(i, *new_colour) lut.Build() surfMapper.SetLookupTable(lut) # return surfActor return surfMapper
def _set_volume_range(volume, ctable, alpha, scalar_bar, rng): import vtk from vtk.util.numpy_support import numpy_to_vtk color_tf = vtk.vtkColorTransferFunction() opacity_tf = vtk.vtkPiecewiseFunction() for loc, color in zip(np.linspace(*rng, num=len(ctable)), ctable): color_tf.AddRGBPoint(loc, *color[:-1]) opacity_tf.AddPoint(loc, color[-1] * alpha / 255. / (len(ctable) - 1)) color_tf.ClampingOn() opacity_tf.ClampingOn() volume.GetProperty().SetColor(color_tf) volume.GetProperty().SetScalarOpacity(opacity_tf) if scalar_bar is not None: lut = vtk.vtkLookupTable() lut.SetRange(*rng) lut.SetTable(numpy_to_vtk(ctable)) scalar_bar.SetLookupTable(lut)
def __xml(self): """ Builds VTK table using Paraview XML colormap files. """ # Extract data name = self.getOption('cmap') data = self._data[name] # Extract the table data xmin = float('inf') xmax = float('-inf') values = [] points = [] for child in data: a = child.attrib if child.tag == 'Point': x = float(a['x']) r = float(a['r']) g = float(a['g']) b = float(a['b']) xmin = min(xmin, x) xmax = max(xmax, x) values.append(x) points.append([r, g, b]) # Flip the data if desired if self.getOption('cmap_reverse'): points = list(reversed(points)) # Build function function = vtk.vtkColorTransferFunction() function.SetRange(xmin, xmax) for i, v in enumerate(values): function.AddRGBPoint(v, *points[i]) function.Build() # The number of points n = self.getOption('cmap_num_colors') cm_points = np.linspace(xmin, xmax, n) # Build the lookup table table = vtk.vtkLookupTable() table.SetNumberOfTableValues(n) for i in range(n): table.SetTableValue(i, *function.GetColor(cm_points[i])) return table
def buildLookupTable(self): self.colorFunction = vtk.vtkColorTransferFunction() self.colorFunction.SetColorSpaceToHSV() self.colorFunction.HSVWrapOff() drange = [10., 20.] self.colorFunction.AddRGBPoint(drange[0], 0.0, 0.0, 1.0) self.colorFunction.AddRGBPoint(drange[1], 1.0, 0.0, 0.0) self.scalarBar.SetTitle("Title1") self.scalarBar.SetLookupTable(self.colorFunction) self.scalarBar.SetOrientationToVertical() self.scalarBar.SetHeight(0.9) self.scalarBar.SetWidth(0.20) # the width is set first # after the width is set, this is adjusted self.scalarBar.SetPosition(0.77, 0.1) #self.scalarBar.SetPosition2(0.1, 0.3) #print self.scalarBar.GetPosition() propTitle = vtk.vtkTextProperty() propTitle.SetFontFamilyToArial() #propTitle.ItalicOff() propTitle.BoldOn() propTitle.ShadowOn() propLabel = vtk.vtkTextProperty() propLabel.BoldOff() propLabel.ShadowOn() scalar_range = self.grid.GetScalarRange() self.aQuadMapper.SetScalarRange(scalar_range) self.aQuadMapper.SetLookupTable(self.colorFunction) #self.scalarBar.SetTitleTextProperty(propTitle); #self.scalarBar.SetLabelTextProperty(propLabel); self.scalarBar.SetLabelFormat("%i") # allows 0-1 to be nice number when ranging values (gotta pick something) self.scalarBar.SetNumberOfLabels(11) self.scalarBar.SetMaximumNumberOfColors(11) #self.scalarBar.VisibilityOff() # first load -> scalar bar off #self.scalarBar.ShadowOn() #self.scalarBar.RepositionableOn() self.rend.AddActor(self.scalarBar)
def createColorLookupTable(self, min_value, max_value): colorTransferFunctionbl = vtk.vtkColorTransferFunction() colorTransferFunctionbl.SetColorSpaceToHSV() colorTransferFunctionbl.AddHSVPoint(min_value, \ self.HSV_color_min_value[0], self.HSV_color_min_value[1], \ self.HSV_color_min_value[2]) colorTransferFunctionbl.AddHSVPoint(max_value, \ self.HSV_color_max_value[0], self.HSV_color_max_value[1], \ self.HSV_color_max_value[2]) # Activate above / below range color, in default # below range = yellow, above range = red #print(colorTransferFunctionbl.GetAboveRangeColor()) #print(colorTransferFunctionbl.GetBelowRangeColor()) #colorTransferFunctionbl.UseBelowRangeColorOn () #colorTransferFunctionbl.UseAboveRangeColorOn () return colorTransferFunctionbl
def __init__(self, parent): super(NeuroGLWidget, self).__init__(parent) xmins = [0, .5] xmaxs = [0.5, 1] ymins = [0, 0] ymaxs = [1, 1] self.ren = [] self.iren = self.GetRenderWindow().GetInteractor() self.volume = [] self.volume.append(vtk.vtkVolume()) self.volume.append(vtk.vtkVolume()) for i in range(2): self.ren.append(vtk.vtkRenderer()) self.GetRenderWindow().AddRenderer(self.ren[i]) self.ren[i].SetViewport(xmins[i], ymins[i], xmaxs[i], ymaxs[i]) self.ren[i].SetBackground(i / 10, i / 10, i / 10) self.ren[i].GetActiveCamera().ParallelProjectionOn() self.style = InteractorStyle.MyInteractorStyle() self.style.AutoAdjustCameraClippingRangeOn() self.style.SetInteractor(self.iren) self.style.SetRenderers(self.ren) self.iren.SetInteractorStyle(self.style) self.transform = [] self.transform.append(vtk.vtkTransform()) self.transform[0].Identity() self.transform.append(vtk.vtkTransform()) self.transform[1].Identity() self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.customContextMenuRequested.connect(self.onContextMenu) self.volumeRes = [] self.volumeRes.append([1, 1, 1]) self.volumeRes.append([1, 1, 1]) self.picker = vtk.vtkCellPicker() self.picker.SetTolerance(0.005) self.importData = [vtk.vtkImageData() for i in range(2)] self.colorFunc = [] self.planeWidgetZ = [] self.sliderRep = [] self.sliderWidget = [] for i in range(2): self.colorFunc.append(vtk.vtkColorTransferFunction()) self.planeWidgetZ.append(vtkImagePlaneWidget()) self.planeWidgetZ[i].SetSliceIndex(0) self.planeMode = False self.CreateSliderWidget()
def setupImageProcessingPipeline(self): # Caster self.caster = vtk.vtkImageShiftScale() self.caster.SetOutputScalarTypeToUnsignedChar() self.caster.ClampOverflowOn() # Setup composite ray cast function self.rayCastFunction = vtk.vtkVolumeRayCastCompositeFunction() # Add to mapper self.volumeMapper = vtk.vtkVolumeRayCastMapper() self.volumeMapper.SetInputConnection(self.caster.GetOutputPort()) self.volumeMapper.SetVolumeRayCastFunction(self.rayCastFunction) # The color transfer function maps voxel intensities to colors. self.volumeColor = vtk.vtkColorTransferFunction() self.volumeColor.AddRGBPoint(0, 0.0, 0.0, 0.0) self.volumeColor.AddRGBPoint(255, 1.0, 1.0, 1.0) # The opacity transfer function (tissue opacity) self.volumeScalarOpacity = vtk.vtkPiecewiseFunction() self.volumeScalarOpacity.AddPoint(0, 0.00) self.volumeScalarOpacity.AddPoint(255, 1) # The gradient opacity function (decrease opacity in flat regions) self.volumeGradientOpacity = vtk.vtkPiecewiseFunction() self.volumeGradientOpacity.AddPoint(0, 0.0) self.volumeGradientOpacity.AddPoint(90, 0.5) self.volumeGradientOpacity.AddPoint(100, 1.0) # Property self.volumeProperty = vtk.vtkVolumeProperty() self.volumeProperty.SetColor(self.volumeColor) self.volumeProperty.SetScalarOpacity(self.volumeScalarOpacity) self.volumeProperty.SetGradientOpacity(self.volumeGradientOpacity) self.volumeProperty.SetInterpolationTypeToLinear() self.volumeProperty.ShadeOn() self.volumeProperty.SetAmbient(1) self.volumeProperty.SetDiffuse(1) self.volumeProperty.SetSpecular(0.2) # Prop self.volume = vtk.vtkVolume() self.volume.SetMapper(self.volumeMapper) self.volume.SetProperty(self.volumeProperty)
def load_transfer_function(filename): tree = ET.parse(filename) root = tree.getroot() TransFuncIntensity = root.find("TransFuncIntensity") domain = TransFuncIntensity.find("domain") domain_x = domain.get("x") domain_y = domain.get("y") threshold = TransFuncIntensity.find("threshold") threshold_x = threshold.get("x") threshold_y = threshold.get("y") list_intensity = [] list_split = [] list_r = [] list_g = [] list_b = [] list_a = [] for key in root.iter('key'): colour = key.find("colorL") list_intensity.append(key.find("intensity").get("value")) list_split.append(key.find("split").get("value")) list_r.append(colour.get("r")) list_g.append(colour.get("g")) list_b.append(colour.get("b")) list_a.append(colour.get("a")) # Create transfer mapping scalar value to opacity opacityTransferFunction = vtk.vtkPiecewiseFunction() # Create transfer mapping scalar value to color colorTransferFunction = vtk.vtkColorTransferFunction() max_intensity = 255 for i in range(len(list_intensity)): intensity = float(list_intensity[i]) * max_intensity r = float(list_r[i]) / max_intensity g = float(list_g[i]) / max_intensity b = float(list_b[i]) / max_intensity a = float(list_a[i]) / max_intensity opacityTransferFunction.AddPoint(intensity, a) colorTransferFunction.AddRGBPoint(intensity, r, g, b) return opacityTransferFunction, colorTransferFunction
def color(self, col): """Assign a color or a set of colors to a volume along the range of the scalar value. A single constant color can also be assigned. Any matplotlib color map name is also accepted, e.g. ``volume.color('jet')``. E.g.: say that your voxel scalar runs from -3 to 6, and you want -3 to show red and 1.5 violet and 6 green, then just set: ``volume.color(['red', 'violet', 'green'])`` """ smin, smax = self._imagedata.GetScalarRange() volumeProperty = self.GetProperty() ctf = vtk.vtkColorTransferFunction() self._color = col if utils.isSequence(col): for i, ci in enumerate(col): r, g, b = colors.getColor(ci) xalpha = smin + (smax - smin) * i / (len(col) - 1) ctf.AddRGBPoint(xalpha, r, g, b) #colors.printc('\tcolor at', round(xalpha, 1), # '\tset to', colors.getColorName((r, g, b)), c='b', bold=0) elif isinstance(col, str): if col in colors.colors.keys() or col in colors.color_nicks.keys(): r, g, b = colors.getColor(col) ctf.AddRGBPoint(smin, r, g, b) # constant color ctf.AddRGBPoint(smax, r, g, b) elif colors._mapscales: for x in np.linspace(smin, smax, num=64, endpoint=True): r, g, b = colors.colorMap(x, name=col, vmin=smin, vmax=smax) ctf.AddRGBPoint(x, r, g, b) elif isinstance(col, int): r, g, b = colors.getColor(col) ctf.AddRGBPoint(smin, r, g, b) # constant color ctf.AddRGBPoint(smax, r, g, b) else: colors.printc("volume.color(): unknown input type:", col, c=1) volumeProperty.SetColor(ctf) volumeProperty.SetInterpolationTypeToLinear() #volumeProperty.SetInterpolationTypeToNearest() return self
def createColorMap(self, vMin, vMax): ctf = vtk.vtkColorTransferFunction() ctf.AddRGBPoint(vMin, 0, 0, 0) ctf.AddRGBPoint(vMin * 0.9, 1, 0, 0) ctf.AddRGBPoint(vMin * 0.7, 1, 0.5, 0) ctf.AddRGBPoint(vMin * 0.4, 1, 1, 0) ctf.AddRGBPoint(0, 1, 1, 1) ctf.AddRGBPoint(vMax * 0.4, 1, 1, 0) ctf.AddRGBPoint(vMax * 0.7, 1, 0.5, 0) ctf.AddRGBPoint(vMax * 0.9, 1, 0, 0) ctf.AddRGBPoint(vMax, 0, 0, 0) colorMap = slicer.vtkMRMLProceduralColorNode() colorMap.SetName(self.filename + ' (' + self.index + ')') colorMap.SetAndObserveColorTransferFunction(ctf) slicer.mrmlScene.AddNode(colorMap) return colorMap
def phaseLUT(): """ define a mangenta-white-cyan color lookup table """ lut = vtk.vtkLookupTable() nc = 256 ctf = vtk.vtkColorTransferFunction() # ctf.SetColorSpaceToDiverging() ctf.AddRGBPoint(0.0, 0.5, 0.0, 0.5) ctf.AddRGBPoint(0.5, 1.0, 1.0, 1.0) ctf.AddRGBPoint(1.0, 0.0, 0.5, 0.5) lut.SetNumberOfTableValues(nc) lut.Build() for i in range(0, nc): rgb = list(ctf.GetColor(float(i) / nc)) rgb.append(1.0) lut.SetTableValue(i, *rgb) return lut
def CreateRangeFunctions(imageData, color=None): """ :type imageData: vktImageData :type color: array of length 3 (r, g, b) :rtype: vtkColorTransferFunction, vtkPiecewiseFunction """ col = [1, 1, 1] if color is not None: col = color minimum, maximum = imageData.GetScalarRange() colorFunction = vtkColorTransferFunction() colorFunction.AddRGBSegment(minimum, 0, 0, 0, maximum, col[0], col[1], col[2]) opacityFunction = vtkPiecewiseFunction() opacityFunction.AddSegment(minimum, 0.0, maximum, 1.0) return colorFunction, opacityFunction
def render_cloud(self): self.ren.RemoveVolume(self.cloud_volume) if not self.config["CLOUD"][0]: return data_path = compose_file_name(self.base_dir, "/CLOUD", self.data_folders["CLOUD"], self.time_step) reader = vtk.vtkXMLImageDataReader() reader.SetFileName(data_path) reader.Update() spacing = reader.GetOutput().GetSpacing() reader.GetOutput().SetSpacing(spacing[0], spacing[1], spacing[2] * 30) myrange = reader.GetOutput().GetPointData().GetScalars().GetRange() opacityTransferFunction = vtk.vtkPiecewiseFunction() opacityTransferFunction.AddPoint(myrange[0], 0.0) opacityTransferFunction.AddPoint(myrange[1], 0.1) color = vtk.vtkColorTransferFunction() # Blue color.AddRGBPoint(myrange[0], 0.8, 0.8, 0.8) color.AddRGBPoint((myrange[0] + myrange[1]) / 2, 1., 1., 1) color.AddRGBPoint(myrange[1], 0.8, 0.8, 0.8) volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(color) volumeProperty.SetScalarOpacity(opacityTransferFunction) volumeProperty.SetInterpolationTypeToLinear() volumeProperty.ShadeOff() volumeMapper = vtk.vtkSmartVolumeMapper() volumeMapper.SetBlendModeToComposite() volumeMapper.SetAutoAdjustSampleDistances(0) volumeMapper.SetSampleDistance(0.5) 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) self.cloud_volume = volume self.ren.AddVolume(volume)
def makeVolumeRenderingPipeline(in_volume): dataImporter = vtk.vtkImageImport() if in_volume.dtype == numpy.uint8: dataImporter.SetDataScalarTypeToUnsignedChar() elif in_volume.dtype == numpy.uint16: dataImporter.SetDataScalarTypeToUnsignedShort() elif in_volume.dtype == numpy.int32: dataImporter.SetDataScalarTypeToInt() elif in_volume.dtype == numpy.int16: dataImporter.SetDataScalarTypeToShort() else: raise RuntimeError("unknown data type %r of volume" % (in_volume.dtype, )) dataImporter.SetImportVoidPointer(in_volume, len(in_volume)) dataImporter.SetNumberOfScalarComponents(1) extent = [ 0, in_volume.shape[2] - 1, 0, in_volume.shape[1] - 1, 0, in_volume.shape[0] - 1 ] dataImporter.SetDataExtent(*extent) dataImporter.SetWholeExtent(*extent) alphaChannelFunc = vtk.vtkPiecewiseFunction() alphaChannelFunc.AddPoint(0, 0.0) for i in range(1, NOBJECTS): alphaChannelFunc.AddPoint(i, 1.0) colorFunc = vtk.vtkColorTransferFunction() volumeMapper = vtk.vtkSmartVolumeMapper() volumeMapper.SetInputConnection(dataImporter.GetOutputPort()) volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(colorFunc) volumeProperty.SetScalarOpacity(alphaChannelFunc) volumeProperty.ShadeOn() volume = vtk.vtkVolume() volume.SetMapper(volumeMapper) volume.SetProperty(volumeProperty) return dataImporter, colorFunc, volume, volumeMapper
def __init__(self, parent): super(NeuroGLWidget, self).__init__(parent) self.iren = self.GetRenderWindow().GetInteractor() self.volume = vtk.vtkVolume() self.GetRenderWindow().SetNumberOfLayers(2) self.ren = [] for i in range(2): self.ren.append(vtk.vtkRenderer()) self.ren[i].SetLayer(i) self.GetRenderWindow().AddRenderer(self.ren[i]) #self.ren[i].GetActiveCamera().ParallelProjectionOn() self.ren[1].SetActiveCamera(self.ren[0].GetActiveCamera()) self.ren[0].GetActiveCamera().ParallelProjectionOn() self.style = InteractorStyle.MyInteractorStyle() self.style.SetInteractor(self.iren) self.style.SetRenderers(self.ren) #self.style.SetRendererCollection(self.GetRenderWindow().GetRenderers()) self.style.AutoAdjustCameraClippingRangeOff() self.iren.SetInteractorStyle(self.style) self.style.SetGLWidgetHandle(self) self.transform = vtk.vtkTransform() self.transform.Identity() self.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.customContextMenuRequested.connect(self.onContextMenu) self.volumeSize = [0, 0, 0] #d,h,w self.volumeRes = [1, 1, 1] #d,h,w self.outLine = vtk.vtkActor() self.axes = vtk.vtkAxesActor() self.marker = vtk.vtkOrientationMarkerWidget() self.marker.SetOutlineColor(1, 1, 1) self.marker.SetOrientationMarker(self.axes) self.marker.SetInteractor(self.GetRenderWindow().GetInteractor()) self.marker.SetViewport(0, 0, 0.1, 0.1) self.marker.SetEnabled(True) self.marker.InteractiveOn() self.picker = vtk.vtkCellPicker() self.picker.SetTolerance(0.005) self.importData = vtk.vtkImageData() self.colorFunc = vtk.vtkColorTransferFunction() self.planeWidgetZ = vtkImagePlaneWidget() self.planeWidgetZ.SetSliceIndex(0) self.planeMode = False self.CreateSliderWidget()
def update_property(self): preset = self._preset color = vtk.vtkColorTransferFunction() for (v, r, g, b, mid, sharp) in preset.color_transfer: color.AddRGBPoint(v, r, g, b, mid, sharp) scalar_opacity = vtk.vtkPiecewiseFunction() for (v, a, mid, sharp) in preset.scalar_opacity: scalar_opacity.AddPoint(v, a, mid, sharp) gradient_opacity = None if preset.gradient_opacity is not None: gradient_opacity = vtk.vtkPiecewiseFunction() for (v, a, mid, sharp) in preset.gradient_opacity: gradient_opacity.AddPoint(v, a, mid, sharp) prop = vtk.vtkVolumeProperty() prop.SetIndependentComponents(True) prop.SetColor(color) prop.SetScalarOpacity(scalar_opacity) if gradient_opacity is not None: prop.SetGradientOpacity(gradient_opacity) if preset.interpolation: prop.SetInterpolationTypeToLinear() else: prop.SetInterpolationTypeToNearest() if preset.shade: prop.ShadeOn() else: prop.ShadeOff() prop.SetAmbient(preset.ambient) prop.SetDiffuse(preset.diffuse) prop.SetSpecular(preset.specular) prop.SetSpecularPower(preset.specular_power) unit_distance = min(self._volume.GetSpacing()) prop.SetScalarOpacityUnitDistance(unit_distance) self._property = prop
def AdaptColor(self, minVal=None, maxVal=None): import vtk if minVal == None or maxVal == None: m, M = self.GetRange() if minVal == None: minVal = m if maxVal == None: maxVal = M colorTransferFunction = vtk.vtkColorTransferFunction() colorTransferFunction.AddHSVPoint(minVal, 0.0, 0.0, 0.0) colorTransferFunction.AddHSVPoint((maxVal - minVal) * 0.25, 0.66, 1.0, 1.0) colorTransferFunction.AddHSVPoint((maxVal - minVal) * 0.5, 0.44, 1.0, 1.0) colorTransferFunction.AddHSVPoint((maxVal - minVal) * 0.75, 0.22, 1.0, 1.0) colorTransferFunction.AddHSVPoint(maxVal, 0.0, 1.0, 1.0) self.__volumeProperty__.SetColor(colorTransferFunction) self.Render()
def updateTransferFunction(self): if self.histogramWidget: self.histogramWidget.transferFunction.updateTransferFunction() self.colorFunction = self.histogramWidget.transferFunction.colorFunction self.opacityFunction = self.histogramWidget.transferFunction.opacityFunction else: # Transfer functions and properties self.colorFunction = vtkColorTransferFunction() self.colorFunction.AddRGBPoint(self.minimum, 0, 0, 0) self.colorFunction.AddRGBPoint(self.maximum, 0, 0, 0) self.opacityFunction = vtkPiecewiseFunction() self.opacityFunction.AddPoint(self.minimum, 0) self.opacityFunction.AddPoint(self.maximum, 0) self.volProp.SetColor(self.colorFunction) self.volProp.SetScalarOpacity(self.opacityFunction) self.updatedTransferFunction.emit()
def MakeLUT(colorScheme, lut): # See: [Diverging Color Maps for Scientific Visualization] # (http:#www.kennethmoreland.com/color-maps/) nc = 256 ctf = vtk.vtkColorTransferFunction() if colorScheme == 1: # Green to purple diverging. ctf.SetColorSpaceToDiverging() ctf.AddRGBPoint(0.0, 0.085, 0.532, 0.201) ctf.AddRGBPoint(1.0, 0.436, 0.308, 0.631) lut.SetNumberOfTableValues(nc) lut.Build() for i in range(0, nc): rgb = list(ctf.GetColor(float(i) / nc)) rgb.append(1.0) lut.SetTableValue(i, *rgb) elif colorScheme == 2: # Make a lookup table, black in the centre with bright areas # at the beginning and end of the table. # This is from the original code. nc2 = nc / 2.0 lut.SetNumberOfColors(nc) lut.Build() for i in range(0, int(nc2)): # White to black. v = (nc2 - i) / nc2 lut.SetTableValue(i, v, v, v, 1) for i in range(int(nc2), nc): # Black to white. v = (i - nc2) / nc2 lut.SetTableValue(i, v, v, v, 1) else: # Cool to warm diverging. ctf.SetColorSpaceToDiverging() ctf.AddRGBPoint(0.0, 0.230, 0.299, 0.754) ctf.AddRGBPoint(1.0, 0.706, 0.016, 0.150) lut.SetNumberOfTableValues(nc) lut.Build() for i in range(0, nc): rgb = list(ctf.GetColor(float(i) / nc)) rgb.append(1.0) lut.SetTableValue(i, *rgb)
def __init__(self, net_struct): "Initialize with the given VisualisableNetworkStructure." self.network_structure = net_struct self.vtk_units = [None] * len(net_struct.units) self.lut = vtk.vtkColorTransferFunction() self.lut.SetColorSpaceToHSV() self.lut.SetScaleToLinear() # Work with white and with black bg self.lut.AddHSVPoint(0., 1., 0., 0.5) self.lut.AddHSVPoint(1., 1., 1., 1.) self.lut.SetRange(0., 1.) # Build update-ordered representations of network maps self.grids = list() self.grids_lengths = list() for g, l in [ self.represent_map(m) for m in self.network_structure.maps_ids ]: self.grids.append(g) self.grids_lengths.append(l)
def divergent_color_lut(table_size=20, table_range=[0, 1]): ctf = vtk.vtkColorTransferFunction() ctf.SetColorSpaceToDiverging() # Green to tan. ctf.AddRGBPoint(0.0, 0.085, 0.532, 0.201) ctf.AddRGBPoint(0.5, 0.865, 0.865, 0.865) ctf.AddRGBPoint(1.0, 0.677, 0.492, 0.093) lut = vtk.vtkLookupTable() lut.SetNumberOfTableValues(table_size) lut.Build() for i in range(0, table_size): rgb = list(ctf.GetColor(float(i) / table_size)) + [1] lut.SetTableValue(i, rgb) lut.SetTableRange(table_range[0], table_range[1]) return lut
def initWindow(self, path): self.vcolor = [[0, 0.0, 0.0, 0.0], [500, 0.6, 0.5, 0.3], [1000, 0.9, 0.9, 0.3], [1150, 1.0, 1.0, 0.9]] self.vOpacity = [[0, 0], [500, 0.55], [1000, 0.55], [1150, 0.85]] self.gOpacity = [[0, 0.0], [90, 0.8], [100, 1.0]] self.source = vtk.vtkDICOMImageReader() self.source.SetDirectoryName(path) self.source.Update() self.volumcolors = vtk.vtkColorTransferFunction() self.setOpacityColor(self.vcolor) self.volumScalarOpacity = vtk.vtkPiecewiseFunction() self.setOpacityValue(self.vOpacity) self.volumGradientOpacity = vtk.vtkPiecewiseFunction() self.setGradientOpacity(self.gOpacity) self.volumMapper = vtk.vtkGPUVolumeRayCastMapper() self.volumMapper.SetInputConnection(self.source.GetOutputPort()) self.volumeProperty = vtk.vtkVolumeProperty() self.volumeProperty.SetColor(self.volumcolors) self.volumeProperty.SetScalarOpacity(self.volumScalarOpacity) self.volumeProperty.SetGradientOpacity(self.volumGradientOpacity) self.volumeProperty.SetInterpolationTypeToLinear() self.volumeProperty.ShadeOn() self.volumeProperty.SetAmbient(0.4) self.volumeProperty.SetDiffuse(0.6) self.volumeProperty.SetSpecular(0.2) self.volume = vtk.vtkVolume() self.volume.SetMapper(self.volumMapper) self.volume.SetProperty(self.volumeProperty) self.colors = vtk.vtkNamedColors() self.colors.SetColor("BackGroundcolors", [255, 255, 255, 255]) self.ren.SetBackground(self.colors.GetColor3d("BackGroundcolors")) self.ren.AddVolume(self.volume) self.iren.Initialize() pass
def createVolume(image): ''' create volume of image - image must be a typical irm image with gray values comprised between 0 and 255 ''' # Create transfer mapping scalar value to opacity opacityTransferFunction = vtk.vtkPiecewiseFunction() opacityTransferFunction.AddPoint(0, 0.0) opacityTransferFunction.AddPoint(10.0, 0.0) opacityTransferFunction.AddPoint(40.0, 1.0) opacityTransferFunction.AddPoint(60, 1.0) opacityTransferFunction.AddPoint(200, 0.0) opacityTransferFunction.AddPoint(255, 0.0) # Create transfer mapping scalar value to color colorTransferFunction = vtk.vtkColorTransferFunction() colorTransferFunction.AddRGBPoint(0.0, 0.0, 0.0, 0.0) colorTransferFunction.AddRGBPoint(64.0, 1.0, 0.0, 0.0) colorTransferFunction.AddRGBPoint(128.0, 0.0, 0.0, 1.0) colorTransferFunction.AddRGBPoint(192.0, 0.0, 1.0, 0.0) colorTransferFunction.AddRGBPoint(255.0, 0.0, 0.2, 0.0) # The property describes how the data will look volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(colorTransferFunction) volumeProperty.SetScalarOpacity(opacityTransferFunction) volumeProperty.ShadeOn() volumeProperty.SetInterpolationTypeToLinear() volumeProperty.SetDiffuse(0.7) volumeProperty.SetSpecular(0.5) volumeProperty.SetSpecularPower(70.0) # mapper volumeMapper=None if 1: compositeFunction = vtk.vtkVolumeRayCastCompositeFunction() volumeMapper = vtk.vtkVolumeRayCastMapper() volumeMapper.SetVolumeRayCastFunction(compositeFunction) volumeMapper.SetInput(image) else: volumeMapper = vtk.vtkVolumeTextureMapper2D() volumeMapper.SetInput(image) # volume volume = vtk.vtkVolume() volume.SetMapper(volumeMapper) volume.SetProperty(volumeProperty) return volume, volumeMapper
def _create_tfs(self): otf = vtk.vtkPiecewiseFunction() ctf = vtk.vtkColorTransferFunction() otf.RemoveAllPoints() t = self._config.threshold p1 = t - t / 10.0 p2 = t + t / 5.0 print "MIP: %.2f - %.2f" % (p1, p2) otf.AddPoint(p1, 0.0) otf.AddPoint(p2, 1.0) otf.AddPoint(self._config.threshold, 1.0) ctf.RemoveAllPoints() ctf.AddHSVPoint(p1, 0.1, 0.7, 1.0) #ctf.AddHSVPoint(p2, *self._config.mip_colour) ctf.AddHSVPoint(p2, 0.65, 0.7, 1.0) return (otf, ctf)
def retrieveImageInfo(self, filename): """ A method that reads information from an image """ assert filename, "Filename must be defined" assert os.path.exists( filename), "File that we're retrieving information \ from (%s) needs to exist, but doesn't." % filename self.ext = filename.split(".")[-1].lower() rdr = self.getReaderByExtension(self.ext) if self.ext == "bmp": rdr.Allow8BitBMPOn() rdr.SetFileName(filename) if rdr.IsA("vtkExtTIFFReader"): rdr.UpdateInformation() if rdr.GetNumberOfScalarComponents() == 1: rdr.RawModeOn() data = rdr.GetOutput() data.Update() self.numberOfComponents = data.GetNumberOfScalarComponents() if not self.ctf: bd = self.getDataBitDepth(data) self.ctf = vtk.vtkColorTransferFunction() if bd == 8 or bd == 12: self.ctf.AddRGBPoint(0, 0, 0, 0) self.ctf.AddRGBPoint((2**bd) - 1, 0, 1, 0) else: range = data.GetScalarRange() self.ctf.AddRGBPoint(range[0], 0, 0, 0) self.ctf.AddRGBPoint(range[1], 0, 1, 0) self.x, self.y, z = data.GetDimensions() self.dimensions = (self.x, self.y, self.slicesPerTimepoint) if z > 1: self.slicesPerTimepoint = z self.z = z self.dimensions = (self.x, self.y, self.slicesPerTimepoint) lib.messenger.send(self, "update_dimensions") self.originalDimensions = self.dimensions
def showVolume(self, vtkImageData, preserveState): '''Shows volume of image.''' producer = vtk.vtkTrivialProducer() producer.SetOutput(vtkImageData) flip = vtk.vtkImageFlip() # flip over y axis flip.SetFilteredAxis(1) flip.SetInputConnection(producer.GetOutputPort()) mapper = vtk.vtkSmartVolumeMapper() mapper.SetInputConnection(flip.GetOutputPort()) scalarRange = vtkImageData.GetScalarRange() opacity = vtk.vtkPiecewiseFunction() opacity.AddPoint(scalarRange[0], 0.2) opacity.AddPoint(scalarRange[1], 0.9) color = vtk.vtkColorTransferFunction() color.AddRGBPoint(scalarRange[0], 0, 0, 0) color.AddRGBPoint(scalarRange[1], 1, 1, 1) prop = vtk.vtkVolumeProperty() prop.ShadeOff() prop.SetInterpolationType(vtk.VTK_LINEAR_INTERPOLATION) prop.SetColor(color) prop.SetScalarOpacity(opacity) # save tubes and property if preserving state if preserveState and self.volume: prop = self.volume.GetProperty() self.volumeRenderer.RemoveViewProp(self.volume) else: self.volumeRenderer.RemoveAllViewProps() self.volume = vtk.vtkVolume() self.volume.SetMapper(mapper) self.volume.SetProperty(prop) self.volumeRenderer.AddViewProp(self.volume) self.volumeRenderer.ResetCamera()
def load_atlas(path, opacity): ''' path: path to atlas file opacity: opacity of overlayed atlas brain ''' nifti_reader = vtk.vtkNIFTIImageReader() nifti_reader.SetFileName(path) nifti_reader.Update() # The following class is used to store transparencyv-values for later # retrival. In our case, we want the value 0 to be completly opaque alphaChannelFunc = vtk.vtkPiecewiseFunction() alphaChannelFunc.AddPoint(0, 0.0) alphaChannelFunc.AddPoint(1, opacity) # This class stores color data and can create color tables from a few color # points. For this demo, we want the three cubes to be of the colors red # green and blue. colorFunc = vtk.vtkColorTransferFunction() colorFunc.AddRGBPoint(0, 0.0, 0.0, 0.0) colorFunc.AddRGBPoint(1, 1.0, 1.0, 1.0) # The preavius two classes stored properties. Because we want to apply # these properties to the volume we want to render, we have to store them # in a class that stores volume prpoperties. volumeProperty = vtk.vtkVolumeProperty() volumeProperty.SetColor(colorFunc) volumeProperty.SetScalarOpacity(alphaChannelFunc) volumeProperty.ShadeOn() # We can finally create our volume. We also have to specify the data for # it, as well as how the data will be rendered. volumeMapper = vtk.vtkSmartVolumeMapper() volumeMapper.SetInputDataObject(nifti_reader.GetOutput()) # The class vtkVolume is used to pair the preaviusly declared volume as # well as the properties to be used when rendering that volume. volume = vtk.vtkVolume() volume.SetMapper(volumeMapper) volume.SetProperty(volumeProperty) return volume
def getColorTransferFunction(self): """ Returns the ctf of the source dataunit """ sources = self.getSourceDataUnits() if not self.initialized: self.initialized = 1 if len(sources) == 1: ctf = sources[0].getSettings().get("ColorTransferFunction") self.settings.set("ColorTransferFunction", ctf) return ctf else: ctf = sources[0].getSettings().get("ColorTransferFunction") start, end = ctf.GetRange() ctf = vtk.vtkColorTransferFunction() ctf.AddRGBPoint(0, 0, 0, 0) ctf.AddRGBPoint(end, 1.0, 1.0, 1.0) self.settings.set("ColorTransferFunction", ctf) return ctf return self.settings.get("ColorTransferFunction")
def Create16bColorTable(self, scale): if self.color_transfer: color_transfer = self.color_transfer else: color_transfer = vtk.vtkColorTransferFunction() color_transfer.RemoveAllPoints() curve_table = self.config['16bitClutCurves'] color_table = self.config['16bitClutColors'] colors = [] for i, l in enumerate(curve_table): for j, lopacity in enumerate(l): gray_level = lopacity['x'] r = color_table[i][j]['red'] g = color_table[i][j]['green'] b = color_table[i][j]['blue'] colors.append((gray_level, r, g, b)) color_transfer.AddRGBPoint( self.TranslateScale(scale, gray_level), r, g, b) self.color_transfer = color_transfer
def __init__(self,delta,wing): self.arrowColor = vtk.vtkColorTransferFunction() self.update_look_up_table() self.print_counter=0 self.ren = vtk.vtkRenderer() self.geo_reader = vtk.vtkUnstructuredGridReader() self.geo_reader.SetFileName(wing) self.vec_reader = vtk.vtkStructuredPointsReader() self.vec_reader.SetFileName(delta) """ This is for drawing the wing,""" geo_Mapper=vtk.vtkDataSetMapper() geo_Mapper.SetInputConnection(self.geo_reader.GetOutputPort()) geo_actor = vtk.vtkActor() geo_actor.SetMapper(geo_Mapper) self.ren.AddActor(geo_actor) """End of adding the wing """ self.ren.AddActor(self.create_stream_line(25,150,0,0.5)) #Add renderer to renderwindow and render self.renWin = vtk.vtkRenderWindow() self.renWin.AddRenderer(self.ren) self.renWin.SetSize(1920, 1080) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(self.renWin) iren.AddObserver('RightButtonPressEvent', self.capture_image, 1.0) # Scalar Bar actor scalar_bar = vtk.vtkScalarBarActor() scalar_bar.SetOrientationToHorizontal() scalar_bar.SetLookupTable(self.arrowColor) scalar_bar.SetTitle("Color map") scalar_bar.SetLabelFormat("%5.2f") scalar_bar.SetMaximumHeightInPixels(300) scalar_bar.SetMaximumWidthInPixels(60) # Scalar Bar Widget scalar_bar_widget = vtk.vtkScalarBarWidget() scalar_bar_widget.SetInteractor(iren) scalar_bar_widget.SetScalarBarActor(scalar_bar) scalar_bar_widget.On() self.ren.SetBackground(0,0,0) self.renWin.Render() iren.Start()