def from_mask(self, mask): mask = np.array(mask.matrix[1:, 1:, 1:]) slic = sl.Slice() image = slic.matrix mask = to_vtk(mask, spacing=slic.spacing) image = to_vtk(image, spacing=slic.spacing) flip = vtk.vtkImageFlip() flip.SetInputData(image) flip.SetFilteredAxis(1) flip.FlipAboutOriginOn() flip.ReleaseDataFlagOn() flip.Update() image = flip.GetOutput() flip = vtk.vtkImageFlip() flip.SetInputData(mask) flip.SetFilteredAxis(1) flip.FlipAboutOriginOn() flip.ReleaseDataFlagOn() flip.Update() mask = flip.GetOutput() # Image self.refImage = image self._do_surface_creation(mask)
def processStlToImageData(dicomImageData, m_Origin, stlfilepaths): resultary = None for stlfilepath in stlfilepaths: if not os.path.exists(stlfilepath): continue polyData = readStlFile(stlfilepath) orginlData = dicomImageData spacing = orginlData.GetSpacing() outval = 0 whiteData = vtk.vtkImageData() whiteData.DeepCopy(orginlData) pointdata = whiteData.GetPointData() pointscalars = pointdata.GetScalars() # 通过矩阵计算将whiteData中点的颜色全部设置成白色 sc = vtk_to_numpy(pointscalars) sc = np.where(sc < 255, 255, 255) newscalars = numpy_to_vtk(sc) pointdata.SetScalars(newscalars) whiteData.Modified() pol2stenc = vtk.vtkPolyDataToImageStencil() pol2stenc.SetInputData(polyData) pol2stenc.SetOutputOrigin(m_Origin) pol2stenc.SetOutputSpacing(spacing) pol2stenc.SetOutputWholeExtent(orginlData.GetExtent()) pol2stenc.Update() imgstenc = vtk.vtkImageStencil() imgstenc.SetInputData(whiteData) imgstenc.SetStencilConnection(pol2stenc.GetOutputPort()) imgstenc.ReverseStencilOff() imgstenc.SetBackgroundValue(outval) imgstenc.Update() flip = vtk.vtkImageFlip() flip.SetInputData(imgstenc.GetOutput()) flip.SetFilteredAxes(1) flip.Update() flip2 = vtk.vtkImageFlip() flip2.SetInputData(flip.GetOutput()) flip2.SetFilteredAxes(2) flip2.Update() if resultary is None: resultary = [flip2.GetOutput()] else: resultary.append(flip2.GetOutput()) return resultary
def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._imageInput = None self._meshInput = None self._flipper = vtk.vtkImageFlip() self._flipper.SetFilteredAxis(1) module_utils.setup_vtk_object_progress(self, self._flipper, 'Flipping Y axis.') self._config.cpt_driver_path = \ 'd:\\misc\\stuff\\driver.bat' #'/home/cpbotha/build/cpt/3d/driver/driver.exe' self._config.max_distance = 5 config_list = [ ('CPT driver path', 'cpt_driver_path', 'base:str', 'filebrowser', 'Path to CPT driver executable', { 'fileMode': module_mixins.wx.OPEN, 'fileMask': 'All files (*.*)|*.*' }), ('Maximum distance', 'max_distance', 'base:float', 'text', 'The maximum (absolute) distance up to which the field is computed.' ) ] ScriptedConfigModuleMixin.__init__(self, config_list, {'Module (self)': self}) self.sync_module_logic_with_config()
def __init__(self, module_manager): # call parent constructor ModuleBase.__init__(self, module_manager) self._imageInput = None self._meshInput = None self._flipper = vtk.vtkImageFlip() self._flipper.SetFilteredAxis(1) module_utils.setup_vtk_object_progress( self, self._flipper, 'Flipping Y axis.') self._config.cpt_driver_path = \ 'd:\\misc\\stuff\\driver.bat' #'/home/cpbotha/build/cpt/3d/driver/driver.exe' self._config.max_distance = 5 config_list = [ ('CPT driver path', 'cpt_driver_path', 'base:str', 'filebrowser', 'Path to CPT driver executable', {'fileMode' : module_mixins.wx.OPEN, 'fileMask' : 'All files (*.*)|*.*'}), ('Maximum distance', 'max_distance', 'base:float', 'text', 'The maximum (absolute) distance up to which the field is computed.')] ScriptedConfigModuleMixin.__init__( self, config_list, {'Module (self)' : self}) self.sync_module_logic_with_config()
def create_mesh(label_pix, labels_to_use, inds_to_phys=None): # convert the numpy representation to VTK, so we can create a mesh # using marching cubes for display later vtk_import = vtkImageImport() vtk_import.SetImportVoidPointer(label_pix, True) vtk_import.SetDataScalarType(VTK_UNSIGNED_CHAR) vtk_import.SetNumberOfScalarComponents(1) vtk_import.SetDataExtent(0, label_pix.shape[2] - 1, 0, label_pix.shape[1] - 1, 0, label_pix.shape[0] - 1) vtk_import.SetWholeExtent(0, label_pix.shape[2] - 1, 0, label_pix.shape[1] - 1, 0, label_pix.shape[0] - 1) vtk_import.Update() flipper = vtkImageFlip() flipper.SetInputData(vtk_import.GetOutput()) flipper.SetFilteredAxis(1) flipper.FlipAboutOriginOff() flipper.Update() vtk_img = flipper.GetOutput() marching_cubes = vtkDiscreteMarchingCubes() marching_cubes.SetInputData(vtk_img) num_labels_to_use = len(labels_to_use) marching_cubes.SetNumberOfContours(num_labels_to_use) for i in range(num_labels_to_use): marching_cubes.SetValue(i, labels_to_use[i]) marching_cubes.Update() smoother = vtkWindowedSincPolyDataFilter() smoother.SetInputData(marching_cubes.GetOutput()) smoother.SetNumberOfIterations(25) smoother.SetPassBand(0.1) smoother.SetBoundarySmoothing(False) smoother.SetFeatureEdgeSmoothing(False) smoother.SetFeatureAngle(120.0) smoother.SetNonManifoldSmoothing(True) smoother.NormalizeCoordinatesOn() smoother.Update() mesh_reduce = vtkQuadricDecimation() mesh_reduce.SetInputData(smoother.GetOutput()) mesh_reduce.SetTargetReduction(0.25) mesh_reduce.Update() vertex_xform = np.mat(np.eye(4)) vertex_xform[1, 1] = -1 vertex_xform[1, 3] = label_pix.shape[1] + 1 vertex_xform = inds_to_phys * vertex_xform return xform_mesh(mesh_reduce.GetOutput(), vertex_xform)
def mirror(self, axis="x"): """ Mirror flip along one of the cartesian axes. .. note:: ``axis='n'``, will flip only mesh normals. |mirror| |mirror.py|_ """ img = self.imagedata() ff = vtk.vtkImageFlip() ff.SetInputData(img) if axis.lower() == "x": ff.SetFilteredAxis(0) elif axis.lower() == "y": ff.SetFilteredAxis(1) elif axis.lower() == "z": ff.SetFilteredAxis(2) else: colors.printc( "\times Error in mirror(): mirror must be set to x, y, z or n.", c='r') raise RuntimeError() ff.Update() return self._update(ff.GetOutput())
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkImageFlip(), 'Processing.', ('vtkImageData', 'vtkImageStencilData'), ('vtkImageData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def tomo_poly_iso(tomo, th, flp, dec=None): # Marching cubes configuration march = vtk.vtkMarchingCubes() # tomo_vtk = numpy_support.numpy_to_vtk(num_array=tomo.ravel(), deep=True, array_type=vtk.VTK_FLOAT) tomo_vtk = ps.disperse_io.numpy_to_vti(tomo) # Flipping if flp: fliper = vtk.vtkImageFlip() fliper.SetFilteredAxis(2) fliper.SetInputData(tomo_vtk) fliper.Update() tomo_vtk = fliper.GetOutput() march.SetInputData(tomo_vtk) march.SetValue(0, th) # Running Marching Cubes march.Update() hold_poly = march.GetOutput() # Decimation filter if dec is not None: tr_dec = vtk.vtkDecimatePro() tr_dec.SetInputData(hold_poly) tr_dec.SetTargetReduction(dec) tr_dec.Update() hold_poly = tr_dec.GetOutput() return hold_poly
def highlight_voxels_3D(self, coords): self.viewer.ren_iso.RemoveVolume(self.viewer.vol) newimage = vtk.vtkImageData() newimage.SetSpacing(self.viewer.volumedata.GetSpacing()) newimage.SetOrigin(self.viewer.volumedata.GetOrigin()) newimage.SetDimensions(self.viewer.volumedata.GetDimensions()) newimage.SetExtent(self.viewer.volumedata.GetExtent()) newimage.SetNumberOfScalarComponents(1) newimage.SetScalarTypeToDouble() newimage.AllocateScalars() for p in coords: newimage.SetScalarComponentFromDouble(p[0], p[1], p[2], 0, p[3]) shift_scale = vtk.vtkImageShiftScale() shift_scale.SetInput(newimage) shift_scale.SetOutputScalarTypeToUnsignedChar() shift_scale.Update() flipYFilter = vtk.vtkImageFlip() flipYFilter.SetFilteredAxis(1) flipYFilter.SetInput(shift_scale.GetOutput()) flipYFilter.Update() self.viewer.volMapper.SetInput(flipYFilter.GetOutput()) self.viewer.ren_iso.AddVolume(self.viewer.vol) self.viewer.refresh_3d()
def ShowTextureOnModel(self, modelNode, textureImageNode): modelDisplayNode=modelNode.GetDisplayNode() modelDisplayNode.SetBackfaceCulling(0) textureImageFlipVert=vtk.vtkImageFlip() textureImageFlipVert.SetFilteredAxis(1) textureImageFlipVert.SetInputConnection(textureImageNode.GetImageDataConnection()) modelDisplayNode.SetTextureImageDataConnection(textureImageFlipVert.GetOutputPort())
def getSphericalMap( self, **args ): thetaResolution = args.get( "thetaRes", 32 ) phiResolution = args.get( "phiRes", 32 ) radius = args.get( "radius", 100 ) if self.sphereActor == None: self.sphere = vtk.vtkSphereSource() self.sphere.SetThetaResolution( thetaResolution ) self.sphere.SetPhiResolution( phiResolution ) self.sphere.SetRadius( radius ) self.sphere.SetEndTheta( 359.999 ) mesh = self.sphere.GetOutput() self.sphereTexmapper = vtk.vtkTextureMapToSphere() if vtk.VTK_MAJOR_VERSION <= 5: self.sphereTexmapper.SetInput(mesh) else: self.sphereTexmapper.SetInputData(mesh) self.sphereTexmapper.PreventSeamOff() self.sphereMapper = vtk.vtkPolyDataMapper() self.sphereMapper.SetInputConnection(self.sphereTexmapper.GetOutputPort()) imageFlipper = vtk.vtkImageFlip() if vtk.VTK_MAJOR_VERSION <= 5: imageFlipper.SetInput(self.sphericalBaseImage) else: imageFlipper.SetInputData(self.sphericalBaseImage) imageFlipper.SetFilteredAxis( 1 ) self.sphereTexture = vtk.vtkTexture() self.sphereTexture.SetInputConnection( imageFlipper.GetOutputPort() ) self.sphereActor = vtk.vtkActor() self.sphereActor.SetMapper(self.sphereMapper) self.sphereActor.SetTexture(self.sphereTexture) # self.sphereActor.GetProperty().SetOpacity( self.map_opacity ) self.sphereActor.SetVisibility( False ) return self.sphereActor
def flipVTKImageData(image, image_flip): '''flip image for visualization. Parameters ---------- image : vtkImageData image_flip : tuple, (-1 1 1) means flip x-axis Returns ------- imageOut : vtkImageData, flipped image ''' if image_flip[0] == 1 and image_flip[1] == 1 and image_flip[2] == 1: return image imageOut = vtk.vtkImageData() imageOut.DeepCopy(image) for i, ff in enumerate(image_flip): if ff == -1: flipFilter = vtk.vtkImageFlip() flipFilter.SetInputData(imageOut) flipFilter.SetFilteredAxis(i) flipFilter.Update() imageOut = flipFilter.GetOutput() return imageOut
def read_dicom(filename): """ dicomデータの読み込み. Parameters ---------- filename : string dicomデータのディレクトリへのパスを指定. Returns ------- image : vtk型のimage画像. """ reader = vtk.vtkDICOMImageReader() reader.SetDirectoryName(filename) reader.Update() # vtkとDICOM画像において,空間座標系が違うため変換が必要. # 詳細は,“https://itk.org/Wiki/Proposals:Orientation” flip = vtk.vtkImageFlip() flip.SetFilteredAxis(1) flip.SetInputData(reader.GetOutput()) flip.SetOutputSpacing(reader.GetDataSpacing()) flip.Update() image = flip return image
def reverseGridAxii(pdi, axes=(True,True,True), pdo=None): """ Reverses data along different axial directions TODO: Description """ if pdo is None: pdo = vtk.vtkImageData() # Copy over input to output to be flipped around # Deep copy keeps us from messing with the input data pdo.DeepCopy(pdi) # Iterate over all array in the PointData for j in range(pdo.GetPointData().GetNumberOfArrays()): # Swap Scalars with all Arrays in PointData so that all data gets filtered scal = pdo.GetPointData().GetScalars() arr = pdi.GetPointData().GetArray(j) pdo.GetPointData().SetScalars(arr) pdo.GetPointData().AddArray(scal) for i in range(3): # Rotate ImageData on each axis if needed # Go through each axis and rotate if needed # Note: ShallowCopy is necessary!! if axes[i]: flipper = vtk.vtkImageFlip() flipper.SetInputData(pdo) flipper.SetFilteredAxis(i) flipper.Update() flipper.UpdateWholeExtent() pdo.ShallowCopy(flipper.GetOutput()) return pdo
def InputImageWidget(self, pubsub_evt): widget = pubsub_evt.data flip = vtk.vtkImageFlip() flip.SetInput(self.window_level.GetOutput()) flip.SetFilteredAxis(1) flip.FlipAboutOriginOn() flip.Update() widget.SetInput(flip.GetOutput())
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkImageFlip(), 'Processing.', ('vtkImageData', 'vtkImageStencilData'), ('vtkImageData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def convertTextureToPointAttribute(self, modelNode, textureImageNode): polyData = modelNode.GetPolyData() textureImageFlipVert = vtk.vtkImageFlip() textureImageFlipVert.SetFilteredAxis(1) textureImageFlipVert.SetInputConnection( textureImageNode.GetImageDataConnection()) textureImageFlipVert.Update() textureImageData = textureImageFlipVert.GetOutput() pointData = polyData.GetPointData() tcoords = pointData.GetTCoords() numOfPoints = pointData.GetNumberOfTuples() assert numOfPoints == tcoords.GetNumberOfTuples( ), "Number of texture coordinates does not equal number of points" textureSamplingPointsUv = vtk.vtkPoints() textureSamplingPointsUv.SetNumberOfPoints(numOfPoints) for pointIndex in range(numOfPoints): uv = tcoords.GetTuple2(pointIndex) textureSamplingPointsUv.SetPoint(pointIndex, uv[0], uv[1], 0) textureSamplingPointDataUv = vtk.vtkPolyData() uvToXyz = vtk.vtkTransform() textureImageDataSpacingSpacing = textureImageData.GetSpacing() textureImageDataSpacingOrigin = textureImageData.GetOrigin() textureImageDataSpacingDimensions = textureImageData.GetDimensions() uvToXyz.Scale( textureImageDataSpacingDimensions[0] / textureImageDataSpacingSpacing[0], textureImageDataSpacingDimensions[1] / textureImageDataSpacingSpacing[1], 1) uvToXyz.Translate(textureImageDataSpacingOrigin) textureSamplingPointDataUv.SetPoints(textureSamplingPointsUv) transformPolyDataToXyz = vtk.vtkTransformPolyDataFilter() transformPolyDataToXyz.SetInputData(textureSamplingPointDataUv) transformPolyDataToXyz.SetTransform(uvToXyz) probeFilter = vtk.vtkProbeFilter() probeFilter.SetInputConnection(transformPolyDataToXyz.GetOutputPort()) probeFilter.SetSourceData(textureImageData) probeFilter.Update() rgbPoints = probeFilter.GetOutput().GetPointData().GetArray( 'ImageScalars') colorArray = vtk.vtkDoubleArray() colorArray.SetName('Color') colorArray.SetNumberOfComponents(3) colorArray.SetNumberOfTuples(numOfPoints) for pointIndex in range(numOfPoints): rgb = rgbPoints.GetTuple3(pointIndex) colorArray.SetTuple3(pointIndex, rgb[0] / 255., rgb[1] / 255., rgb[2] / 255.) colorArray.Modified() pointData.AddArray(colorArray) pointData.Modified() polyData.Modified()
def read_image(self,itk_image): # convert ITK image to VTK image, set image type to signed short (16-bits/pixel) vtk_image = itk.ImageToVTKImageFilter[itk.Image.SS3].New() vtk_image.SetInput(itk_image.GetOutput()) vtk_image.Update() # the coordinates of ITK and VTK are inconsistent, so flip the y-axis of the image flip = vtk.vtkImageFlip() flip.SetInputData(vtk_image.GetOutput()) flip.SetFilteredAxes(1) flip.Update() self.__image = flip
def mirror(self, axis="x"): """Mirror picture along x or y axis. Same as flip().""" ff = vtk.vtkImageFlip() ff.SetInputData(self.inputdata()) if axis.lower() == "x": ff.SetFilteredAxis(0) elif axis.lower() == "y": ff.SetFilteredAxis(1) else: colors.printc("Error in mirror(): mirror must be set to x or y.", c='r') raise RuntimeError() ff.Update() return self._update(ff.GetOutput())
def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageFlip = vtk.vtkImageFlip() self._imageFlip.SetFilteredAxis(2) self._imageFlip.GetOutput().SetUpdateExtentToWholeExtent() module_utils.setup_vtk_object_progress(self, self._imageFlip, 'Flipping image') NoConfigModuleMixin.__init__(self, {'vtkImageFlip': self._imageFlip}) self.sync_module_logic_with_config()
def getDataSet(self, i, raw=0): """ @return Timepoint i @param i The timepoint to return """ data = self.getTimepoint(i) if self.isRGB and self.numberOfComponents == 4: extract = vtk.vtkImageExtractComponents() extract.SetComponents(0, 1, 2) extract.SetInput(data) data = extract.GetOutput() if self.flipVertically: flip = vtk.vtkImageFlip() flip.SetFilteredAxis(1) flip.SetInput(data) data = flip.GetOutput() if self.flipHorizontally: flip = vtk.vtkImageFlip() flip.SetFilteredAxis(0) flip.SetInput(data) data = flip.GetOutput() return data
def getDataSet(self, i, raw = 0): """ @return Timepoint i @param i The timepoint to return """ data = self.getTimepoint(i) if self.isRGB and self.numberOfComponents == 4: extract = vtk.vtkImageExtractComponents() extract.SetComponents(0, 1, 2) extract.SetInput(data) data = extract.GetOutput() if self.flipVertically: flip = vtk.vtkImageFlip() flip.SetFilteredAxis(1) flip.SetInput(data) data = flip.GetOutput() if self.flipHorizontally: flip = vtk.vtkImageFlip() flip.SetFilteredAxis(0) flip.SetInput(data) data = flip.GetOutput() return data
def UpdateSlice3D(self, pubsub_evt): widget, orientation = pubsub_evt.data img = self.buffer_slices[orientation].vtk_image original_orientation = Project().original_orientation cast = vtk.vtkImageCast() cast.SetInput(img) cast.SetOutputScalarTypeToDouble() cast.ClampOverflowOn() cast.Update() # if (original_orientation == const.AXIAL): flip = vtk.vtkImageFlip() flip.SetInput(cast.GetOutput()) flip.SetFilteredAxis(1) flip.FlipAboutOriginOn() flip.Update() widget.SetInput(flip.GetOutput())
def ReadCubeMap(folderRoot, fileRoot, ext, key): """ Read the cube map. :param folderRoot: The folder where the cube maps are stored. :param fileRoot: The root of the individual cube map file names. :param ext: The extension of the cube map files. :param key: The key to data used to build the full file name. :return: The cubemap texture. """ # A map of cube map naming conventions and the corresponding file name # components. fileNames = { 0: ['right', 'left', 'top', 'bottom', 'front', 'back'], 1: ['posx', 'negx', 'posy', 'negy', 'posz', 'negz'], 2: ['-px', '-nx', '-py', '-ny', '-pz', '-nz'], 3: ['0', '1', '2', '3', '4', '5'] } if key in fileNames: fns = fileNames[key] else: print('ReadCubeMap(): invalid key, unable to continue.') sys.exit() texture = vtk.vtkTexture() texture.CubeMapOn() # Build the file names. for i in range(0, len(fns)): fns[i] = Path(str(folderRoot) + fileRoot + fns[i]).with_suffix(ext) if not fns[i].is_file(): print('Nonexistent texture file:', fns[i]) return texture i = 0 for fn in fns: # Read the images readerFactory = vtk.vtkImageReader2Factory() imgReader = readerFactory.CreateImageReader2(str(fn)) imgReader.SetFileName(str(fn)) flip = vtk.vtkImageFlip() flip.SetInputConnection(imgReader.GetOutputPort()) flip.SetFilteredAxis(1) # flip y axis texture.SetInputConnection(i, flip.GetOutputPort(0)) i += 1 texture.MipmapOn() texture.InterpolateOn() return texture
def __init__(self, module_manager): # initialise our base class ModuleBase.__init__(self, module_manager) self._imageFlip = vtk.vtkImageFlip() self._imageFlip.SetFilteredAxis(2) self._imageFlip.GetOutput().SetUpdateExtentToWholeExtent() module_utils.setup_vtk_object_progress(self, self._imageFlip, 'Flipping image') NoConfigModuleMixin.__init__( self, {'vtkImageFlip' : self._imageFlip}) self.sync_module_logic_with_config()
def showSlice(self, vtkImageData, preserveState): '''Shows slice of image.''' self.producer.SetOutput(vtkImageData) self.reslice.SetInputConnection(self.producer.GetOutputPort()) self.reslice.SetResliceAxesDirectionCosines((1,0,0), (0,1,0), (0,0,1)) self.reslice.SetOutputDimensionality(2) self.reslice.SetInterpolationModeToLinear() flip = vtk.vtkImageFlip() # flip over y axis flip.SetFilteredAxis(1) flip.SetInputConnection(self.reslice.GetOutputPort()) # create lookup table for intensity -> color table = vtk.vtkLookupTable() table.SetRange(vtkImageData.GetScalarRange()) table.SetValueRange(0, 1) # no saturation table.SetSaturationRange(0, 0) table.SetRampToLinear() table.Build() # map lookup table to colors colors = vtk.vtkImageMapToColors() colors.SetLookupTable(table) colors.SetInputConnection(flip.GetOutputPort()) # preserve image property imageProperty = None if preserveState and self.sliceActor: imageProperty = self.sliceActor.GetProperty() self.sliceActor = vtk.vtkImageActor() self.sliceActor.GetMapper().SetInputConnection(colors.GetOutputPort()) # restore image property if preserveState and imageProperty: self.sliceActor.SetProperty(imageProperty) self.sliceRenderer.RemoveAllViewProps() self.sliceRenderer.AddActor(self.sliceActor) self.sliceRenderer.ResetCamera()
def get_vtk_image(self): importer = vtk.vtkImageImport() importer.SetDataSpacing(1,1,1) importer.SetDataOrigin(0,0,0) importer.SetWholeExtent(0, self.im.shape[1] - 1, 0, self.im.shape[0] - 1, 0, 0) importer.SetDataExtentToWholeExtent() importer.SetDataScalarTypeToUnsignedChar() importer.SetNumberOfScalarComponents(self.im.shape[2]) importer.SetImportVoidPointer(self.im) importer.Update() flipY = vtk.vtkImageFlip() flipY.SetFilteredAxis(1) flipY.SetInputConnection(importer.GetOutputPort()) flipY.Update() yActor = vtk.vtkImageActor() yActor.SetInput(flipY.GetOutput()) return yActor
def highlight_voxels_2D(self, coords): newimage = vtk.vtkImageData() newimage.SetSpacing(self.viewer.doseplans["p1"].GetSpacing()) newimage.SetOrigin(self.viewer.doseplans["p1"].GetOrigin()) newimage.SetDimensions(self.viewer.doseplans["p1"].GetDimensions()) newimage.SetExtent(self.viewer.doseplans["p1"].GetExtent()) newimage.SetNumberOfScalarComponents(1) newimage.SetScalarTypeToDouble() newimage.AllocateScalars() for p in coords: newimage.SetScalarComponentFromDouble(p[0], p[1], p[2], 0, 60) flipYFilter = vtk.vtkImageFlip() flipYFilter.SetFilteredAxis(1) flipYFilter.SetInput(newimage) flipYFilter.Update() self.viewer.refresh_2d(flipYFilter.GetOutput())
def get_vtk_image(self): importer = vtk.vtkImageImport() importer.SetDataSpacing(1, 1, 1) importer.SetDataOrigin(0, 0, 0) importer.SetWholeExtent(0, self.im.shape[1] - 1, 0, self.im.shape[0] - 1, 0, 0) importer.SetDataExtentToWholeExtent() importer.SetDataScalarTypeToUnsignedChar() importer.SetNumberOfScalarComponents(self.im.shape[2]) importer.SetImportVoidPointer(self.im) importer.Update() flipY = vtk.vtkImageFlip() flipY.SetFilteredAxis(1) flipY.SetInputConnection(importer.GetOutputPort()) flipY.Update() yActor = vtk.vtkImageActor() yActor.SetInput(flipY.GetOutput()) return yActor
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 Update(self): source = self._input output = vtk.vtkImageData() self._output = vtk.vtkImageData() if not any(self._flip): output = source for i in range(3): if self._flip[i]: transpose = vtk.vtkImageFlip() transpose.SetFilteredAxis(i) if self._flipOrigin[i]: transpose.FlipAboutOriginOn() else: transpose.FlipAboutOriginOff() transpose.SetInput(source) transpose.Update() output = transpose.GetOutput() source = output self._output = output
def getSphericalMap(self, **args): thetaResolution = args.get("thetaRes", 32) phiResolution = args.get("phiRes", 32) radius = args.get("radius", 100) if self.sphereActor == None: self.sphere = vtk.vtkSphereSource() self.sphere.SetThetaResolution(thetaResolution) self.sphere.SetPhiResolution(phiResolution) self.sphere.SetRadius(radius) self.sphere.SetEndTheta(359.999) self.sphere.Update() mesh = self.sphere.GetOutput() self.sphereTexmapper = vtk.vtkTextureMapToSphere() if vtk.VTK_MAJOR_VERSION <= 5: self.sphereTexmapper.SetInput(mesh) else: self.sphereTexmapper.SetInputData(mesh) self.sphereTexmapper.PreventSeamOff() self.sphereMapper = vtk.vtkPolyDataMapper() self.sphereMapper.SetInputConnection( self.sphereTexmapper.GetOutputPort()) imageFlipper = vtk.vtkImageFlip() if vtk.VTK_MAJOR_VERSION <= 5: imageFlipper.SetInput(self.sphericalBaseImage) else: imageFlipper.SetInputData(self.sphericalBaseImage) imageFlipper.SetFilteredAxis(1) self.sphereTexture = vtk.vtkTexture() self.sphereTexture.SetInputConnection(imageFlipper.GetOutputPort()) self.sphereActor = vtk.vtkActor() self.sphereActor.SetMapper(self.sphereMapper) self.sphereActor.SetTexture(self.sphereTexture) # self.sphereActor.GetProperty().SetOpacity( self.map_opacity ) self.sphereActor.SetVisibility(False) return self.sphereActor
def read_nifti(filename): """ NIfTI-1(.nii)の単一ファイル形式の読み込み. Parameters ---------- filename : string .niiまたは.nii.gz形式のパスを指定. Returns ------- image : vtk型のimage画像. """ reader = vtk.vtkNIFTIImageReader() reader.SetFileName(filename) reader.Update() flip = vtk.vtkImageFlip() flip.SetFilteredAxis(2) flip.SetInputData(reader.GetOutput()) flip.Update() image = flip return image
plt.show() ''' dataImporter = vtk.vtkImageImport() data_string = avg_matrix.tostring() dataImporter.CopyImportVoidPointer(data_string, len(data_string)) dataImporter.SetDataScalarTypeToFloat() dataImporter.SetNumberOfScalarComponents(1) dataImporter.SetDataExtent(0,119,0,119,0,119) dataImporter.SetWholeExtent(0,119,0,119,0,119) dataImporter.SetDataOrigin(-30.000000, -15.000000, -30.000000) dataImporter.SetDataSpacing(.252101, .252101, .252101) dataImporter.Update() flip = vtk.vtkImageFlip() ''' http://vtkusers.public.kitware.narkive.com/vxTpmeIS/is-there-a-filter-to-convert-float-volume-to-unsigned-int vtkImageShiftScale should do what you want. Set the shift value so that is moves your min scalar value to 0, set the scale so that the max scalar value (after being shifted) will become 65535. Then set the output scalar type to unsigned short. http://www.vtk.org/doc/nightly/html/classvtkImageShiftScale.html#details shift and scale an input image With vtkImageShiftScale Pixels are shifted (a constant value added) and then scaled (multiplied by a scalar. As a convenience, this class allows
def LoadVolume(self): proj = prj.Project() #image = imagedata_utils.to_vtk(n_array, spacing, slice_number, orientation) if not self.loaded_image: self.LoadImage() self.loaded_image = 1 image = self.image number_filters = len(self.config['convolutionFilters']) if (prj.Project().original_orientation == const.AXIAL): flip_image = True else: flip_image = False #if (flip_image): update_progress = vtk_utils.ShowProgress(2 + number_filters) # Flip original vtkImageData flip = vtk.vtkImageFlip() flip.SetInputData(image) flip.SetFilteredAxis(1) flip.FlipAboutOriginOn() # flip.ReleaseDataFlagOn() flip_ref = weakref.ref(flip) flip_ref().AddObserver( "ProgressEvent", lambda obj, evt: update_progress(flip_ref(), "Rendering...")) flip.Update() image = flip.GetOutput() scale = image.GetScalarRange() self.scale = scale cast = vtk.vtkImageShiftScale() cast.SetInputData(image) cast.SetShift(abs(scale[0])) cast.SetOutputScalarTypeToUnsignedShort() # cast.ReleaseDataFlagOn() cast_ref = weakref.ref(cast) cast_ref().AddObserver( "ProgressEvent", lambda obj, evt: update_progress(cast_ref(), "Rendering...")) cast.Update() image2 = cast self.imagedata = image2 if self.config['advancedCLUT']: self.Create16bColorTable(scale) self.CreateOpacityTable(scale) else: self.Create8bColorTable(scale) self.Create8bOpacityTable(scale) image2 = self.ApplyConvolution(image2.GetOutput(), update_progress) self.final_imagedata = image2 # Changed the vtkVolumeRayCast to vtkFixedPointVolumeRayCastMapper # because it's faster and the image is better # TODO: To test if it's true. if const.TYPE_RAYCASTING_MAPPER: volume_mapper = vtk.vtkVolumeRayCastMapper() #volume_mapper.AutoAdjustSampleDistancesOff() #volume_mapper.SetInput(image2) #volume_mapper.SetVolumeRayCastFunction(composite_function) #volume_mapper.SetGradientEstimator(gradientEstimator) volume_mapper.IntermixIntersectingGeometryOn() self.volume_mapper = volume_mapper else: if int(ses.Session().rendering) == 0: volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper() #volume_mapper.AutoAdjustSampleDistancesOff() self.volume_mapper = volume_mapper volume_mapper.IntermixIntersectingGeometryOn() else: volume_mapper = vtk.vtkGPUVolumeRayCastMapper() volume_mapper.UseJitteringOn() self.volume_mapper = volume_mapper self.SetTypeRaycasting() volume_mapper.SetInputData(image2) # TODO: Look to this #volume_mapper_hw = vtk.vtkVolumeTextureMapper3D() #volume_mapper_hw.SetInput(image2) #Cut Plane #CutPlane(image2, volume_mapper) #self.color_transfer = color_transfer volume_properties = vtk.vtkVolumeProperty() #volume_properties.IndependentComponentsOn() volume_properties.SetInterpolationTypeToLinear() volume_properties.SetColor(self.color_transfer) try: volume_properties.SetScalarOpacity(self.opacity_transfer_func) except NameError: pass if not self.volume_mapper.IsA("vtkGPUVolumeRayCastMapper"): # Using these lines to improve the raycasting quality. These values # seems related to the distance from ray from raycasting. # TODO: Need to see values that improve the quality and don't decrease # the performance. 2.0 seems to be a good value to pix_diag pix_diag = 2.0 volume_mapper.SetImageSampleDistance(0.25) volume_mapper.SetSampleDistance(pix_diag / 5.0) volume_properties.SetScalarOpacityUnitDistance(pix_diag) self.volume_properties = volume_properties self.SetShading() volume = vtk.vtkVolume() volume.SetMapper(volume_mapper) volume.SetProperty(volume_properties) self.volume = volume colour = self.GetBackgroundColour() self.exist = 1 if self.plane: self.plane.SetVolumeMapper(volume_mapper) Publisher.sendMessage('Load volume into viewer', volume=volume, colour=colour, ww=self.ww, wl=self.wl) del flip del cast
def create_volume(self): if self._actor is None: if int(ses.Session().rendering) == 0: self._volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper() #volume_mapper.AutoAdjustSampleDistancesOff() self._volume_mapper.IntermixIntersectingGeometryOn() pix_diag = 2.0 self._volume_mapper.SetImageSampleDistance(0.25) self._volume_mapper.SetSampleDistance(pix_diag / 5.0) else: self._volume_mapper = vtk.vtkGPUVolumeRayCastMapper() self._volume_mapper.UseJitteringOn() if LooseVersion(vtk.vtkVersion().GetVTKVersion() ) > LooseVersion('8.0'): self._volume_mapper.SetBlendModeToIsoSurface() # else: # isosurfaceFunc = vtk.vtkVolumeRayCastIsosurfaceFunction() # isosurfaceFunc.SetIsoValue(127) # self._volume_mapper = vtk.vtkVolumeRayCastMapper() # self._volume_mapper.SetVolumeRayCastFunction(isosurfaceFunc) self._flip = vtk.vtkImageFlip() self._flip.SetInputData(self.mask.imagedata) self._flip.SetFilteredAxis(1) self._flip.FlipAboutOriginOn() self._volume_mapper.SetInputConnection(self._flip.GetOutputPort()) self._volume_mapper.Update() r, g, b = self.colour self._color_transfer = vtk.vtkColorTransferFunction() self._color_transfer.RemoveAllPoints() self._color_transfer.AddRGBPoint(0.0, 0, 0, 0) self._color_transfer.AddRGBPoint(254.0, r, g, b) self._color_transfer.AddRGBPoint(255.0, r, g, b) self._piecewise_function = vtk.vtkPiecewiseFunction() self._piecewise_function.RemoveAllPoints() self._piecewise_function.AddPoint(0.0, 0.0) self._piecewise_function.AddPoint(127, 1.0) self._volume_property = vtk.vtkVolumeProperty() self._volume_property.SetColor(self._color_transfer) self._volume_property.SetScalarOpacity(self._piecewise_function) self._volume_property.ShadeOn() self._volume_property.SetInterpolationTypeToLinear() self._volume_property.SetSpecular(0.75) self._volume_property.SetSpecularPower(2) if not self._volume_mapper.IsA("vtkGPUVolumeRayCastMapper"): self._volume_property.SetScalarOpacityUnitDistance(pix_diag) else: if LooseVersion(vtk.vtkVersion().GetVTKVersion() ) > LooseVersion('8.0'): self._volume_property.GetIsoSurfaceValues().SetValue( 0, 127) self._actor = vtk.vtkVolume() self._actor.SetMapper(self._volume_mapper) self._actor.SetProperty(self._volume_property) self._actor.Update()
def Execute(self): extensionFormats = { 'vti': 'vtkxml', 'vtkxml': 'vtkxml', 'vtk': 'vtk', 'dcm': 'dicom', 'raw': 'raw', 'mhd': 'meta', 'mha': 'meta', 'tif': 'tiff', 'png': 'png' } if self.InputFileName == 'BROWSER': import tkFileDialog initialDir = '.' self.InputFileName = tkFileDialog.askopenfilename( title="Input image", initialdir=initialDir) if not self.InputFileName: self.PrintError('Error: no InputFileName.') if self.InputDirectoryName == 'BROWSER': import tkFileDialog initialDir = '.' self.InputDirectoryName = tkFileDialog.askdirectory( title="Input directory", initialdir=initialDir) if not self.InputDirectoryName: self.PrintError('Error: no InputDirectoryName.') if self.GuessFormat and self.InputFileName and not self.Format: import os.path extension = os.path.splitext(self.InputFileName)[1] if extension: extension = extension[1:] if extension in extensionFormats.keys(): self.Format = extensionFormats[extension] if self.UseITKIO and self.InputFileName and self.Format not in [ 'vtkxml', 'raw' ] and not self.InputDirectoryName: self.ReadITKIO() else: if self.Format == 'vtkxml': self.ReadVTKXMLImageFile() elif self.Format == 'vtk': self.ReadVTKImageFile() elif self.Format == 'dicom': if self.InputDirectoryName != '': self.ReadDICOMDirectory() else: self.ReadDICOMFile() elif self.Format == 'raw': self.ReadRawImageFile() elif self.Format == 'meta': self.ReadMetaImageFile() elif self.Format == 'png': self.ReadPNGImageFile() elif self.Format == 'tiff': self.ReadTIFFImageFile() else: self.PrintError('Error: unsupported format ' + self.Format + '.') if (self.Flip[0] == 1) | (self.Flip[1] == 1) | (self.Flip[2] == 1): temp0 = self.Image if self.Flip[0] == 1: flipFilter = vtk.vtkImageFlip() flipFilter.SetInput(self.Image) flipFilter.SetFilteredAxis(0) flipFilter.Update() temp0 = flipFilter.GetOutput() temp1 = temp0 if self.Flip[1] == 1: flipFilter = vtk.vtkImageFlip() flipFilter.SetInput(temp0) flipFilter.SetFilteredAxis(1) flipFilter.Update() temp1 = flipFilter.GetOutput() temp2 = temp1 if self.Flip[2] == 1: flipFilter = vtk.vtkImageFlip() flipFilter.SetInput(temp1) flipFilter.SetFilteredAxis(2) flipFilter.Update() temp2 = flipFilter.GetOutput() self.Image = temp2 print 'Spacing ', self.Image.GetSpacing() print 'Origin ', self.Image.GetOrigin() print 'Dimensions ', self.Image.GetDimensions() if self.Image.GetSource(): self.Image.GetSource().UnRegisterAllOutputs() self.Output = self.Image
norms.SetInputConnection(reader.GetOutputPort()) texture = vtk.vtkTexture() texture.CubeMapOn() files = [ "skybox-px.jpg", "skybox-nx.jpg", "skybox-py.jpg", "skybox-ny.jpg", "skybox-pz.jpg", "skybox-nz.jpg" ] # files = ["wall1.jpg", "wall1.jpg", "wall1.jpg", "wall1.jpg", "wall1.jpg", "wall1.jpg"] for i in range(6): imgReader = vtk.vtkJPEGReader() imgReader.SetFileName(files[i]) flip = vtk.vtkImageFlip() flip.SetInputConnection(imgReader.GetOutputPort()) flip.SetFilteredAxis(1) texture.SetInputConnection(i, flip.GetOutputPort()) # imgReader = vtk.vtkJPEGReader() # imgReader.SetFileName(file) # texture.SetInputConnection(0, imgReader.GetOutputPort()) s_mapper = vtk.vtkOpenGLPolyDataMapper() s_mapper.SetInputConnection(norms.GetOutputPort()) h_actor = vtk.vtkActor() scene.add(h_actor) h_actor.SetTexture(texture) h_actor.SetMapper(s_mapper)
def Execute(self): extensionFormats = {'vti':'vtkxml', 'vtkxml':'vtkxml', 'vtk':'vtk', 'dcm':'dicom', 'raw':'raw', 'mhd':'meta', 'mha':'meta', 'tif':'tiff', 'png':'png'} if self.InputFileName == 'BROWSER': import tkinter.filedialog import os.path initialDir = pypes.pypeScript.lastVisitedPath self.InputFileName = tkinter.filedialog.askopenfilename(title="Input image",initialdir=initialDir) pypes.pypeScript.lastVisitedPath = os.path.dirname(self.InputFileName) if not self.InputFileName: self.PrintError('Error: no InputFileName.') if self.GuessFormat and self.InputFileName and not self.Format: import os.path extension = os.path.splitext(self.InputFileName)[1] if extension: extension = extension[1:] if extension in list(extensionFormats.keys()): self.Format = extensionFormats[extension] if self.UseITKIO and self.InputFileName and self.Format not in ['vtkxml','vtk','raw']: self.ReadITKIO() else: if self.Format == 'vtkxml': self.ReadVTKXMLImageFile() elif self.Format == 'vtk': self.ReadVTKImageFile() elif self.Format == 'raw': self.ReadRawImageFile() elif self.Format == 'meta': self.ReadMetaImageFile() elif self.Format == 'png': self.ReadPNGImageFile() elif self.Format == 'tiff': self.ReadTIFFImageFile() elif self.Format == 'dicom': self.PrintError('Error: please enable parameter UseITKIO in order to read dicom files') else: self.PrintError('Error: unsupported format '+ self.Format + '.') if (self.Flip[0] == 1) | (self.Flip[1] == 1) | (self.Flip[2] == 1): temp0 = self.Image if self.Flip[0] == 1: flipFilter = vtk.vtkImageFlip() flipFilter.SetInputData(self.Image) flipFilter.SetFilteredAxis(0) flipFilter.Update() temp0 = flipFilter.GetOutput() temp1 = temp0 if self.Flip[1] == 1: flipFilter = vtk.vtkImageFlip() flipFilter.SetInputData(temp0) flipFilter.SetFilteredAxis(1) flipFilter.Update() temp1 = flipFilter.GetOutput() temp2 = temp1 if self.Flip[2] == 1: flipFilter = vtk.vtkImageFlip() flipFilter.SetInputData(temp1) flipFilter.SetFilteredAxis(2) flipFilter.Update() temp2 = flipFilter.GetOutput() self.Image = temp2 self.PrintLog('Spacing %f %f %f' % self.Image.GetSpacing()) self.PrintLog('Origin %f %f %f' % self.Image.GetOrigin()) self.PrintLog('Dimensions %d %d %d' % self.Image.GetDimensions()) self.Output = self.Image
def Execute(self): extensionFormats = { 'vti': 'vtkxml', 'vtkxml': 'vtkxml', 'vtk': 'vtk', 'dcm': 'dicom', 'raw': 'raw', 'mhd': 'meta', 'mha': 'meta', 'tif': 'tiff', 'png': 'png' } if self.InputFileName == 'BROWSER': import tkinter.filedialog import os.path initialDir = pypes.pypeScript.lastVisitedPath self.InputFileName = tkinter.filedialog.askopenfilename( title="Input image", initialdir=initialDir) pypes.pypeScript.lastVisitedPath = os.path.dirname( self.InputFileName) if not self.InputFileName: self.PrintError('Error: no InputFileName.') if self.GuessFormat and self.InputFileName and not self.Format: import os.path extension = os.path.splitext(self.InputFileName)[1] if extension: extension = extension[1:] if extension in list(extensionFormats.keys()): self.Format = extensionFormats[extension] if self.UseITKIO and self.InputFileName and self.Format not in [ 'vtkxml', 'vtk', 'raw' ]: self.ReadITKIO() else: if self.Format == 'vtkxml': self.ReadVTKXMLImageFile() elif self.Format == 'vtk': self.ReadVTKImageFile() elif self.Format == 'raw': self.ReadRawImageFile() elif self.Format == 'meta': self.ReadMetaImageFile() elif self.Format == 'png': self.ReadPNGImageFile() elif self.Format == 'tiff': self.ReadTIFFImageFile() elif self.Format == 'dicom': self.PrintError( 'Error: please enable parameter UseITKIO in order to read dicom files' ) else: self.PrintError('Error: unsupported format ' + self.Format + '.') if (self.Flip[0] == 1) | (self.Flip[1] == 1) | (self.Flip[2] == 1): temp0 = self.Image if self.Flip[0] == 1: flipFilter = vtk.vtkImageFlip() flipFilter.SetInputData(self.Image) flipFilter.SetFilteredAxis(0) flipFilter.Update() temp0 = flipFilter.GetOutput() temp1 = temp0 if self.Flip[1] == 1: flipFilter = vtk.vtkImageFlip() flipFilter.SetInputData(temp0) flipFilter.SetFilteredAxis(1) flipFilter.Update() temp1 = flipFilter.GetOutput() temp2 = temp1 if self.Flip[2] == 1: flipFilter = vtk.vtkImageFlip() flipFilter.SetInputData(temp1) flipFilter.SetFilteredAxis(2) flipFilter.Update() temp2 = flipFilter.GetOutput() self.Image = temp2 self.PrintLog('Spacing %f %f %f' % self.Image.GetSpacing()) self.PrintLog('Origin %f %f %f' % self.Image.GetOrigin()) self.PrintLog('Dimensions %d %d %d' % self.Image.GetDimensions()) self.Output = self.Image
import vtk from vtk.test import Testing from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Image pipeline reader = vtk.vtkImageReader() reader.GetExecutive().SetReleaseDataFlag(0,0) reader.SetDataByteOrderToLittleEndian() reader.SetDataExtent(0,63,0,63,1,93) reader.SetFilePrefix("" + str(VTK_DATA_ROOT) + "/Data/headsq/quarter") reader.SetDataMask(0x7fff) imageFloat = vtk.vtkImageCast() imageFloat.SetInputConnection(reader.GetOutputPort()) imageFloat.SetOutputScalarTypeToFloat() flipX = vtk.vtkImageFlip() flipX.SetInputConnection(imageFloat.GetOutputPort()) flipX.SetFilteredAxis(0) flipY = vtk.vtkImageFlip() flipY.SetInputConnection(imageFloat.GetOutputPort()) flipY.SetFilteredAxis(1) flipY.FlipAboutOriginOn() imageAppend = vtk.vtkImageAppend() imageAppend.AddInputConnection(imageFloat.GetOutputPort()) imageAppend.AddInputConnection(flipX.GetOutputPort()) imageAppend.AddInputConnection(flipY.GetOutputPort()) imageAppend.SetAppendAxis(0) viewer = vtk.vtkImageViewer() viewer.SetInputConnection(imageAppend.GetOutputPort()) viewer.SetZSlice(22) viewer.SetColorWindow(2000)
def CreateSurface(self): _ = i18n.InstallLanguage(self.language) reader = vtk.vtkXMLImageDataReader() reader.SetFileName(self.filename) reader.Update() image = reader.GetOutput() if (self.flip_image): # Flip original vtkImageData flip = vtk.vtkImageFlip() flip.SetInput(reader.GetOutput()) flip.SetFilteredAxis(1) flip.FlipAboutOriginOn() image = flip.GetOutput() # Create vtkPolyData from vtkImageData if self.mode == "CONTOUR": contour = vtk.vtkContourFilter() contour.SetInput(image) contour.SetValue(0, self.min_value) # initial threshold contour.SetValue(1, self.max_value) # final threshold contour.GetOutput().ReleaseDataFlagOn() contour.AddObserver("ProgressEvent", lambda obj,evt: self.SendProgress(obj, _("Generating 3D surface..."))) polydata = contour.GetOutput() else: #mode == "GRAYSCALE": mcubes = vtk.vtkMarchingCubes() mcubes.SetInput(image) mcubes.SetValue(0, 255) mcubes.ComputeScalarsOn() mcubes.ComputeGradientsOn() mcubes.ComputeNormalsOn() mcubes.ThresholdBetween(self.min_value, self.max_value) mcubes.GetOutput().ReleaseDataFlagOn() mcubes.AddObserver("ProgressEvent", lambda obj,evt: self.SendProgress(obj, _("Generating 3D surface..."))) polydata = mcubes.GetOutput() if self.decimate_reduction: decimation = vtk.vtkQuadricDecimation() decimation.SetInput(polydata) decimation.SetTargetReduction(self.decimate_reduction) decimation.GetOutput().ReleaseDataFlagOn() decimation.AddObserver("ProgressEvent", lambda obj,evt: self.SendProgress(obj, _("Generating 3D surface..."))) polydata = decimation.GetOutput() if self.smooth_iterations and self.smooth_relaxation_factor: smoother = vtk.vtkSmoothPolyDataFilter() smoother.SetInput(polydata) smoother.SetNumberOfIterations(self.smooth_iterations) smoother.SetFeatureAngle(80) smoother.SetRelaxationFactor(self.smooth_relaxation_factor) smoother.FeatureEdgeSmoothingOn() smoother.BoundarySmoothingOn() smoother.GetOutput().ReleaseDataFlagOn() smoother.AddObserver("ProgressEvent", lambda obj,evt: self.SendProgress(obj, _("Generating 3D surface..."))) polydata = smoother.GetOutput() if self.keep_largest: conn = vtk.vtkPolyDataConnectivityFilter() conn.SetInput(polydata) conn.SetExtractionModeToLargestRegion() conn.AddObserver("ProgressEvent", lambda obj,evt: self.SendProgress(obj, _("Generating 3D surface..."))) polydata = conn.GetOutput() # Filter used to detect and fill holes. Only fill boundary edges holes. #TODO: Hey! This piece of code is the same from # polydata_utils.FillSurfaceHole, we need to review this. if self.fill_holes: filled_polydata = vtk.vtkFillHolesFilter() filled_polydata.SetInput(polydata) filled_polydata.SetHoleSize(300) filled_polydata.AddObserver("ProgressEvent", lambda obj,evt: self.SendProgress(obj, _("Generating 3D surface..."))) polydata = filled_polydata.GetOutput() filename = tempfile.mktemp() writer = vtk.vtkXMLPolyDataWriter() writer.SetInput(polydata) writer.SetFileName(filename) writer.Write() self.pipe.send(None) self.pipe.send(filename)
def writeImages(self): """ Writes out the images """ dirname = self.browsedir.GetValue() pattern = self.patternEdit.GetValue() n = pattern.count("%d") ext = self.outputFormat.menu.GetString(self.outputFormat.menu.GetSelection()).lower() writer = "vtk.vtk%sWriter()" % (ext.upper()) writer = eval(writer) if ext == "tiff": writer.SetCompressionToNoCompression() prefix = dirname + os.path.sep self.dlg = wx.ProgressDialog("Writing", "Writing image %d / %d" % (0, 0), maximum = self.imageAmnt, parent = self, style = wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME | wx.PD_AUTO_HIDE) if n == 0: pattern = pattern + "%d" n = 1 Logging.info("Prefix =", prefix, "pattern =", pattern, kw = "io") writer.SetFilePrefix(prefix) # Do vertical flip to each image flip = vtk.vtkImageFlip() flip.SetFilteredAxis(1) for c in range(self.c): for t in range(self.t): Logging.info("Writing timepoint %d" % t, kw = "io") # If the numbering uses two separate numbers (one for time point, one for slice) # then we modify the pattern to account for the timepoint if n == 3: end = pattern.rfind("%") endstr = pattern[end:] middle = pattern.rfind("%",0,end) middlestr = pattern[middle:end] beginstr = pattern[:middle] currpattern = beginstr%c + middlestr%t + endstr elif n == 2: end = pattern.rfind("%") endstr = pattern[end:] beginstr = pattern[:end] currpattern = beginstr%t + endstr currpattern = "_" + currpattern else: # otherwise we put an underscore (_) in the name then later # on it will be renamed to the proper name and underscore # removed this is done so that if we write many timepoints, # the files can be named with the correct numbers, because # the image writer would otherwise write # every timepoint with slice numbers from 0 to z currpattern = "_" + pattern currpattern += ".%s" % ext currpattern = "%s" + currpattern Logging.info("Setting pattern %s" % currpattern, kw = "io") writer.SetFilePattern(currpattern) data = self.dataUnits[c].getTimepoint(t) data.SetUpdateExtent(data.GetWholeExtent()) data.Update() flip.SetInput(data) writer.SetInput(flip.GetOutput()) writer.SetFileDimensionality(2) self.dlg.Update((c+1) * (t+1) * self.z, "Writing image %d / %d" % ((c+1) * (t+1) * self.z, self.imageAmnt)) Logging.info("Writer = ", writer, kw = "io") writer.Update() writer.Write() overwrite = None if n == 1 or n == 2: for z in range(self.z): if n == 1: img = prefix + "_" + pattern % z + ".%s" % ext else: img = prefix + "_" + pattern%(t,z) + ".%s" % ext if n == 1: num = c * self.t * self.z + t * self.z + z newname = prefix + pattern % num + ".%s" % ext else: newname = prefix + pattern%(t,z) + ".%s" % ext fileExists = os.path.exists(newname) if fileExists and overwrite == None: dlg = wx.MessageDialog(self, "A file called '%s' already exists. Overwrite?"%os.path.basename(newname), "Overwrite existing file", wx.YES_NO|wx.YES_DEFAULT) if dlg.ShowModal()==wx.ID_YES: overwrite=1 os.remove(newname) else: break elif fileExists and overwrite == 1: os.remove(newname) os.rename(img, newname) self.dlg.Destroy()
def __init__(self, master): global _vtk_lib_present if not _vtk_lib_present: raise ValueError("no VTK") # Window creation tk.Frame.__init__(self, master) self.columnconfigure(0, weight=1) self.rowconfigure(0, weight=1) # Renderer and associated widget self.im_ref = None self._renWidget = vtkTkRenderWidget(self) self._ren = vtk.vtkRenderer() self._renWidget.GetRenderWindow().AddRenderer(self._ren) self._renWidget.grid(row=0, column=0, sticky=tk.E+tk.W+tk.N+tk.S) # Transfer functions and volume display options and properties self.vtk_im = vtkImageImport() self.vtk_im.SetDataScalarType(VTK_UNSIGNED_CHAR) self.im_flipy = vtk.vtkImageFlip() self.im_flipy.SetFilteredAxis(1) self.im_flipy.SetInputConnection(self.vtk_im.GetOutputPort()); self.im_flipz = vtk.vtkImageFlip() self.im_flipz.SetFilteredAxis(2) self.im_flipz.SetInputConnection(self.im_flipy.GetOutputPort()); self.opaTF = vtk.vtkPiecewiseFunction() self.colTF = vtk.vtkColorTransferFunction() self.volProp = vtk.vtkVolumeProperty() self.volProp.SetColor(self.colTF) self.volProp.SetScalarOpacity(self.opaTF) self.volProp.ShadeOn() self.volProp.SetInterpolationTypeToLinear() self.compoFun = vtk.vtkVolumeRayCastCompositeFunction() self.isosfFun = vtk.vtkVolumeRayCastIsosurfaceFunction() self.isosfFun.SetIsoValue(0) self.mipFun = vtk.vtkVolumeRayCastMIPFunction() self.volMap = vtk.vtkVolumeRayCastMapper() self.volMap.SetVolumeRayCastFunction(self.compoFun) self.volMap.SetInputConnection(self.im_flipz.GetOutputPort()) self.volume = vtk.vtkVolume() self.volume.SetMapper(self.volMap) self.volume.SetProperty(self.volProp) self.outlineData = vtk.vtkOutlineFilter() self.outlineData.SetInputConnection(self.im_flipz.GetOutputPort()) self.mapOutline = vtk.vtkPolyDataMapper() self.mapOutline.SetInputConnection(self.outlineData.GetOutputPort()) self.outline = vtk.vtkActor() self.outline.SetMapper(self.mapOutline) self.outline.GetProperty().SetColor(1, 1, 1) self._ren.AddVolume(self.volume) self._ren.AddActor(self.outline) self._ren.SetBackground(116/255.0,214/255.0,220/255.0) # Control widget self.controlbar = ttk.Frame(self) self.controlbar.grid(row=0, column=1, sticky=tk.E+tk.W+tk.N+tk.S) self.drawControlBar() self.controlbar.grid_remove() self.controlbar.state = "hidden" self.master = master # Creates the info status bar. statusbar = ttk.Frame(self) statusbar.columnconfigure(0, weight=1) statusbar.grid(row=1, column=0, columnspan=2, sticky=tk.E+tk.W) self.infos = [] for i in range(3): v = tk.StringVar(self) ttk.Label(statusbar, anchor=tk.W, textvariable=v).grid(row=0, column=i, sticky=tk.E+tk.W) self.infos.append(v) self.infos[2].set("Hit Tab for control <-") # Events bindings master.bind("<KeyPress-Tab>", self.displayControlEvent)
def LoadVolume(self): proj = prj.Project() #image = imagedata_utils.to_vtk(n_array, spacing, slice_number, orientation) if not self.loaded_image: self.LoadImage() self.loaded_image = 1 image = self.image number_filters = len(self.config['convolutionFilters']) if (prj.Project().original_orientation == const.AXIAL): flip_image = True else: flip_image = False #if (flip_image): update_progress= vtk_utils.ShowProgress(2 + number_filters) # Flip original vtkImageData flip = vtk.vtkImageFlip() flip.SetInputData(image) flip.SetFilteredAxis(1) flip.FlipAboutOriginOn() # flip.ReleaseDataFlagOn() flip_ref = weakref.ref(flip) flip_ref().AddObserver("ProgressEvent", lambda obj,evt: update_progress(flip_ref(), "Rendering...")) flip.Update() image = flip.GetOutput() scale = image.GetScalarRange() self.scale = scale cast = vtk.vtkImageShiftScale() cast.SetInputData(image) cast.SetShift(abs(scale[0])) cast.SetOutputScalarTypeToUnsignedShort() # cast.ReleaseDataFlagOn() cast_ref = weakref.ref(cast) cast_ref().AddObserver("ProgressEvent", lambda obj,evt: update_progress(cast_ref(), "Rendering...")) cast.Update() image2 = cast self.imagedata = image2 if self.config['advancedCLUT']: self.Create16bColorTable(scale) self.CreateOpacityTable(scale) else: self.Create8bColorTable(scale) self.Create8bOpacityTable(scale) image2 = self.ApplyConvolution(image2.GetOutput(), update_progress) self.final_imagedata = image2 # Changed the vtkVolumeRayCast to vtkFixedPointVolumeRayCastMapper # because it's faster and the image is better # TODO: To test if it's true. if const.TYPE_RAYCASTING_MAPPER: volume_mapper = vtk.vtkVolumeRayCastMapper() #volume_mapper.AutoAdjustSampleDistancesOff() #volume_mapper.SetInput(image2) #volume_mapper.SetVolumeRayCastFunction(composite_function) #volume_mapper.SetGradientEstimator(gradientEstimator) volume_mapper.IntermixIntersectingGeometryOn() self.volume_mapper = volume_mapper else: if int(ses.Session().rendering) == 0: volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper() #volume_mapper.AutoAdjustSampleDistancesOff() self.volume_mapper = volume_mapper volume_mapper.IntermixIntersectingGeometryOn() else: volume_mapper = vtk.vtkGPUVolumeRayCastMapper() self.volume_mapper = volume_mapper self.SetTypeRaycasting() volume_mapper.SetInputData(image2) # TODO: Look to this #volume_mapper_hw = vtk.vtkVolumeTextureMapper3D() #volume_mapper_hw.SetInput(image2) #Cut Plane #CutPlane(image2, volume_mapper) #self.color_transfer = color_transfer volume_properties = vtk.vtkVolumeProperty() #volume_properties.IndependentComponentsOn() volume_properties.SetInterpolationTypeToLinear() volume_properties.SetColor(self.color_transfer) try: volume_properties.SetScalarOpacity(self.opacity_transfer_func) except NameError: pass # Using these lines to improve the raycasting quality. These values # seems related to the distance from ray from raycasting. # TODO: Need to see values that improve the quality and don't decrease # the performance. 2.0 seems to be a good value to pix_diag pix_diag = 2.0 volume_mapper.SetImageSampleDistance(0.25) volume_mapper.SetSampleDistance(pix_diag / 5.0) volume_properties.SetScalarOpacityUnitDistance(pix_diag) self.volume_properties = volume_properties self.SetShading() volume = vtk.vtkVolume() volume.SetMapper(volume_mapper) volume.SetProperty(volume_properties) self.volume = volume colour = self.GetBackgroundColour() self.exist = 1 Publisher.sendMessage('Load volume into viewer', (volume, colour, (self.ww, self.wl))) del flip del cast
def dicomTransform(self, image, image_pos_pat, image_ori_pat): """ dicomTransform: transforms an image to a DICOM coordinate frame INPUTS: ======= image: (vtkImageData) Input image to Transform image_pos_pat: (list(dicomInfo[0x0020,0x0032].value))) Image position patient Dicom Tag image_ori_pat: (list(dicomInfo[0x0020,0x0037].value)) Image oreintation patient Dicom Tag OUTPUTS: ======= transformed_image (vtkImageData) Transformed imaged mapped to dicom coords frame transform (vtkTransform) Transform used """ # If one considers the localizer plane as a "viewport" onto the DICOM 3D coordinate space, then that viewport is described by its origin, its row unit vector, column unit vector and a normal unit vector (derived from the row and column vectors by taking the cross product). Now if one moves the origin to 0,0,0 and rotates this viewing plane such that the row vector is in the +X direction, the column vector the +Y direction, and the normal in the +Z direction, then one has a situation where the X coordinate now represents a column offset in mm from the localizer's top left hand corner, and the Y coordinate now represents a row offset in mm from the localizer's top left hand corner, and the Z coordinate can be ignored. One can then convert the X and Y mm offsets into pixel offsets using the pixel spacing of the localizer imag # Initialize Image orienation "Image Orientation Patient Matrix" IO = matrix( [[0, 0,-1, 1], [1, 0, 0, 1], [0,-1, 0, 1], [0, 0, 0, 1]]) # Assign the 6-Image orientation patient coordinates (from Dicomtags) IO[0,0] = image_ori_pat[0]; IO[0,1] = image_ori_pat[1]; IO[0,2] = image_ori_pat[2]; IO[1,0] = image_ori_pat[3]; IO[1,1] = image_ori_pat[4]; IO[1,2] = image_ori_pat[5]; # obtain thrid column as the cross product of column 1 y 2 IO_col1 = [image_ori_pat[0], image_ori_pat[1], image_ori_pat[2]] IO_col2 = [image_ori_pat[3], image_ori_pat[4], image_ori_pat[5]] IO_col3 = cross(IO_col1, IO_col2) # assign column 3 IO[2,0] = IO_col3[0]; IO[2,1] = IO_col3[1]; IO[2,2] = IO_col3[2]; IP = array([0, 0, 0, 1]) # Initialization Image Position IP[0] = image_pos_pat[0]; IP[1] = image_pos_pat[1]; IP[2] = image_pos_pat[2]; IO[0,3] = -image_pos_pat[0]; IO[1,3] = -image_pos_pat[1]; IO[2,3] = -image_pos_pat[2] "Compute Volume Origin" origin = IP*IO.I # Create matrix 4x4 DICOM_mat = vtk.vtkMatrix4x4(); DICOM_mat.SetElement(0, 0, IO[0,0]) DICOM_mat.SetElement(0, 1, IO[0,1]) DICOM_mat.SetElement(0, 2, IO[0,2]) DICOM_mat.SetElement(0, 3, IO[0,3]) DICOM_mat.SetElement(1, 0, IO[1,0]) DICOM_mat.SetElement(1, 1, IO[1,1]) DICOM_mat.SetElement(1, 2, IO[1,2]) DICOM_mat.SetElement(1, 3, IO[1,3]) DICOM_mat.SetElement(2, 0, IO[2,0]) DICOM_mat.SetElement(2, 1, IO[2,1]) DICOM_mat.SetElement(2, 2, IO[2,2]) DICOM_mat.SetElement(2, 3, IO[2,3]) DICOM_mat.SetElement(3, 0, IO[3,0]) DICOM_mat.SetElement(3, 1, IO[3,1]) DICOM_mat.SetElement(3, 2, IO[3,2]) DICOM_mat.SetElement(3, 3, IO[3,3]) #DICOM_mat.Invert() # Set up the axes transform = vtk.vtkTransform() transform.Concatenate(DICOM_mat) transform.Update() # Set up the cube (set up the translation back to zero DICOM_mat_cube = vtk.vtkMatrix4x4(); DICOM_mat_cube.DeepCopy(DICOM_mat) DICOM_mat_cube.SetElement(0, 3, 0) DICOM_mat_cube.SetElement(1, 3, 0) DICOM_mat_cube.SetElement(2, 3, 0) transform_cube = vtk.vtkTransform() transform_cube.Concatenate(DICOM_mat_cube) transform_cube.Update() # Change info # Flip along Y-Z-axis: VTK uses computer graphics convention where the first pixel in memory is shown # in the lower left of the displayed image. flipZ_image = vtk.vtkImageFlip() flipZ_image.SetInput(image) flipZ_image.SetFilteredAxis(2) flipZ_image.Update() flipY_image = vtk.vtkImageFlip() flipY_image.SetInput(flipZ_image.GetOutput()) flipY_image.SetFilteredAxis(1) flipY_image.Update() # Change info origin flipY_origin_image = vtk.vtkImageChangeInformation() flipY_origin_image.SetInput( flipY_image.GetOutput() ); flipY_origin_image.SetOutputOrigin(origin[0,0], origin[0,1], origin[0,2]) flipY_origin_image.Update() transformed_image = flipY_origin_image.GetOutput() transformed_image.UpdateInformation() self.dims = transformed_image.GetDimensions() print "Image Dimensions" print self.dims (xMin, xMax, yMin, yMax, zMin, zMax) = transformed_image.GetWholeExtent() print "Image Extension" print xMin, xMax, yMin, yMax, zMin, zMax self.spacing = transformed_image.GetSpacing() print "Image Spacing" print self.spacing self.origin = transformed_image.GetOrigin() print "Image Origin" print self.origin return transformed_image, transform_cube
def mesh_2_mask( inputMesh, outputImage, inputImage=None, superRes=False, spacing=(1.0, 1.0, 1.0) ): """ This program takes in a closed 3D surface, vtkPolyData, and converts it into volume representation (vtkImageData) where the foreground voxels are 1 and the background voxels are 0. Internally vtkPolyDataToImageStencil is utilized. The resultant image is saved to disk in NIFTIimage file format. SimpleITK is used to convert images to standard orientation used for 3D medical images. :param inputMesh: a vtkPolyData file of a 3D surface :param outputImage: output file path for NIFTI image :param inputImage: reference image to get desired spacing, origin, and direction. :param superRes: :param spacing: :return: """ VTK_MAJOR_VERSION = str(vtk.vtkVersion().GetVTKVersion()).split(".")[0] outputImage = str(outputImage) if inputImage: inputImage = str(inputImage) # check output image extension out_ext = outputImage.split(".", 1)[-1] if "nii" in out_ext: writer = vtk.vtkNIFTIImageWriter() else: print( "ERROR: Output must be NIFTI image file. \n\tUnrecognized extension: {0}".format( out_ext ) ) return sys.exit(os.EX_IOERR) if inputImage: image = read_vtk_image(inputImage) else: image = None # read the mesh in pd = read_poly_data(inputMesh) pd = preprocess_mesh(pd) # allocate whiteImage whiteImage = vtk.vtkImageData() # polygonal data -. image stencil: pol2stenc = vtk.vtkPolyDataToImageStencil() if VTK_MAJOR_VERSION <= 5: pol2stenc.SetInput(pd) else: pol2stenc.SetInputData(pd) # get the bounds bounds = pd.GetBounds() if image: spacing = image.GetSpacing() dim = image.GetDimensions() # set VTK direction to RAS vtk_direction = (-1.0, 0.0, 0.0, 0.0, -1.0, 0.0, 0.0, 0.0, 1.0) # vtk does not get the correct origin # origin = image.GetOrigin () # use SimpleITK instead image_sitk = sitk.ReadImage(inputImage) origin = image_sitk.GetOrigin() direction = image_sitk.GetDirection() print(direction) print(origin) print(spacing) # superRes slows down the script quite a bit if superRes: """Creates an image with pixels a fourth the size of the original This helps allivaite some of the partial voluming effect that can take place.""" denom = 2 spacing = ( spacing[0] / float(denom), spacing[1] / float(denom), spacing[2] / float(denom), ) dim = (dim[0] * denom, dim[1] * denom, dim[2] * denom) # VTKImages seem to always have the same direction origin = ( origin[0] * vtk_direction[0], origin[1] * vtk_direction[4], origin[2] * vtk_direction[8], ) if direction != vtk_direction: if direction == (1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0): origin = ( origin[0] - spacing[0] * (dim[0] - 1), origin[1] - spacing[1] * (dim[1] - 1), origin[2], ) else: print("ERROR: Not sure how to handle input image direction") sys.exit() print(origin) else: if superRes: spacing = ( spacing[0] / float(2), spacing[1] / float(2), spacing[2] / float(2), ) # compute dimensions dim = [0, 0, 0] for i in range(3): dim[i] = int(math.ceil((bounds[i * 2 + 1] - bounds[i * 2]) / spacing[i])) dim = tuple(dim) # get origin origin = [0, 0, 0] origin[0] = bounds[0] + spacing[0] / float(2) origin[1] = bounds[2] + spacing[1] / float(2) origin[2] = bounds[4] + spacing[2] / float(2) origin = tuple(origin) whiteImage.SetSpacing(spacing) whiteImage.SetOrigin(origin) pol2stenc.SetOutputOrigin(origin) pol2stenc.SetOutputSpacing(spacing) # set dimensions whiteImage.SetDimensions(dim) whiteImage.SetExtent(0, dim[0] - 1, 0, dim[1] - 1, 0, dim[2] - 1) if VTK_MAJOR_VERSION <= 5: whiteImage.SetScalarTypeToUnsignedChar() whiteImage.AllocateScalars() else: whiteImage.AllocateScalars(vtk.VTK_UNSIGNED_CHAR, 1) # fill the image with foreground voxels: inval = 1 outval = 0 count = whiteImage.GetNumberOfPoints() for i in range(count): whiteImage.GetPointData().GetScalars().SetTuple1(i, inval) # update pol2stenc pol2stenc.SetOutputWholeExtent(whiteImage.GetExtent()) pol2stenc.Update() # cut the corresponding white image and set the background: imgstenc = vtk.vtkImageStencil() if VTK_MAJOR_VERSION <= 5: imgstenc.SetInput(whiteImage) imgstenc.SetStencil(pol2stenc.GetOutput()) else: imgstenc.SetInputData(whiteImage) imgstenc.SetStencilConnection(pol2stenc.GetOutputPort()) imgstenc.ReverseStencilOff() imgstenc.SetBackgroundValue(outval) imgstenc.Update() # write image to file writer.SetFileName(outputImage) if inputImage != None and direction != vtk_direction: flipFilter = vtk.vtkImageFlip() flipFilter.SetFilteredAxis(1) # flip y axis flipFilter.SetInputData(imgstenc.GetOutput()) flipFilter.SetFlipAboutOrigin(1) flipFilter.Update() flipFilter2 = vtk.vtkImageFlip() flipFilter2.SetFilteredAxis(0) # flip x axis flipFilter2.SetInputData(flipFilter.GetOutput()) flipFilter2.SetFlipAboutOrigin(1) flipFilter2.Update() if VTK_MAJOR_VERSION <= 5: writer.SetInput(flipFilter2.GetOutput()) else: writer.SetInputData(flipFilter2.GetOutput()) writer.Write() itk_image = sitk.ReadImage(inputImage) out_image = sitk.ReadImage(outputImage) out_image.SetDirection(itk_image.GetDirection()) out_image.SetOrigin(itk_image.GetOrigin()) sitk.WriteImage(out_image, outputImage) else: if VTK_MAJOR_VERSION <= 5: writer.SetInput(imgstenc.GetOutput()) else: writer.SetInputData(imgstenc.GetOutput()) writer.Write() return os.path.abspath(outputImage)
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): if from_binary: mask = numpy.memmap(mask_filename, mode='r', dtype=mask_dtype, shape=mask_shape) a_mask = numpy.array(mask[roi.start + 1:roi.stop + 1, 1:, 1:]) image = converters.to_vtk(a_mask, spacing, roi.start, "AXIAL") 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) a_image = numpy.array(image[roi]) 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") 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, spacing, roi.start, "AXIAL") 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() 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 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)
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 Execute(self): extensionFormats = {'vti':'vtkxml', 'vtkxml':'vtkxml', 'vtk':'vtk', 'dcm':'dicom', 'raw':'raw', 'mhd':'meta', 'mha':'meta', 'tif':'tiff', 'png':'png'} if self.InputFileName == 'BROWSER': import tkFileDialog initialDir = '.' self.InputFileName = tkFileDialog.askopenfilename(title="Input image",initialdir=initialDir) if not self.InputFileName: self.PrintError('Error: no InputFileName.') if self.InputDirectoryName == 'BROWSER': import tkFileDialog initialDir = '.' self.InputDirectoryName = tkFileDialog.askdirectory(title="Input directory",initialdir=initialDir) if not self.InputDirectoryName: self.PrintError('Error: no InputDirectoryName.') if self.GuessFormat and self.InputFileName and not self.Format: import os.path extension = os.path.splitext(self.InputFileName)[1] if extension: extension = extension[1:] if extension in extensionFormats.keys(): self.Format = extensionFormats[extension] if self.UseITKIO and self.InputFileName and self.Format not in ['vtkxml','raw'] and not self.InputDirectoryName: self.ReadITKIO() else: if self.Format == 'vtkxml': self.ReadVTKXMLImageFile() elif self.Format == 'vtk': self.ReadVTKImageFile() elif self.Format == 'dicom': if self.InputDirectoryName != '': self.ReadDICOMDirectory() else: self.ReadDICOMFile() elif self.Format == 'raw': self.ReadRawImageFile() elif self.Format == 'meta': self.ReadMetaImageFile() elif self.Format == 'png': self.ReadPNGImageFile() elif self.Format == 'tiff': self.ReadTIFFImageFile() else: self.PrintError('Error: unsupported format '+ self.Format + '.') if (self.Flip[0] == 1) | (self.Flip[1] == 1) | (self.Flip[2] == 1): temp0 = self.Image if self.Flip[0] == 1: flipFilter = vtk.vtkImageFlip() flipFilter.SetInput(self.Image) flipFilter.SetFilteredAxis(0) flipFilter.Update() temp0 = flipFilter.GetOutput() temp1 = temp0 if self.Flip[1] == 1: flipFilter = vtk.vtkImageFlip() flipFilter.SetInput(temp0) flipFilter.SetFilteredAxis(1) flipFilter.Update() temp1 = flipFilter.GetOutput() temp2 = temp1 if self.Flip[2] == 1: flipFilter = vtk.vtkImageFlip() flipFilter.SetInput(temp1) flipFilter.SetFilteredAxis(2) flipFilter.Update() temp2 = flipFilter.GetOutput() self.Image = temp2 print 'Spacing ', self.Image.GetSpacing() print 'Origin ', self.Image.GetOrigin() print 'Dimensions ', self.Image.GetDimensions() if self.Image.GetSource(): self.Image.GetSource().UnRegisterAllOutputs() self.Output = self.Image