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 __init__(self, brain_data, isoval=34): # Setup Surface Rendering # Gaussian smoothing of surface rendering for aesthetics # Adds significant delay to rendering self.cortexSmoother = vtk.vtkImageGaussianSmooth() self.cortexSmoother.SetDimensionality(3) self.cortexSmoother.SetRadiusFactors(0.5, 0.5, 0.5) self.cortexSmoother.SetInput(brain_data.GetOutput()) # Apply a marching cubes algorithm to extract surface contour with # isovalue of 30 (can change to adjust proper rendering of tissue self.cortexExtractor = vtk.vtkMarchingCubes() self.cortexExtractor.SetInput(self.cortexSmoother.GetOutput()) self.cortexExtractor.SetValue(0, isoval) self.cortexExtractor.ComputeNormalsOn() # Map/Paint the polydata associated with the surface rendering self.cortexMapper = vtk.vtkPolyDataMapper() self.cortexMapper.SetInput(self.cortexExtractor.GetOutput()) self.cortexMapper.ScalarVisibilityOff() # Color the cortex (RGB) self.cortexProperty = vtk.vtkProperty() self.cortexProperty.SetColor(1, 1, 1) self.cortexProperty.SetOpacity(1) # Set the actor to adhere to mapped surface and inherit properties self.SetMapper(self.cortexMapper) self.SetProperty(self.cortexProperty) self.cortexExtractor.Update()
def open_actor(actor, actor_index=0, scale=SCALE, radius=RADIUS): poly = actor.GetMapper().GetInput() pre_image = voxelizer(poly, scale) opened_image = open_image(pre_image, radius) gauss = vtk.vtkImageGaussianSmooth() gauss.SetDimensionality(3) gauss.SetStandardDeviation(radius, radius, radius) gauss.SetInputData(opened_image) gauss.Update() image_to_contour = gauss.GetOutput() contour = vtk.vtkMarchingCubes() contour.SetInputData(image_to_contour) contour.SetValue(0, 127.5) contour.ComputeScalarsOff() contour.Update() repared_poly = contour.GetOutput() if repared_poly.GetNumberOfCells() == 0: print("ERROR: number_of_cells = 0", end=' ') # write_image(image_to_contour, "/tmp/%d.mhd"%actor_index) raise ValueError("ERROR: number_of_cells = 0") # (minX, maxX, minY, maxY, minZ, maxZ) = [int(x) for x in repared_poly.GetBounds()] #convert tuple of floats to ints # print " Repared bounds are %s"%str((minX, maxX, minY, maxY, minZ, maxZ)) #dimensions of the resulting image # print " Dimensions: %s"%str((maxX - minX, maxY - minY, maxZ - minZ)) actor.GetMapper().SetInputData(repared_poly)
def __init__(self, brain_data, isoval=34): # Setup Surface Rendering # Gaussian smoothing of surface rendering for aesthetics # Adds significant delay to rendering self.cortexSmoother = vtk.vtkImageGaussianSmooth() self.cortexSmoother.SetDimensionality(3) self.cortexSmoother.SetRadiusFactors(0.5, 0.5, 0.5) self.cortexSmoother.SetInput(brain_data.GetOutput()) # Apply a marching cubes algorithm to extract surface contour with # isovalue of 30 (can change to adjust proper rendering of tissue self.cortexExtractor = vtk.vtkMarchingCubes() self.cortexExtractor.SetInput(self.cortexSmoother.GetOutput()) self.cortexExtractor.SetValue(0, isoval) self.cortexExtractor.ComputeNormalsOn() # Map/Paint the polydata associated with the surface rendering self.cortexMapper = vtk.vtkPolyDataMapper() self.cortexMapper.SetInput(self.cortexExtractor.GetOutput()) self.cortexMapper.ScalarVisibilityOff() # Color the cortex (RGB) self.cortexProperty = vtk.vtkProperty() self.cortexProperty.SetColor(1, 1, 1) self.cortexProperty.SetOpacity(1); # Set the actor to adhere to mapped surface and inherit properties self.SetMapper(self.cortexMapper) self.SetProperty(self.cortexProperty) self.cortexExtractor.Update()
def smooth(self, sigma=3, radius=None): """ Smooth a Picture with Gaussian kernel. Parameters ---------- sigma : int, optional number of sigmas in pixel units. The default is 3. radius : TYPE, optional how far out the gaussian kernel will go before being clamped to zero. The default is None. """ gsf = vtk.vtkImageGaussianSmooth() gsf.SetDimensionality(2) gsf.SetInputData(self._data) if radius is not None: if utils.isSequence(radius): gsf.SetRadiusFactors(radius[0],radius[1]) else: gsf.SetRadiusFactor(radius) if utils.isSequence(sigma): gsf.SetStandardDeviations(sigma[0], sigma[1]) else: gsf.SetStandardDeviation(sigma) gsf.Update() return self._update(gsf.GetOutput())
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkImageGaussianSmooth(), 'Processing.', ('vtkImageData',), ('vtkImageData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def vtkVOIdata(self, volum = 'GAUSSIAN'): """ Modification du volume d'interet """ #----------------------------------------- # Creation de la VOI #----------------------------------------- self.vtkVolum = vtk.vtkExtractVOI() self.vtkVolum.SetInput(self.vtkVolumAll.GetOutput()) self.vtkVolum.SetVOI(self.VOI_pt1[0], self.VOI_pt2[0], \ self.VOI_pt1[1], self.VOI_pt2[1], \ self.VOI_pt1[2], self.VOI_pt2[2]) self.vtkVolumBlur = vtk.vtkImageGaussianSmooth() #----------------------------------------- # Creation du volume sur volume filtre gaussien #----------------------------------------- if volum == 'GAUSSIAN': self.vtkVolumBlur.SetInputConnection(self.vtkVolum.GetOutputPort()) #----------------------------------------- # Creation du volume sur volume filtre gradient + gaussien #----------------------------------------- if volum == 'GRADIENT': self.vtkVolumGrad = vtk.vtkImageGradientMagnitude() self.vtkVolumGrad.SetDimensionality(3) self.vtkVolumGrad.HandleBoundariesOn() self.vtkVolumGrad.SetInputConnection(self.vtkVolum.GetOutputPort()) self.vtkVolumBlur.SetInputConnection(self.vtkVolumGrad.GetOutputPort()) self.vtkVolumBlur.SetStandardDeviation(self.valGaussianFilter) self.vtkVolumBlur.Update() self.vtkVolumRange = self.vtkVolumBlur.GetOutput().GetScalarRange() print " Range from Volume Of Interest : ", self.vtkVolumRange
def setupImageProcessingPipeline(self): # Gaussian Smooth the image first # http://www.vtk.org/doc/nightly/html/classvtkImageGaussianSmooth.html self.noiseFilter = vtk.vtkImageGaussianSmooth() self.noiseFilter.SetStandardDeviation(1, 1, 1) self.noiseFilter.SetRadiusFactors(10, 10, 10) # Image Resize for resampler # http://www.vtk.org/doc/nightly/html/classvtkImageResize.html self.resampler = vtk.vtkImageResize() self.resampler.SetResizeMethodToMagnificationFactors() self.resampler.SetMagnificationFactors(1, 1, 1) self.resampler.BorderOn() self.resampler.SetInputConnection(self.noiseFilter.GetOutputPort()) # Marching cubes for iso value # http://www.vtk.org/doc/nightly/html/classvtkImageMarchingCubes.html self.marchingCubes = vtk.vtkImageMarchingCubes() self.marchingCubes.SetInputConnection(self.resampler.GetOutputPort()) self.marchingCubes.ComputeGradientsOn() self.marchingCubes.ComputeNormalsOn() self.marchingCubes.ComputeScalarsOn() self.marchingCubes.SetNumberOfContours(1) self.marchingCubes.SetValue(0, 0) # Create mapper and actor for renderer self.mapper = vtk.vtkPolyDataMapper() self.mapper.SetInputConnection(self.marchingCubes.GetOutputPort()) self.actor = vtk.vtkActor() self.actor.SetMapper(self.mapper) self.actor.GetProperty().SetInterpolationToGouraud()
def CreateFrogActor(fileName, tissue): #reader = vtk.vtkMetaImageReader() reader = vtk.vtkXMLImageDataReader() reader.SetFileName(fileName) reader.Update() selectTissue = vtk.vtkImageThreshold() #selectTissue.ThresholdBetween(tissue, tissue) selectTissue.ThresholdBetween(120, 125) selectTissue.SetInValue(255) selectTissue.SetOutValue(0) selectTissue.SetInputConnection(reader.GetOutputPort()) gaussianRadius = 1 gaussianStandardDeviation = 2.0 gaussian = vtk.vtkImageGaussianSmooth() gaussian.SetStandardDeviations(gaussianStandardDeviation, gaussianStandardDeviation, gaussianStandardDeviation) gaussian.SetRadiusFactors(gaussianRadius, gaussianRadius, gaussianRadius) gaussian.SetInputConnection(selectTissue.GetOutputPort()) isoValue = 130 mcubes = vtk.vtkMarchingCubes() #mcubes.SetInputConnection(gaussian.GetOutputPort()) mcubes.SetInputConnection(reader.GetOutputPort()) mcubes.ComputeScalarsOff() mcubes.ComputeGradientsOff() mcubes.ComputeNormalsOff() mcubes.SetValue(0, isoValue) smoothingIterations = 5 passBand = 0.001 featureAngle = 60.0 smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(mcubes.GetOutputPort()) smoother.SetNumberOfIterations(smoothingIterations) smoother.BoundarySmoothingOff() smoother.FeatureEdgeSmoothingOff() smoother.SetFeatureAngle(featureAngle) smoother.SetPassBand(passBand) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() smoother.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(smoother.GetOutputPort()) normals.SetFeatureAngle(featureAngle) stripper = vtk.vtkStripper() stripper.SetInputConnection(normals.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def gaussianSmooth(image,stddev=3): gaussian = vtk.vtkImageGaussianSmooth() gaussian.SetInput(generalTools.castImage(image, coding='double')) gaussian.SetStandardDeviation(stddev) gaussian.SetDimensionality(3) gaussian.Update() return gaussian.GetOutput()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkImageGaussianSmooth(), 'Processing.', ('vtkImageData', ), ('vtkImageData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def GaussFilter2D(vtk_image_data): vtk_gauss_filter2d = vtk.vtkImageGaussianSmooth() vtk_gauss_filter2d.SetInputData(vtk_image_data) vtk_gauss_filter2d.SetDimensionality(2) vtk_gauss_filter2d.SetRadiusFactor(5) vtk_gauss_filter2d.SetStandardDeviation(3) vtk_gauss_filter2d.Update() return vtk_gauss_filter2d.GetOutput() pass
def create_smooth_frog_actor(file_name, tissue): reader = vtk.vtkMetaImageReader() reader.SetFileName(str(file_name)) reader.Update() select_tissue = vtk.vtkImageThreshold() select_tissue.ThresholdBetween(tissue, tissue) select_tissue.SetInValue(255) select_tissue.SetOutValue(0) select_tissue.SetInputConnection(reader.GetOutputPort()) gaussianRadius = 1 gaussianStandardDeviation = 2.0 gaussian = vtk.vtkImageGaussianSmooth() gaussian.SetStandardDeviations(gaussianStandardDeviation, gaussianStandardDeviation, gaussianStandardDeviation) gaussian.SetRadiusFactors(gaussianRadius, gaussianRadius, gaussianRadius) gaussian.SetInputConnection(select_tissue.GetOutputPort()) isoValue = 63.5 iso_surface = vtk.vtkFlyingEdges3D() iso_surface.SetInputConnection(gaussian.GetOutputPort()) iso_surface.ComputeScalarsOff() iso_surface.ComputeGradientsOff() iso_surface.ComputeNormalsOff() iso_surface.SetValue(0, isoValue) smoothing_iterations = 20 pass_band = 0.001 feature_angle = 60.0 smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(iso_surface.GetOutputPort()) smoother.SetNumberOfIterations(smoothing_iterations) smoother.BoundarySmoothingOff() smoother.FeatureEdgeSmoothingOff() smoother.SetFeatureAngle(feature_angle) smoother.SetPassBand(pass_band) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOff() smoother.Update() normals = vtk.vtkPolyDataNormals() normals.SetInputConnection(smoother.GetOutputPort()) normals.SetFeatureAngle(feature_angle) stripper = vtk.vtkStripper() stripper.SetInputConnection(normals.GetOutputPort()) mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(stripper.GetOutputPort()) actor = vtk.vtkActor() actor.SetMapper(mapper) return actor
def main(): colors = vtk.vtkNamedColors() fileName = get_program_parameters() # Now create the RenderWindow, Renderer and Interactor. # ren1 = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren1) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) imageIn = vtk.vtkPNMReader() imageIn.SetFileName(fileName) gaussian = vtk.vtkImageGaussianSmooth() gaussian.SetStandardDeviations(2, 2) gaussian.SetDimensionality(2) gaussian.SetRadiusFactors(1, 1) gaussian.SetInputConnection(imageIn.GetOutputPort()) geometry = vtk.vtkImageDataGeometryFilter() geometry.SetInputConnection(gaussian.GetOutputPort()) aClipper = vtk.vtkClipPolyData() aClipper.SetInputConnection(geometry.GetOutputPort()) aClipper.SetValue(127.5) aClipper.GenerateClipScalarsOff() aClipper.InsideOutOn() aClipper.GetOutput().GetPointData().CopyScalarsOff() aClipper.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(aClipper.GetOutputPort()) mapper.ScalarVisibilityOff() letter = vtk.vtkActor() letter.SetMapper(mapper) ren1.AddActor(letter) letter.GetProperty().SetDiffuseColor(colors.GetColor3d("LampBlack")) letter.GetProperty().SetRepresentationToWireframe() ren1.SetBackground(colors.GetColor3d("WhiteSmoke")) ren1.ResetCamera() ren1.GetActiveCamera().Dolly(1.2) ren1.ResetCameraClippingRange() renWin.SetSize(640, 480) renWin.SetWindowName('CreateBFont') # Render the image. # renWin.Render() iren.Start()
def BuildEditedImage(imagedata, points): """ Editing the original image in accordance with the edit points in the editor, it is necessary to generate the vtkPolyData via vtkContourFilter """ init_values = None for point in points: x, y, z = point colour = points[point] imagedata.SetScalarComponentFromDouble(x, y, z, 0, colour) imagedata.Update() if not (init_values): xi = x xf = x yi = y yf = y zi = z zf = z init_values = 1 if (xi > x): xi = x elif (xf < x): xf = x if (yi > y): yi = y elif (yf < y): yf = y if (zi > z): zi = z elif (zf < z): zf = z clip = vtk.vtkImageClip() clip.SetInput(imagedata) clip.SetOutputWholeExtent(xi, xf, yi, yf, zi, zf) clip.Update() gauss = vtk.vtkImageGaussianSmooth() gauss.SetInput(clip.GetOutput()) gauss.SetRadiusFactor(0.6) gauss.Update() app = vtk.vtkImageAppend() app.PreserveExtentsOn() app.SetAppendAxis(2) app.SetInput(0, imagedata) app.SetInput(1, gauss.GetOutput()) app.Update() return app.GetOutput()
def BuildEditedImage(imagedata, points): """ Editing the original image in accordance with the edit points in the editor, it is necessary to generate the vtkPolyData via vtkContourFilter """ init_values = None for point in points: x, y, z = point colour = points[point] imagedata.SetScalarComponentFromDouble(x, y, z, 0, colour) imagedata.Update() if not(init_values): xi = x xf = x yi = y yf = y zi = z zf = z init_values = 1 if (xi > x): xi = x elif(xf < x): xf = x if (yi > y): yi = y elif(yf < y): yf = y if (zi > z): zi = z elif(zf < z): zf = z clip = vtk.vtkImageClip() clip.SetInput(imagedata) clip.SetOutputWholeExtent(xi, xf, yi, yf, zi, zf) clip.Update() gauss = vtk.vtkImageGaussianSmooth() gauss.SetInput(clip.GetOutput()) gauss.SetRadiusFactor(0.6) gauss.Update() app = vtk.vtkImageAppend() app.PreserveExtentsOn() app.SetAppendAxis(2) app.SetInput(0, imagedata) app.SetInput(1, gauss.GetOutput()) app.Update() return app.GetOutput()
def gaussianFilter(image): filter = vtk.vtkImageGaussianSmooth() filter.SetInputConnection(image.GetOutputPort()) filter.SetStandardDeviation(1) filter.SetRadiusFactors(1, 1, 1) filter.SetDimensionality(3) filter.Update() return filter.GetOutput()
def __init__(self, img, threshold, xysmoothing, zsmoothing, color, alpha): 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(xysmoothing, xysmoothing, zsmoothing) self.__smoother.SetInputConnection(dataImporter.GetOutputPort()) self.__threshold = vtk.vtkImageThreshold() self.__threshold.SetInputConnection(self.__smoother.GetOutputPort()) self.__threshold.ThresholdByUpper(threshold) self.__threshold.ReplaceInOn() self.__threshold.SetInValue(1) self.__threshold.ReplaceOutOn() self.__threshold.SetOutValue(0) self.__threshold.Update() contour = vtk.vtkDiscreteMarchingCubes() contour.SetInputConnection(self.__threshold.GetOutputPort()) contour.ComputeNormalsOn() contour.SetValue(0, 1) contour.Update() smoother = vtk.vtkWindowedSincPolyDataFilter() smoother.SetInputConnection(contour.GetOutputPort()) smoother.NonManifoldSmoothingOn() smoother.NormalizeCoordinatesOn() smoother.Update() triangleCellNormals=vtk.vtkPolyDataNormals() triangleCellNormals.SetInputConnection(smoother.GetOutputPort()) triangleCellNormals.ComputeCellNormalsOn() triangleCellNormals.ComputePointNormalsOff() triangleCellNormals.ConsistencyOn() triangleCellNormals.AutoOrientNormalsOn() triangleCellNormals.Update() triangleCellAn = vtk.vtkMeshQuality() triangleCellAn.SetInputConnection(triangleCellNormals.GetOutputPort()) triangleCellAn.SetTriangleQualityMeasureToArea() triangleCellAn.SaveCellQualityOn() triangleCellAn.Update() mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(triangleCellAn.GetOutputPort()) mapper.ScalarVisibilityOn() mapper.SetScalarRange(.3, 1) mapper.SetScalarModeToUsePointData() colorLookupTable = vtk.vtkLookupTable() colorLookupTable.SetHueRange(.6, 1) colorLookupTable.Build() mapper.SetLookupTable(colorLookupTable) self.SetMapper(mapper) self.GetProperty().SetColor(*color) self.GetProperty().SetOpacity(alpha)
def __init__(self): """ Initialization """ ProcessingFilter.ProcessingFilter.__init__(self, (1, 1)) self.vtkfilter = vtk.vtkImageGaussianSmooth() self.eventDesc = "Performing gaussian smoothing" self.vtkfilter.AddObserver("ProgressEvent", lib.messenger.send) lib.messenger.connect(self.vtkfilter, 'ProgressEvent', self.updateProgress) self.descs = {"RadiusX": "Radius factor X:", "RadiusY": "Radius factor Y:", "RadiusZ": "Radius factor Z:", "Dimensionality": "Dimensionality"} self.filterDesc = "Performs convolution with gaussian\nInput: Grayscale image\nOutput: Grayscale image"
def applyGauss(self, imgData, std=1, radius=3): # Use bult in functions in vtk to smooth data filterImg = vtk.vtkImageGaussianSmooth() # set input connection from the reader filterImg.SetInputData(imgData.GetOutput()) filterImg.SetStandardDeviation(std, std, std) filterImg.SetRadiusFactors(radius, radius, radius) filterImg.SetDimensionality(3) filterImg.Update() return filterImg # return vtk object type
def ApplyGaussianFilter(self): spacing = self.Image.GetSpacing() pixelStandardDeviations = [self.StandardDeviation/spacing[0],self.StandardDeviation/spacing[1],self.StandardDeviation/spacing[2]] smoothingFilter = vtk.vtkImageGaussianSmooth() smoothingFilter.SetInputData(self.Image) smoothingFilter.SetStandardDeviations(pixelStandardDeviations) smoothingFilter.SetRadiusFactor(self.RadiusFactor) smoothingFilter.SetDimensionality(self.Dimensionality) smoothingFilter.Update() self.EnhancedImage = smoothingFilter.GetOutput()
def performLaplaceOfGaussian(self, image): gaussian = vtk.vtkImageGaussianSmooth() gaussian.SetInputData(image) gaussian.Update() laplacian = vtk.vtkImageLaplacian() laplacian.SetInputData(gaussian.GetOutput()) laplacian.Update() outImageData = vtk.vtkImageData() outImageData.DeepCopy(laplacian.GetOutput()) return outImageData
def VTKGauss(x,sigma=5,numret=1,radius=3,sigmax=None,sigmay=None): if type(x) == np.ndarray: i = NumToVTKImage(x) else: i = x if sigmax is None: sigmax=sigma if sigmay is None: sigmay=sigma d = vtk.vtkImageGaussianSmooth() d.SetStandardDeviations(sigmax,sigmay,0) d.SetRadiusFactors(radius,radius,1) d.SetInputData(i) o = d.GetOutput() d.Update() if numret: return VTKImageToNum(o) else: return o
def execute(self, inputs=(1, 1), update=0, last=0): """ Execute filter in input image and return output image. """ if not lib.ProcessingFilter.ProcessingFilter.execute(self, inputs): return None image = self.getInput(1) dim = image.GetDimensions()[2] if dim > 0: dim = 3 else: dim = 2 radius1 = int(round(2 * self.parameters["StdDevX1"])), int( round(2 * self.parameters["StdDevY1"])), int( round(2 * self.parameters["StdDevZ1"])) radius2 = int(round(2 * self.parameters["StdDevX2"])), int( round(2 * self.parameters["StdDevY2"])), int( round(2 * self.parameters["StdDevZ2"])) gaussian = vtk.vtkImageGaussianSmooth() gaussian.SetInput(image) gaussian.SetDimensionality(dim) gaussian.SetStandardDeviations(self.parameters["StdDevX1"], self.parameters["StdDevY1"], self.parameters["StdDevZ1"]) gaussian.SetRadiusFactors(radius1) gaussian.Update() gaussian1 = vtk.vtkImageData() gaussian1.DeepCopy(gaussian.GetOutput()) gaussian.SetStandardDeviations(self.parameters["StdDevX2"], self.parameters["StdDevY2"], self.parameters["StdDevZ2"]) gaussian.SetRadiusFactors(radius2) gaussian.Update() gaussian2 = gaussian.GetOutput() imageMath = vtkbxd.vtkImageMathematicsClamp() imageMath.SetOperationToSubtract() imageMath.SetInput1(gaussian1) imageMath.SetInput2(gaussian2) imageMath.SetClampOverflow(True) data = imageMath.GetOutput() #if update: data.Update() return data
def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._imageGaussianSmooth = vtk.vtkImageGaussianSmooth() module_utils.setup_vtk_object_progress( self, self._imageGaussianSmooth, 'Smoothing image with Gaussian') self._config.standardDeviation = (2.0, 2.0, 2.0) self._config.radiusCutoff = (1.5, 1.5, 1.5) self._view_frame = None self._module_manager.sync_module_logic_with_config(self)
def __init__(self, data): gaussianSmooth = vtk.vtkImageGaussianSmooth() gaussianSmooth.SetInputData(data.GetOutput()) gaussianSmooth.SetDimensionality(1) gaussianSmooth.SetStandardDeviation(2.0) gaussianSmooth.Update() interp = vtk.vtkImageInterpolator() interp.Initialize(gaussianSmooth.GetOutput()) interp.SetOutValue(-42) interp.Update() self.interp = interp
def Execute(self): if self.Image == None: self.PrintError('Error: No input image.') spacing = self.Image.GetSpacing() pixelStandardDeviations = [self.StandardDeviation/spacing[0],self.StandardDeviation/spacing[1],self.StandardDeviation/spacing[2]] smoothingFilter = vtk.vtkImageGaussianSmooth() smoothingFilter.SetInputData(self.Image) smoothingFilter.SetStandardDeviations(pixelStandardDeviations) smoothingFilter.SetRadiusFactor(self.RadiusFactor) smoothingFilter.SetDimensionality(self.Dimensionality) smoothingFilter.Update() self.Image = smoothingFilter.GetOutput()
def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) self._imageGaussianSmooth = vtk.vtkImageGaussianSmooth() module_utils.setup_vtk_object_progress(self, self._imageGaussianSmooth, 'Smoothing image with Gaussian') self._config.standardDeviation = (2.0, 2.0, 2.0) self._config.radiusCutoff = (1.5, 1.5, 1.5) self._view_frame = None self._module_manager.sync_module_logic_with_config(self)
def createMesh(self, polyData, spacing): dv = 1.75 rf = 1 data_matrix = polyData data_matrix = np.rot90(data_matrix, 1) data_matrix = data_matrix.astype(np.uint8) xSize, ySize, zSize = data_matrix.shape #================================BoneExtrctor================================== dataImporter = vtk.vtkImageImport() data_string = data_matrix.tostring() dataImporter.CopyImportVoidPointer(data_string, len(data_string)) dataImporter.SetDataScalarTypeToUnsignedChar() dataImporter.SetNumberOfScalarComponents(1) dataImporter.SetDataExtent(0, xSize - 1, 0, ySize - 1, 0, zSize - 1) dataImporter.SetWholeExtent(0, xSize - 1, 0, ySize - 1, 0, zSize - 1) dataImporter.SetDataExtentToWholeExtent() #============================= Smoothed pipeline ============================== smooth = vtk.vtkImageGaussianSmooth() smooth.SetDimensionality(3) smooth.SetInputConnection(dataImporter.GetOutputPort()) smooth.SetStandardDeviations(dv, dv, dv) smooth.SetRadiusFactor(rf) subsampleSmoothed = vtk.vtkImageShrink3D() subsampleSmoothed.SetInputConnection(smooth.GetOutputPort()) subsampleSmoothed.SetShrinkFactors(4, 4, 1) isoSmoothed = vtk.vtkImageMarchingCubes() isoSmoothed.SetInputConnection(smooth.GetOutputPort()) isoSmoothed.SetValue(0, 10) isoSmoothedMapper = vtk.vtkPolyDataMapper() isoSmoothedMapper.SetInputConnection(isoSmoothed.GetOutputPort()) isoSmoothedMapper.ScalarVisibilityOff() tmpTransfor = vtk.vtkTransform() tmpTransfor.Scale(spacing) meshActor = vtk.vtkActor() meshActor.SetMapper(isoSmoothedMapper) meshActor.SetUserTransform(tmpTransfor) return meshActor
def __init__(self, parent=None): # Defaults self.filename = "" self.gaussStandardDeviation = 1.2 self.gaussRadius = 2 self.magnification = 1 self.isosurface = 1 self.actorColor = [1.000, 0.000, 0.000] self.actorOpacity = 1.0 self.actorVisibility = 1 self.actorPickable = 1 self.pipelineType = "MarchingCubes" # In the future we could define other types of pipelines self.pipelineDataType = None self.actorAdded = False self.processing_log = None self.image_info = None # Elements of the VTK pipeline self.reader = None self.gauss = vtk.vtkImageGaussianSmooth() self.pad = vtk.vtkImageConstantPad() self.resampler = vtk.vtkImageResize() self.marchingCubes = vtk.vtkImageMarchingCubes() self.mapper = vtk.vtkPolyDataMapper() self.mapperDS = vtk.vtkDataSetMapper() self.actor = vtk.vtkActor() self.transformPolyData = vtk.vtkTransformPolyDataFilter() # The vtkTransform is part of the pipeline. The matrix defines the vtkTransform, but we # store a copy in self.matrix for retrieval later. self.rigidBodyTransform = vtk.vtkTransform() self.rigidBodyTransform.Identity() self.rigidBodyTransform.PostMultiply() # Important so that transform concatenations is correct! self.matrix = vtk.vtkMatrix4x4() self.dim = [1,1,1] self.pos = [0,0,0] self.el_size_mm = [0.082,0.082,0.082] self.extent = [0,1,0,1,0,1] self.origin = [0,0,0] self.validForExtrusion = False
def isosurface(image, c, alpha, wire, bc, legend, texture, smoothing, threshold, connectivity): '''Return a vtkActor isosurface from a vtkImageData object.''' from vtkplotter.actors import Actor if smoothing: print(' gaussian smoothing data with volume_smoothing =', smoothing) smImg = vtk.vtkImageGaussianSmooth() smImg.SetDimensionality(3) smImg.SetInputData(image) smImg.SetStandardDeviations(smoothing, smoothing, smoothing) smImg.Update() image = smImg.GetOutput() scrange = image.GetScalarRange() if not threshold: if scrange[1] > 1e10: threshold = (2*scrange[0]+abs(10*scrange[0]))/3. print("Warning, high scalar range detected:", scrange[1]) print(" setting threshold to:", threshold) else: threshold = (2*scrange[0]+scrange[1])/3. cf = vtk.vtkContourFilter() cf.SetInputData(image) cf.UseScalarTreeOn() cf.ComputeScalarsOff() cf.SetValue(0, threshold) cf.Update() clp = vtk.vtkCleanPolyData() clp.SetInputData(cf.GetOutput()) clp.Update() image = clp.GetOutput() if connectivity: print(' applying connectivity filter, select largest region') conn = vtk.vtkPolyDataConnectivityFilter() conn.SetExtractionModeToLargestRegion() conn.SetInputData(image) conn.Update() image = conn.GetOutput() return Actor(image, c, alpha, wire, bc, legend, texture)
def execute(self, inputs = (1,1), update = 0, last = 0): """ Execute filter in input image and return output image. """ if not lib.ProcessingFilter.ProcessingFilter.execute(self,inputs): return None image = self.getInput(1) dim = image.GetDimensions()[2] if dim > 0: dim = 3 else: dim = 2 radius1 = int(round(2 * self.parameters["StdDevX1"])), int(round(2 * self.parameters["StdDevY1"])), int(round(2 * self.parameters["StdDevZ1"])) radius2 = int(round(2 * self.parameters["StdDevX2"])), int(round(2 * self.parameters["StdDevY2"])), int(round(2 * self.parameters["StdDevZ2"])) gaussian = vtk.vtkImageGaussianSmooth() gaussian.SetInput(image) gaussian.SetDimensionality(dim) gaussian.SetStandardDeviations(self.parameters["StdDevX1"],self.parameters["StdDevY1"],self.parameters["StdDevZ1"]) gaussian.SetRadiusFactors(radius1) gaussian.Update() gaussian1 = vtk.vtkImageData() gaussian1.DeepCopy(gaussian.GetOutput()) gaussian.SetStandardDeviations(self.parameters["StdDevX2"],self.parameters["StdDevY2"],self.parameters["StdDevZ2"]) gaussian.SetRadiusFactors(radius2) gaussian.Update() gaussian2 = gaussian.GetOutput() imageMath = vtkbxd.vtkImageMathematicsClamp() imageMath.SetOperationToSubtract() imageMath.SetInput1(gaussian1) imageMath.SetInput2(gaussian2) imageMath.SetClampOverflow(True) data = imageMath.GetOutput() #if update: data.Update() return data
def ipl_gauss_lp(image_in, sigma, support): ipl_gauss_lp_settings(sigma, support) gauss = vtk.vtkImageGaussianSmooth() gauss.SetInput(image_in) gauss.SetDimensionality(3) gauss.SetStandardDeviation(sigma) gauss.SetRadiusFactors(support, support, support) gauss.Update() extent = gauss.GetOutput().GetExtent() off = [support, support, support] voi = vtk.vtkExtractVOI() voi.SetInput(gauss.GetOutput()) voi.SetVOI(extent[0] + off[0], extent[1] - off[0], extent[2] + off[1], extent[3] - off[1], extent[4] + off[2], extent[5] - off[2]) voi.Update() image_out = voi.GetOutput() return image_out
def __init__(self, input_file, gaussian, radius, isosurface, window_size, *args, **kwargs): """MainWindow constructor""" super().__init__(*args, **kwargs) # Window setup self.resize(window_size[0], window_size[1]) self.title = "Basic Qt Viewer for MDSC 689.03" self.statusBar().showMessage("Welcome.", 8000) # Capture defaults self.gaussian = gaussian self.radius = radius self.isosurface = isosurface # Initialize the window self.initUI() # Set up some VTK pipeline classes self.reader = None self.gauss = vtk.vtkImageGaussianSmooth() self.marchingCubes = vtk.vtkImageMarchingCubes() self.mapper = vtk.vtkPolyDataMapper() self.actor = vtk.vtkActor() # Take inputs from command line. Only use these if there is an input file specified if (input_file != None): if (not os.path.exists(input_file)): qtw.QMessageBox.warning(self, "Error", "Invalid input file.") return #_,ext = os.path.splitext(input_file) #if not (self.validExtension(ext.lower())): # qtw.QMessageBox.warning(self, "Error", "Invalid file type.") # return self.createPipeline(input_file) self.statusBar().showMessage("Loading file " + input_file, 4000) self.changeSigma(gaussian) self.changeRadius(radius) self.changeIsosurface(isosurface)
def gaussianSmooth(self, sigma=(2, 2, 2), radius=None): """Performs a convolution of the input Volume with a gaussian. :param float,list sigma: standard deviation(s) in voxel units. A list can be given to smooth in the three direction differently. :param float,list radius: radius factor(s) determine how far out the gaussian kernel will go before being clamped to zero. A list can be given too. """ gsf = vtk.vtkImageGaussianSmooth() gsf.SetDimensionality(3) gsf.SetInputData(self.imagedata()) if utils.isSequence(sigma): gsf.SetStandardDeviations(sigma) else: gsf.SetStandardDeviation(sigma) if radius is not None: if utils.isSequence(radius): gsf.SetRadiusFactors(radius) else: gsf.SetRadiusFactor(radius) gsf.Update() return self._update(gsf.GetOutput())
def ipl_seg_gauss(image_in, sigma, support, lower, upper, value_in_range): ipl_seg_gauss_settings(sigma, support, lower, upper, value_in_range) gauss = vtk.vtkImageGaussianSmooth() gauss.SetInputConnection(image_in()) gauss.SetDimensionality(3) gauss.SetStandardDeviation(sigma) gauss.SetRadiusFactors(support, support, support) gauss.Update() # If there is an offset in the input file, we scrub # those layers from the image data (as does IPL during # the thresholding function extent = reader.GetOutput().GetExtent() voi = vtk.vtkExtractVOI() voi.SetInputConnection(gauss.GetOutputPort()) voi.SetVOI(extent[0] + support, extent[1] - support, extent[2] + support, extent[3] - support, extent[4] + support, extent[5] - support) voi.Update() # Scale the thresholds from 'per 1000' of maximum scalar value max_scaler = gauss.GetOutput().GetScalarTypeMax() scaled_lower = lower / 1000.0 * max_scaler scaled_upper = upper / 1000.0 * max_scaler thres = vtk.vtkImageThreshold() thres.SetInputConnection(voi.GetOutputPort()) thres.ThresholdBetween(scaled_lower, scaled_upper) thres.SetInValue(value_in_range) thres.SetOutValue(0) thres.SetOutputScalarTypeToChar() thres.Update() image_out = thres.GetOutput() return image_out
def GaussianFilter(self, image, radius=3, image3d=True): """Returns a Gaussian-smoothed version of image""" n = image.get_array() dims = n.shape if image3d or len(dims) == 2 or dims[0] == 1: # use VTK here - multithreaded performance image.SetReleaseDataFlag(1) _filter = vtk.vtkImageGaussianSmooth() _filter.SetDimensionality(3) _filter.SetRadiusFactor(radius) _filter.SetInput(image.GetRealImage()) _filter.SetProgressText("Applying Gaussian filter...") _filter.AddObserver('ProgressEvent', self.HandleVTKProgressEvent) _filter.Update() image = MVImage.MVImage(_filter.GetOutputPort(), input=image) else: # apply slice-by-slice filter for z in range(dims[0]): event.notify( ProgressEvent("Applying slice-by-slice Gaussian filter...", float(z) / dims[0])) n[z, :] = scipy.ndimage.filters.gaussian_filter(n[z, :], sigma=radius) # image.GetPointData().GetScalars().Modified() image.ScalarsModified() event.notify( ProgressEvent("Applying slice-by-slice Gaussian filter...", 1.0)) logging.info("Gaussian filter applied with radius={0}".format(radius)) return image
def GaussianFilter(self, image, radius=3, image3d=True): """Returns a Gaussian-smoothed version of image""" n = image.get_array() dims = n.shape if image3d or len(dims) == 2 or dims[0] == 1: # use VTK here - multithreaded performance image.SetReleaseDataFlag(1) _filter = vtk.vtkImageGaussianSmooth() _filter.SetDimensionality(3) _filter.SetRadiusFactor(radius) _filter.SetInput(image.GetRealImage()) _filter.SetProgressText("Applying Gaussian filter...") _filter.AddObserver('ProgressEvent', self.HandleVTKProgressEvent) _filter.Update() image = MVImage.MVImage(_filter.GetOutputPort(), input=image) else: # apply slice-by-slice filter for z in range(dims[0]): event.notify( ProgressEvent("Applying slice-by-slice Gaussian filter...", float(z) / dims[0])) n[z, :] = scipy.ndimage.filters.gaussian_filter( n[z, :], sigma=radius) # image.GetPointData().GetScalars().Modified() image.ScalarsModified() event.notify( ProgressEvent("Applying slice-by-slice Gaussian filter...", 1.0)) logging.info("Gaussian filter applied with radius={0}".format(radius)) return image
pointData = imageData.GetPointData() dataArray = pointData.GetArray(0) minVal, maxVal = dataArray.GetRange() xmin, xmax, ymin, ymax, zmin, zmax = imageData.GetBounds() print 'xmin, xmax = ', xmin, xmax print 'ymin, ymax = ', ymin, ymax print 'zmin, zmax = ', zmin, zmax print 'minVal, maxVal = ', minVal, maxVal nx, ny, nz = imageData.GetDimensions() print 'nx, ny, nz = ', nx, ny, nz smooth = vtk.vtkImageGaussianSmooth() npx, npy, npz = int(0.01*nx), int(0.01*ny), int(0.05*nz) print 'npx, npy, npz = ', npx, npy, npz smooth.SetStandardDeviation(npx, npy, npz) #smooth.SetRadiusFactors(10, 10, 10) if vtk.VTK_MAJOR_VERSION <= 5: smooth.SetInput(imageData) else: smooth.SetInputData(imageData) smooth.Update() print smooth.GetOutput() print smooth.GetOutput().GetPointData().GetArray(0).GetRange() contour = vtk.vtkContourFilter()
def Execute(self): if self.GaussFiltering: gauss = vtk.vtkImageGaussianSmooth() gauss.SetInput(self.Image) gauss.SetStandardDeviations(self.StandardDeviations) gauss.SetRadiusFactors(self.RadiusFactors) if self.Shape.find('2d') != -1: gauss.SetDimensionality(2) elif self.Shape.find('3d') != -1: gauss.SetDimensionality(3) else: gauss.SetDimensionality(3) gauss.Update() self.Image = gauss.GetOutput() scalarRange = [0.0,0.0] if self.FWHMRegion == 'image': scalarRange = self.Image.GetScalarRange() elif self.FWHMRegion == 'midline': extent = self.Image.GetWholeExtent() newYExtent = extent[2]+(extent[3]-extent[2])/2 clip = vtk.vtkImageClip() clip.SetInput(self.Image) clip.SetOutputWholeExtent(extent[0],extent[1],newYExtent,newYExtent,extent[4],extent[5]) clip.ClipDataOn() clip.Update() scalarRange = clip.GetOutput().GetScalarRange() self.FWHMLevel = (scalarRange[1] - scalarRange[0]) * self.FWHMRatio + scalarRange[0] if self.FWHMBackground != None: self.FWHMLevel = (scalarRange[1] - self.FWHMBackground) * self.FWHMRatio + self.FWHMBackground if self.Method == 'levelsets': if self.Shape.find('2d') != -1: gradientMagnitude = vtk.vtkImageGradientMagnitude() gradientMagnitude.SetDimensionality(2) elif self.Shape.find('3d') != -1: if self.FeatureImageType == 'gradient': gradientMagnitude = vtkvmtk.vtkvmtkGradientMagnitudeImageFilter() elif self.FeatureImageType == 'upwind': gradientMagnitude = vtkvmtk.vtkvmtkUpwindGradientMagnitudeImageFilter() gradientMagnitude.SetUpwindFactor(self.UpwindFactor) else: self.PrintError('Unsupported feature image type: choices are "gradient", "upwind".') return else: gradientMagnitude = vtk.vtkImageGradientMagnitude() gradientMagnitude.SetInput(self.Image) gradientMagnitude.Update() boundedReciprocal = vtkvmtk.vtkvmtkBoundedReciprocalImageFilter() boundedReciprocal.SetInput(gradientMagnitude.GetOutput()) boundedReciprocal.Update() self.FeatureImage = vtk.vtkImageData() self.FeatureImage.DeepCopy(boundedReciprocal.GetOutput()) levelSetsFilter = None if self.Shape.find('2d') != -1: levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSet2DImageFilter() elif self.Shape.find('3d') != -1: levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSetImageFilter() else: levelSetsFilter = vtkvmtk.vtkvmtkGeodesicActiveContourLevelSetImageFilter() levelSetsFilter.SetInput(self.Image) levelSetsFilter.SetFeatureImage(boundedReciprocal.GetOutput()) levelSetsFilter.SetDerivativeSigma(0.0) levelSetsFilter.SetAutoGenerateSpeedAdvection(1) levelSetsFilter.SetNumberOfIterations(self.LevelSetsIterations) levelSetsFilter.SetPropagationScaling(0.0) levelSetsFilter.SetCurvatureScaling(self.CurvatureScaling) levelSetsFilter.SetAdvectionScaling(1.0) levelSetsFilter.SetIsoSurfaceValue(self.FWHMLevel) levelSetsFilter.SetInterpolateSurfaceLocation(1) levelSetsFilter.SetMaximumRMSError(1E-10) levelSetsFilter.Update() self.LevelSets = vtk.vtkImageData() self.LevelSets.DeepCopy(levelSetsFilter.GetOutput()) contourFilter = vtk.vtkMarchingContourFilter() contourFilter.SetInput(self.LevelSets) contourFilter.SetValue(0,0.0) contourFilter.Update() self.Contour = contourFilter.GetOutput() elif self.Method == 'fwhm': contourFilter = vtk.vtkMarchingContourFilter() contourFilter.SetInput(self.Image) contourFilter.SetValue(0,self.FWHMLevel) contourFilter.Update() self.Contour = contourFilter.GetOutput() else: self.PrintError('Unsupported method: choices are "levelsets", "fwhm".') return if self.Smoothing: smoothingFilter = vtk.vtkWindowedSincPolyDataFilter() smoothingFilter.SetInput(self.Contour) smoothingFilter.SetNumberOfIterations(self.SmoothingIterations) smoothingFilter.SetPassBand(self.SmoothingPassBand) smoothingFilter.Update() self.Contour = smoothingFilter.GetOutput() measurementFilter = None if self.Shape is 'thickplane2d': measurementFilter = femri2DPlaneThickness() elif self.Shape is 'cylinder2d': measurementFilter = femri2DCylinderThickness() elif self.Shape is 'hollowcylinder2d': measurementFilter = femri2DHollowCylinderThickness() elif self.Shape is 'cylinder3d': measurementFilter = femri3DCylinderThickness() else: self.PrintError('Unsupported shape: choices are "thickplane2d", "cylinder2d", "hollowcylinder2d", "cylinder3d".') return measurementFilter.Contour = self.Contour measurementFilter.Center = self.Center measurementFilter.TiltingAngle = math.radians(self.TiltingAngle) measurementFilter.RotationAngle = math.radians(self.RotationAngle) measurementFilter.Execute() if self.Shape is 'hollowcylinder2d': measurementFilter.ComputeAreas() self.InnerArea = measurementFilter.InnerArea self.OuterArea = measurementFilter.OuterArea self.Thickness = measurementFilter.Thickness self.Thickness3D = measurementFilter.Thickness3D self.Locations = measurementFilter.Locations self.Contour = measurementFilter.Contour self.OutputText('\n') self.OutputText('Thickness: ' + str(self.Thickness) + '\n') self.OutputText('Thickness3D: ' + str(self.Thickness3D) + '\n') self.OutputText('Locations: ' + str(self.Locations) + '\n') if self.Shape is 'hollowcylinder2d': self.OutputText('InnerArea: ' + str(self.InnerArea) + '\n') self.OutputText('OuterArea: ' + str(self.OuterArea) + '\n') self.OutputText('\n')
def create_surface_piece(filename, shape, dtype, mask_filename, mask_shape, mask_dtype, roi, spacing, mode, min_value, max_value, decimate_reduction, smooth_relaxation_factor, smooth_iterations, language, flip_image, from_binary, algorithm, imagedata_resolution, fill_border_holes): log_path = tempfile.mktemp('vtkoutput.txt') fow = vtk.vtkFileOutputWindow() fow.SetFileName(log_path) ow = vtk.vtkOutputWindow() ow.SetInstance(fow) pad_bottom = (roi.start == 0) pad_top = (roi.stop >= shape[0]) if fill_border_holes: padding = (1, 1, pad_bottom) else: padding = (0, 0, 0) if from_binary: mask = numpy.memmap(mask_filename, mode='r', dtype=mask_dtype, shape=mask_shape) if fill_border_holes: a_mask = pad_image(mask[roi.start + 1: roi.stop + 1, 1:, 1:], 0, pad_bottom, pad_top) else: a_mask = numpy.array(mask[roi.start + 1: roi.stop + 1, 1:, 1:]) image = converters.to_vtk(a_mask, spacing, roi.start, "AXIAL", padding=padding) del a_mask else: image = numpy.memmap(filename, mode='r', dtype=dtype, shape=shape) mask = numpy.memmap(mask_filename, mode='r', dtype=mask_dtype, shape=mask_shape) if fill_border_holes: a_image = pad_image(image[roi], numpy.iinfo(image.dtype).min, pad_bottom, pad_top) else: a_image = numpy.array(image[roi]) # if z_iadd: # a_image[0, 1:-1, 1:-1] = image[0] # if z_eadd: # a_image[-1, 1:-1, 1:-1] = image[-1] if algorithm == u'InVesalius 3.b2': a_mask = numpy.array(mask[roi.start + 1: roi.stop + 1, 1:, 1:]) a_image[a_mask == 1] = a_image.min() - 1 a_image[a_mask == 254] = (min_value + max_value) / 2.0 image = converters.to_vtk(a_image, spacing, roi.start, "AXIAL", padding=padding) gauss = vtk.vtkImageGaussianSmooth() gauss.SetInputData(image) gauss.SetRadiusFactor(0.3) gauss.ReleaseDataFlagOn() gauss.Update() del image image = gauss.GetOutput() del gauss del a_mask else: # if z_iadd: # origin = -spacing[0], -spacing[1], -spacing[2] # else: # origin = 0, -spacing[1], -spacing[2] image = converters.to_vtk(a_image, spacing, roi.start, "AXIAL", padding=padding) del a_image if imagedata_resolution: image = ResampleImage3D(image, imagedata_resolution) flip = vtk.vtkImageFlip() flip.SetInputData(image) flip.SetFilteredAxis(1) flip.FlipAboutOriginOn() flip.ReleaseDataFlagOn() flip.Update() # writer = vtk.vtkXMLImageDataWriter() # writer.SetFileName('/tmp/camboja.vti') # writer.SetInputData(flip.GetOutput()) # writer.Write() del image image = flip.GetOutput() del flip contour = vtk.vtkContourFilter() contour.SetInputData(image) if from_binary: contour.SetValue(0, 127) # initial threshold else: contour.SetValue(0, min_value) # initial threshold contour.SetValue(1, max_value) # final threshold # contour.ComputeScalarsOn() # contour.ComputeGradientsOn() # contour.ComputeNormalsOn() contour.ReleaseDataFlagOn() contour.Update() polydata = contour.GetOutput() del image del contour filename = tempfile.mktemp(suffix='_%d_%d.vtp' % (roi.start, roi.stop)) writer = vtk.vtkXMLPolyDataWriter() writer.SetInputData(polydata) writer.SetFileName(filename) writer.Write() print("Writing piece", roi, "to", filename) print("MY PID MC", os.getpid()) return filename
def _BuildPipeline(self): """_BuildPipeline - Builds the visualization pipeline""" image = component.getUtility(ICurrentImage) # update image (VTK-6 compatible) image.Update() # image reslice object reslice = vtk.vtkImageReslice() reslice.SetInterpolationModeToCubic() reslice.ReleaseDataFlagOn() reslice.SetInputConnection(image.GetOutputPort()) if self._transform: reslice.SetTransform(self._transform) # get extents, spacings, etc in_extent = image.GetExtent() in_spacing = image.GetSpacing() in_origin = image.GetOrigin() # get stencil data stencil_data = image.GetStencilData() # Set image resample factor f = self.gui.m_sliderSurfaceQuality.GetValue() / 100.0 if f == 0.0: f = 0.001 # Set surface decimation factor decf = self.gui.m_sliderDecimationFactor.GetValue() / 100.0 # Enable/Disable stencil usage if self.gui.m_checkBoxClipping.GetValue() is True and stencil_data: if vtk.vtkVersion().GetVTKMajorVersion() > 5: reslice.SetStencilData(stencil_data) else: reslice.SetStencil(stencil_data) reslice.SetBackgroundLevel(image.GetScalarRange()[0]) ext = stencil_data.GetExtent() else: ext = in_extent if vtk.vtkVersion().GetVTKMajorVersion() > 5: reslice.SetStencilData(None) else: reslice.SetStencil(None) # expand extent slightly - account for downsampling later too fudge = int(math.ceil(1.0 / f)) ext = [ext[0] - fudge, ext[1] + fudge, ext[2] - fudge, ext[3] + fudge, ext[4] - fudge, ext[5] + fudge] reslice.SetOutputExtent(ext) # set default origin/spacing -- these two lines work... reslice.SetOutputSpacing(in_spacing) reslice.SetOutputOrigin(in_origin) # do we need to downsample the image? if f < 1.0: resample = vtk.vtkImageResample() resample.SetInputConnection(reslice.GetOutputPort()) resample.ReleaseDataFlagOn() for i in range(3): resample.SetAxisMagnificationFactor(i, f) obj = resample else: obj = reslice # do we need to smooth the image? if self.gui.m_checkBoxImageSmoothing.GetValue() == True: smooth = vtk.vtkImageGaussianSmooth() smooth.SetStandardDeviation(1.0) smooth.ReleaseDataFlagOn() smooth.SetInputConnection(obj.GetOutputPort()) obj = smooth clip = vtk.vtkImageClip() clip.SetInputConnection(obj.GetOutputPort()) # setup contour filter cf = vtk.vtkMarchingCubes() cf.SetNumberOfContours(1) val = float(self.gui.m_textCtrlImageThreshold.GetValue()) cf.SetValue(0, val) cf.SetComputeScalars(0) cf.SetComputeNormals(0) cf.SetInputConnection(clip.GetOutputPort()) # decimate surface decimate = vtk.vtkDecimatePro() decimate.SetInputConnection(cf.GetOutputPort()) decimate.PreserveTopologyOn() decimate.SetTargetReduction(decf) # To cut down on memory consumption, we use the clip object # to process the image a chunk at a time. By default we # use 20 chunks -- but if the chunks are too small, we'll adjust this # number clip.UpdateInformation() ext = clip.GetInput().GetExtent() # main processing loop with wx.BusyCursor(): event.notify(ProgressEvent("Generating surface...", 0.0)) clip.SetOutputWholeExtent(ext[0], ext[1], ext[2], ext[3], ext[4], ext[5]) decimate.Update() event.notify(ProgressEvent("Generating surface...", 1.0)) # Create the rendered Geometry if not self._app_states[self._current_image_index].GetFactory(): self._app_states[self._current_image_index].SetFactory( vtkAtamai.SurfaceObjectFactory.SurfaceObjectFactory() ) self._app_states[self._current_image_index].GetFactory().SetInputConnection(decimate.GetOutputPort()) self._app_states[self._current_image_index].GetFactory().SetBackfaceProperty( self._app_states[self._current_image_index].GetFactory().GetProperty() ) self._app_states[self._current_image_index].GetFactory().NormalGenerationOn() self.SetSurfaceColor() self.GetMicroView().pane3D.ConnectActorFactory(self._app_states[self._current_image_index].GetFactory()) self._app_states[self._current_image_index]._disconnected = False # Update math values self.UpdateMathValues()
def renderIBC(filePrefix, imgLow, imgHigh): global picker, redCone, greenCone # # This example reads a volume dataset, extracts an isosurface that # represents the skin and displays it. # # The following reader is used to read a series of 2D slices (images) # that compose the volume. The slice dimensions are set, and the # pixel spacing. The data Endianness must also be specified. The reader # usese the FilePrefix in combination with the slice number to construct # filenames using the format FilePrefix.%d. (In this case the FilePrefix # is the root name of the file: quarter.) #vtkVolume16Reader v13R # v13R SetDataDimensions 1388 1040 # v13R SetDataByteOrderToBigEndian # v13R SetFilePrefix "IBC146h.R_s" # v13R SetImageRange 0 44 # v13R SetDataSpacing 1 1 2 # Image reader v13G = vtk.vtkTIFFReader() v13G.SetDataExtent(1, 1380, 1, 1030, imgLow, imgHigh) v13G.SetDataByteOrderToLittleEndian() v13G.SetFilePrefix(filePrefix) v13G.SetDataSpacing(0.1, 0.1, 0.6) # Gaussian Smoothing gaus_v13G = vtk.vtkImageGaussianSmooth() gaus_v13G.SetDimensionality(3) gaus_v13G.SetStandardDeviation(1) gaus_v13G.SetRadiusFactors(1, 1, 1) gaus_v13G.SetInput(v13G.GetOutput()) # Set up the volume rendering volumeMapper = vtk.vtkVolumeTextureMapper3D() volumeMapper.SetInput(v13G.GetOutput()) volume = vtk.vtkVolume() volume.SetMapper(volumeMapper) # Surface rendering bactExtractor = vtk.vtkMarchingCubes() bactExtractor.SetInputConnection(gaus_v13G.GetOutputPort()) bactExtractor.SetValue(0,20000) # bactNormals = vtk.vtkPolyDataNormals() # bactNormals.SetInputConnection(bactExtractor.GetOutputPort()) # bactNormals.SetFeatureAngle(90.0) # # bactStripper = vtk.vtkStripper() # bactStripper.SetInputConnection(bactNormals.GetOutputPort()) # bactLocator = vtk.vtkCellLocator() bactLocator.SetDataSet(bactExtractor.GetOutput()) bactLocator.LazyEvaluationOn() # # bactMapper = vtk.vtkPolyDataMapper() # bactMapper.SetInputConnection(bactStripper.GetOutputPort()) # bactMapper.ScalarVisibilityOff() # skinE_v13G = vtk.vtkContourFilter() ## skinE_v13G = vtk.vtkMarchingCubes() # skinE_v13G.UseScalarTreeOn() # skinE_v13G.SetInput(gaus_v13G.GetOutput()) # skinE_v13G.SetValue(0, 10000) # smooth_v13G = vtk.vtkSmoothPolyDataFilter() smooth_v13G.SetInput(bactExtractor.GetOutput()) smooth_v13G.SetNumberOfIterations(50) deci_v13G = vtk.vtkDecimatePro() deci_v13G.SetInput(smooth_v13G.GetOutput()) deci_v13G.SetTargetReduction(0.5) deci_v13G.PreserveTopologyOn() smoother_v13G = vtk.vtkSmoothPolyDataFilter() smoother_v13G.SetInput(deci_v13G.GetOutput()) smoother_v13G.SetNumberOfIterations(50) skinNormals_v13G = vtk.vtkPolyDataNormals() skinNormals_v13G.SetInput(deci_v13G.GetOutput()) skinNormals_v13G.SetFeatureAngle(60.0) skinStripper_v13G = vtk.vtkStripper() skinStripper_v13G.SetInput(skinNormals_v13G.GetOutput()) skinMapper_v13G = vtk.vtkPolyDataMapper() skinMapper_v13G.SetInput(skinStripper_v13G.GetOutput()) skinMapper_v13G.ScalarVisibilityOff() skin_v13G = vtk.vtkActor() skin_v13G.SetMapper(skinMapper_v13G) skin_v13G.GetProperty().SetDiffuseColor(0.2, 1, 0.2) skin_v13G.GetProperty().SetSpecular(.1) skin_v13G.GetProperty().SetSpecularPower(5) skin_v13G.GetProperty().SetOpacity(0.9) # It is convenient to create an initial view of the data. The FocalPoint # and Position form a vector direction. Later on (ResetCamera() method) # this vector is used to position the camera to look at the data in # this direction. aCamera = vtk.vtkCamera() aCamera.SetViewUp(0, 0, -1) aCamera.SetPosition(0, 1.1, 2) aCamera.SetFocalPoint(0, -0.25, 0) aCamera.ComputeViewPlaneNormal() # Actors are added to the renderer. An initial camera view is created. # The Dolly() method moves the camera towards the FocalPoint, # thereby enlarging the image. #aRenderer AddActor skin_v13R ren.AddActor(skin_v13G) ren.SetActiveCamera(aCamera) ren.ResetCamera() aCamera.Dolly(1.0) # 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. ren.ResetCameraClippingRange() # render renWin.Render() # CONE PICKER RENDER #--------------------------------------------------------- # the cone points along the -x axis coneSource = vtk.vtkConeSource() coneSource.CappingOn() coneSource.SetHeight(2) coneSource.SetRadius(1) coneSource.SetResolution(11) coneSource.SetCenter(1,0,0) coneSource.SetDirection(-1,0,0) coneMapper = vtk.vtkDataSetMapper() coneMapper.SetInputConnection(coneSource.GetOutputPort()) redCone = vtk.vtkActor() redCone.PickableOff() redCone.SetMapper(coneMapper) redCone.GetProperty().SetColor(1,0,0) greenCone = vtk.vtkActor() greenCone.PickableOff() greenCone.SetMapper(coneMapper) greenCone.GetProperty().SetColor(0,1,0) # Add the two cones (or just one, if you want) ren.AddViewProp(redCone) ren.AddViewProp(greenCone) #--------------------------------------------------------- # the picker picker = vtk.vtkVolumePicker() picker.SetTolerance(1e-6) picker.SetVolumeOpacityIsovalue(0.1) # locator is optional, but improves performance for large polydata picker.AddLocator(bactLocator) #--------------------------------------------------------- # custom interaction iren.AddObserver("MouseMoveEvent", MoveCursor) # END CONE PICKER RENDER # initialize and start the interactor iren.Initialize() iren.Start()
def CreateSurface(self, roi): if self.from_binary: a_mask = numpy.array(self.mask[roi.start + 1: roi.stop + 1, 1:, 1:]) image = converters.to_vtk(a_mask, self.spacing, roi.start, "AXIAL") del a_mask else: a_image = numpy.array(self.image[roi]) if self.algorithm == u'InVesalius 3.b2': a_mask = numpy.array(self.mask[roi.start + 1: roi.stop + 1, 1:, 1:]) a_image[a_mask == 1] = a_image.min() - 1 a_image[a_mask == 254] = (self.min_value + self.max_value) / 2.0 image = converters.to_vtk(a_image, self.spacing, roi.start, "AXIAL") gauss = vtk.vtkImageGaussianSmooth() gauss.SetInputData(image) gauss.SetRadiusFactor(0.3) gauss.ReleaseDataFlagOn() gauss.Update() del image image = gauss.GetOutput() del gauss del a_mask else: image = converters.to_vtk(a_image, self.spacing, roi.start, "AXIAL") del a_image if self.imagedata_resolution: # image = iu.ResampleImage3D(image, self.imagedata_resolution) image = ResampleImage3D(image, self.imagedata_resolution) flip = vtk.vtkImageFlip() flip.SetInputData(image) flip.SetFilteredAxis(1) flip.FlipAboutOriginOn() flip.ReleaseDataFlagOn() flip.Update() del image image = flip.GetOutput() del flip #filename = tempfile.mktemp(suffix='_%s.vti' % (self.pid)) #writer = vtk.vtkXMLImageDataWriter() #writer.SetInput(mask_vtk) #writer.SetFileName(filename) #writer.Write() #print "Writing piece", roi, "to", filename # Create vtkPolyData from vtkImageData #print "Generating Polydata" #if self.mode == "CONTOUR": #print "Contour" contour = vtk.vtkContourFilter() contour.SetInputData(image) #contour.SetInput(flip.GetOutput()) if self.from_binary: contour.SetValue(0, 127) # initial threshold else: contour.SetValue(0, self.min_value) # initial threshold contour.SetValue(1, self.max_value) # final threshold contour.ComputeScalarsOn() contour.ComputeGradientsOn() contour.ComputeNormalsOn() contour.ReleaseDataFlagOn() contour.Update() #contour.AddObserver("ProgressEvent", lambda obj,evt: # self.SendProgress(obj, _("Generating 3D surface..."))) polydata = contour.GetOutput() del image del contour #else: #mode == "GRAYSCALE": #mcubes = vtk.vtkMarchingCubes() #mcubes.SetInput(flip.GetOutput()) #mcubes.SetValue(0, self.min_value) #mcubes.SetValue(1, self.max_value) #mcubes.ComputeScalarsOff() #mcubes.ComputeGradientsOff() #mcubes.ComputeNormalsOff() #mcubes.AddObserver("ProgressEvent", lambda obj,evt: #self.SendProgress(obj, _("Generating 3D surface..."))) #polydata = mcubes.GetOutput() #triangle = vtk.vtkTriangleFilter() #triangle.SetInput(polydata) #triangle.AddObserver("ProgressEvent", lambda obj,evt: #self.SendProgress(obj, _("Generating 3D surface..."))) #triangle.Update() #polydata = triangle.GetOutput() #if self.decimate_reduction: ##print "Decimating" #decimation = vtk.vtkDecimatePro() #decimation.SetInput(polydata) #decimation.SetTargetReduction(0.3) #decimation.AddObserver("ProgressEvent", lambda obj,evt: #self.SendProgress(obj, _("Generating 3D surface..."))) ##decimation.PreserveTopologyOn() #decimation.SplittingOff() #decimation.BoundaryVertexDeletionOff() #polydata = decimation.GetOutput() self.pipe.send(None) filename = tempfile.mktemp(suffix='_%s.vtp' % (self.pid)) writer = vtk.vtkXMLPolyDataWriter() writer.SetInputData(polydata) writer.SetFileName(filename) writer.Write() print "Writing piece", roi, "to", filename del polydata del writer self.q_out.put(filename)
exit() # Check if the output directory exists if not os.path.isdir(output_folder_name): print("Error: output directory '" + output_folder_name + "' does not exist") exit() # Very important! The following values are for the virtual fish project voxel_size = [0.798, 0.798, 2.0] print("\nIMPORTANT: using the following voxel size: " + str(voxel_size[0]) + ", " + str(voxel_size[1]) + ", " + str(voxel_size[2])) print("the meshes will be saved in " + output_folder_name) # The VTK stuff img_reader = vtk.vtkTIFFReader() # Gaussian image filter img_smoother = vtk.vtkImageGaussianSmooth() img_smoother.SetDimensionality(3) img_smoother.SetRadiusFactor(3) # Marching cubes marching_cubes = vtk.vtkImageMarchingCubes() marching_cubes.SetValue(0, 128) # Mesh writer mesh_writer = vtk.vtkPLYWriter() # First of all, we collect the names of the tiff files tiff_file_names = list() # Get the file names of the tif images in the provided folder for file_name in os.listdir(input_folder_name): full_file_name = os.path.join(input_folder_name, file_name)
def updateRendering(self): """ Update the Rendering of this module """ method = self.parameters["Method"] self.setMethod(method) if self.volumeModule: self.volumeModule.function = vtk.vtkVolumeRayCastIsosurfaceFunction() self.volumeModule.function.SetIsoValue(self.parameters["IsoValue"]) self.volumeModule.showTimepoint(self.timepoint) return if not self.init: self.init = 1 self.mapper.ColorByArrayComponent(0, 0) self.mapper.AddObserver("ProgressEvent", lib.messenger.send) lib.messenger.connect(self.mapper, "ProgressEvent", self.updateProgress) dataUnit = self.getInputDataUnit(1) if not dataUnit: dataUnit = self.dataUnit dataCtf = dataUnit.getColorTransferFunction() if self.parameters["SolidColor"]: minval, maxval = dataCtf.GetRange() ctf = vtk.vtkColorTransferFunction() ctf.AddRGBPoint(int(minval), 0, 0, 0) r, g, b = dataCtf.GetColor(maxval) ctf.AddRGBPoint(int(minval) + 1, r, g, b) ctf.AddRGBPoint(maxval, r, g, b) else: ctf = dataCtf self.mapper.SetLookupTable(ctf) self.mapper.ScalarVisibilityOn() minVal, maxVal = self.data.GetScalarRange() self.setScalarRange(minVal, maxVal) self.mapper.SetScalarRange(minVal, maxVal) self.mapper.SetColorModeToMapScalars() opacity = self.parameters["Transparency"] opacity = (100 - opacity) / 100.0 Logging.info("Using opacity ", opacity, kw="visualizer") if opacity != 1: cullers = self.parent.getRenderer().GetCullers() cullers.InitTraversal() culler = cullers.GetNextItem() culler.SetSortingStyleToBackToFront() # print cullers, culler # self.parent.getRenderer().GetRenderWindow().SetAlphaBitPlanes(1) # self.parent.getRenderer().GetRenderWindow().SetMultiSamples(0) # self.parent.getRenderer().SetUseDepthPeeling(1) # self.parent.getRenderer().SetMaximumNumberOfPeels(100) # self.parent.getRenderer().SetOcclusionRatio(1.0) # print self.parent.getRenderer().GetLastRenderingUsedDepthPeeling() self.actor.GetProperty().SetOpacity(opacity) polyinput = self.getPolyDataInput(1) if polyinput: Logging.info("Using polydata input", kw="visualizer") self.mapper.SetInput(polyinput) VisualizationModule.updateRendering(self, polyinput) self.parent.Render() return x, y, z = self.dataUnit.getDimensions() input = self.getInput(1) input = optimize.optimize(image=input, updateExtent=(0, x - 1, 0, y - 1, 0, z - 1)) if self.parameters["Gaussian"]: Logging.info("Doing gaussian smoothing", kw="visualizer") if not self.smooth: self.smooth = vtk.vtkImageGaussianSmooth() self.smooth.SetInput(input) input = self.smooth.GetOutput() self.contour.SetInput(input) input = self.contour.GetOutput() multi = self.parameters["MultipleSurfaces"] if not multi: Logging.info("Using single isovalue=%d" % int(self.parameters["IsoValue"]), kw="visualizer") self.contour.SetValue(0, self.parameters["IsoValue"]) else: begin = self.parameters["SurfaceRangeBegin"] end = self.parameters["SurfaceRangeEnd"] n = self.parameters["SurfaceAmnt"] Logging.info("Generating %d values in range %d-%d" % (n, begin, end), kw="visualizer") self.contour.GenerateValues(n, begin, end) n = self.contour.GetNumberOfContours() for i in range(0, n): self.contour.SetValue(i, int(self.contour.GetValue(i))) # print self.contour # TODO: should decimateLevel and preserveTopology be instance variables? decimateLevel = self.parameters["Simplify"] preserveTopology = self.parameters["PreserveTopology"] if decimateLevel != 0: self.decimate.SetPreserveTopology(preserveTopology) if not preserveTopology: self.decimate.SplittingOn() self.decimate.BoundaryVertexDeletionOn() else: self.decimate.SplittingOff() self.decimate.BoundaryVertexDeletionOff() self.decimate.SetTargetReduction(decimateLevel / 100.0) Logging.info( "Decimating %.2f%%, preserve topology: %s" % (decimateLevel, preserveTopology), kw="visualizer" ) self.decimate.SetInput(input) input = self.decimate.GetOutput() if self.parameters["Normals"]: angle = self.parameters["FeatureAngle"] Logging.info("Generating normals at angle", angle, kw="visualizer") self.normals.SetFeatureAngle(angle) self.normals.SetInput(input) input = self.normals.GetOutput() self.mapper.SetInput(input) VisualizationModule.updateRendering(self, input) self.parent.Render()
def Render(self, volumeReader): """ This method attempts to tesselate the image data. :@type volumeReader: data.imageIO.base.VolumeImageReader :@param volumeReader: This object handles opening image data and passing it to the appropriate VTK image container :@rtype: 2-tuple :@return: The vtkActor created from tesselated image data and a vtkLocator for improving picking operations. """ if self.imageSetID is None: return self.volumeReader = volumeReader self.vtkReader = volumeReader.LoadVTKReader(self.dataSpacing) # Gaussian Smoothing self.gaussFilter = vtk.vtkImageGaussianSmooth() self.gaussFilter.SetDimensionality(3) self.gaussFilter.SetStandardDeviation(1) self.gaussFilter.SetRadiusFactors(1, 1, 1) self.gaussFilter.SetInput(self.vtkReader.GetOutput()) # VOI Extractor self.voi = vtk.vtkExtractVOI() self.voi.SetInputConnection(self.gaussFilter.GetOutputPort()) # self.voi.SetInputConnection(self.vtkReader.GetOutputPort()) self.voi.SetVOI(self.volumeReader.VolumeExtents) # Surface rendering self.bactExtractor = vtk.vtkMarchingCubes() self.bactExtractor.GenerateValues(1, self.isocontourLevel) self.bactExtractor.ComputeNormalsOff() self.bactExtractor.SetInputConnection(self.voi.GetOutputPort()) # surface rendering with dividing cubes # self.bactExtractor = vtk.vtkRecursiveDividingCubes() # self.bactExtractor.SetInputConnection(self.voi.GetOutputPort()) # self.bactExtractor.SetValue(self.isocontourLevel[0]) # self.bactExtractor.SetDistance(0.5) # self.bactExtractor.SetIncrement(2) # Smooth the mesh relaxedMesh = vtk.vtkSmoothPolyDataFilter() relaxedMesh.SetNumberOfIterations(50) relaxedMesh.SetInput(self.bactExtractor.GetOutput()) # Calculate normals meshNormals = vtk.vtkPolyDataNormals() meshNormals.SetFeatureAngle(60.0) meshNormals.SetInput(relaxedMesh.GetOutput()) # Restrip mesh after normal computation restrippedMesh = vtk.vtkStripper() restrippedMesh.SetInput(meshNormals.GetOutput()) # Convert mesh to graphics primitives self.meshMapper = vtk.vtkPolyDataMapper() self.meshMapper.ScalarVisibilityOff() self.meshMapper.SetInput(restrippedMesh.GetOutput()) # Finally create a renderable object "Actor" # that can be passed to the render window self.ibcActor = vtk.vtkActor() self.ibcActor.SetMapper(self.meshMapper) ibcColor = DataStore.GetImageSet(self.imageSetID).color self.ibcActor.GetProperty().SetDiffuseColor(ibcColor.r, ibcColor.g, ibcColor.b) self.ibcActor.GetProperty().SetSpecular(.1) self.ibcActor.GetProperty().SetSpecularPower(5) self.ibcActor.GetProperty().SetOpacity(1) self.ibcActor.SetVisibility(boolInt(self.visible)) self.renderer.AddActor(self.ibcActor) # Optional Locator to help the ray traced picker self.bactLocator = vtk.vtkCellLocator() self.bactLocator.SetDataSet(restrippedMesh.GetOutput()) self.bactLocator.LazyEvaluationOn() return self.bactLocator
def smoothSelectedSegment(self): try: # Get master volume image data import vtkSegmentationCorePython # Get modifier labelmap modifierLabelmap = self.scriptedEffect.defaultModifierLabelmap() selectedSegmentLabelmap = self.scriptedEffect.selectedSegmentLabelmap() smoothingMethod = self.scriptedEffect.parameter("SmoothingMethod") if smoothingMethod == GAUSSIAN: maxValue = 255 thresh = vtk.vtkImageThreshold() thresh.SetInputData(selectedSegmentLabelmap) thresh.ThresholdByLower(0) thresh.SetInValue(0) thresh.SetOutValue(maxValue) thresh.SetOutputScalarType(vtk.VTK_UNSIGNED_CHAR) standardDeviationMm = self.scriptedEffect.doubleParameter("GaussianStandardDeviationMm") gaussianFilter = vtk.vtkImageGaussianSmooth() gaussianFilter.SetInputConnection(thresh.GetOutputPort()) gaussianFilter.SetStandardDeviation(standardDeviationMm) gaussianFilter.SetRadiusFactor(4) thresh2 = vtk.vtkImageThreshold() thresh2.SetInputConnection(gaussianFilter.GetOutputPort()) thresh2.ThresholdByUpper(int(maxValue / 2)) thresh2.SetInValue(1) thresh2.SetOutValue(0) thresh2.SetOutputScalarType(selectedSegmentLabelmap.GetScalarType()) thresh2.Update() modifierLabelmap.DeepCopy(thresh2.GetOutput()) else: # size rounded to nearest odd number. If kernel size is even then image gets shifted. kernelSizePixel = self.getKernelSizePixel() if smoothingMethod == MEDIAN: # Median filter does not require a particular label value smoothingFilter = vtk.vtkImageMedian3D() smoothingFilter.SetInputData(selectedSegmentLabelmap) else: # We need to know exactly the value of the segment voxels, apply threshold to make force the selected label value labelValue = 1 backgroundValue = 0 thresh = vtk.vtkImageThreshold() thresh.SetInputData(selectedSegmentLabelmap) thresh.ThresholdByLower(0) thresh.SetInValue(backgroundValue) thresh.SetOutValue(labelValue) thresh.SetOutputScalarType(selectedSegmentLabelmap.GetScalarType()) smoothingFilter = vtk.vtkImageOpenClose3D() smoothingFilter.SetInputConnection(thresh.GetOutputPort()) if smoothingMethod == MORPHOLOGICAL_OPENING: smoothingFilter.SetOpenValue(labelValue) smoothingFilter.SetCloseValue(backgroundValue) else: # must be smoothingMethod == MORPHOLOGICAL_CLOSING: smoothingFilter.SetOpenValue(backgroundValue) smoothingFilter.SetCloseValue(labelValue) smoothingFilter.SetKernelSize(kernelSizePixel[0],kernelSizePixel[1],kernelSizePixel[2]) smoothingFilter.Update() modifierLabelmap.DeepCopy(smoothingFilter.GetOutput()) except IndexError: logging.error('apply: Failed to apply smoothing') # Apply changes self.scriptedEffect.modifySelectedSegmentByLabelmap(modifierLabelmap, slicer.qSlicerSegmentEditorAbstractEffect.ModificationModeSet)