def createScanlines(self, scanlineVolume): imgDim = self.inputVolume.GetImageData().GetDimensions() drawFilter = vtk.vtkImageCanvasSource2D() drawFilter.SetExtent(0,imgDim[0]-1,0,imgDim[1]-1,0,0) drawFilter.SetScalarTypeToUnsignedChar() drawFilter.SetDrawColor(0) # Color for background drawFilter.FillBox(0,imgDim[0]-1,0,imgDim[1]-1) # Initialize background drawFilter.SetDrawColor(1) # Color for scanlines # Draw each scanline for i in range(self.numberOfScanlines): drawFilter.FillTube(int(self.scanlines[i].startPoint[0]),int(self.scanlines[i].startPoint[1]),int(self.scanlines[i].endPoint[0]),int(self.scanlines[i].endPoint[1]),0.5) drawFilter.Update() # Copy scanline slice to match the Z-dimension of input US volume numOfSlices = imgDim[2] imageAppendFilter = vtk.vtkImageAppend() imageAppendFilter.SetAppendAxis(2) for _ in range(numOfSlices): imageAppendFilter.AddInputData(drawFilter.GetOutput()) imageAppendFilter.Update() # Set scanline imagedata scanlineVolume.SetIJKToRASMatrix(self.ijkToRas) scanlineVolume.SetRASToIJKMatrix(self.rasToIjk) scanlineVolume.SetAndObserveImageData(imageAppendFilter.GetOutput())
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__( self, module_manager, vtk.vtkImageAppend(), 'Processing.', ('vtkImageData',), ('vtkImageData',), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def getMaskFromPoints(points, mx, my, mz, value=255): """ Create a mask where all given points are set to value (between 0-255) """ if value > 255: value = 255 elif value < 0: value = 0 size = mx * my pointStructString = "%dB" % size pointData = [] for y in range(0, my): for x in range(0, mx): pointData.append(value * points.get((x, y), 0)) packedPointString = struct.pack(pointStructString, *pointData) importer = vtk.vtkImageImport() importer.CopyImportVoidPointer(packedPointString, mx * my) importer.SetDataScalarTypeToUnsignedChar() importer.SetNumberOfScalarComponents(1) importer.SetDataExtent(0, mx - 1, 0, my - 1, 0, 0) importer.SetWholeExtent(0, mx - 1, 0, my - 1, 0, 0) importer.Update() append = vtk.vtkImageAppend() append.SetAppendAxis(2) for z in range(0, mz): append.SetInput(z, importer.GetOutput()) append.Update() image2 = append.GetOutput() return image2
def Execute(self): if self.Mesh == None: self.PrintError("Error: no Mesh.") acquiredMesh = self.Mesh acquiredKSpace = None if (self.KSpaceDimensionality == 3) or not self.SliceSelection: origin = [ self.FOVCenter[0] - self.FOV[0] / 2.0, self.FOVCenter[1] - self.FOV[1] / 2.0, self.FOVCenter[2] - self.FOV[2] / 2.0, ] spacing = [ self.FOV[0] / self.MatrixSize[0], self.FOV[1] / self.MatrixSize[1], self.FOV[2] / self.MatrixSize[2], ] acquiredKSpace = self.AcquireKSpace(self.Mesh, origin, spacing) elif self.KSpaceDimensionality == 2: spacing = [ self.FOV[0] / self.MatrixSize[0], self.FOV[1] / self.MatrixSize[1], self.FOV[2] / self.MatrixSize[2], ] kSpaceAppend = vtk.vtkImageAppend() kSpaceAppend.SetAppendAxis(2) sliceLocations = [] sliceLocation = self.FOVCenter[2] - self.FOV[2] / 2.0 while sliceLocation <= self.FOVCenter[2] + self.FOV[2] / 2.0: sliceLocations.append(sliceLocation) sliceLocation += self.SliceSpacing bounds = self.Mesh.GetBounds() for sliceLocation in sliceLocations: self.PrintLog("Processing slice at " + str(sliceLocation)) origin = [self.FOVCenter[0] - self.FOV[0] / 2.0, self.FOVCenter[1] - self.FOV[1] / 2.0, sliceLocation] sliceKSpace = self.AcquireKSpace(self.Mesh, origin, spacing) kSpaceAppend.AddInput(sliceKSpace) kSpaceAppend.Update() acquiredKSpace = kSpaceAppend.GetOutput() self.KSpace = self.ComputeKSpaceOperation(acquiredKSpace)
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 CreateVolumeFromSlices(vtkImages, spacing): """ Creates a volume from a set of slices (2D vtkImage objects). """ vtkImageAppend = vtk.vtkImageAppend() vtkImageAppend.SetAppendAxis(2) for sliceIndex in range(0, len(vtkImages)): vtkImageAppend.SetInput(sliceIndex, vtkImages[sliceIndex]) output = vtkImageAppend.GetOutput() output.SetSpacing(spacing) output.Update() return output
def FixGantryTilt(imagedata, tilt): """ Fix gantry tilt given a vtkImageData and the tilt value. Return new vtkImageData. """ # Retrieve data from original imagedata extent = [int(value) for value in imagedata.GetExtent()] origin = imagedata.GetOrigin() spacing = [float(value) for value in imagedata.GetSpacing()] n_slices = int(extent[5]) new_zspacing = math.cos(tilt*(math.acos(-1.0)/180.0)) * spacing[2] #zspacing translate_coef = math.tan(tilt*math.pi/180.0)*new_zspacing*(n_slices-1) # Class responsible for translating data reslice = vtk.vtkImageReslice() reslice.SetInput(imagedata) reslice.SetInterpolationModeToLinear() # Translation will create new pixels. Let's set new pixels' colour to black. reslice.SetBackgroundLevel(imagedata.GetScalarRange()[0]) # Class responsible for append translated data append = vtk.vtkImageAppend() append.SetAppendAxis(2) # Translate and append each slice for i in xrange(n_slices+1): slice_imagedata = vtk.vtkImageData() value = math.tan(tilt*math.pi/180.0) * new_zspacing * i new_origin1 = origin[1] + value - translate_coef # Translate data reslice.SetOutputOrigin(origin[0], new_origin1, origin[2]) reslice.SetOutputExtent(extent[0], extent[1], extent[2], extent[3], i,i) reslice.Update() # Append data slice_imagedata.DeepCopy(reslice.GetOutput()) slice_imagedata.UpdateInformation() append.AddInput(slice_imagedata) append.Update() # Final imagedata imagedata = vtk.vtkImageData() imagedata.DeepCopy(append.GetOutput()) imagedata.SetSpacing(spacing[0], spacing[1], new_zspacing) imagedata.SetExtent(extent) imagedata.UpdateInformation() return imagedata
def __init__(self, module_manager): ModuleBase.__init__(self, module_manager) NoConfigModuleMixin.__init__(self) self._imageStack = None self._transformStack = None # self._itkExporterStack = [] self._imageAppend = vtk.vtkImageAppend() # stack of images should become volume self._imageAppend.SetAppendAxis(2) self._viewFrame = self._createViewFrame( {'Module (self)' : self}) self.config_to_logic() self.logic_to_config() self.config_to_view()
def RollMap( self, baseImage ): # baseImage.Update() if self.world_cut == self.map_cut: return baseImage baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] newCut = self.NormalizeMapLon( self.world_cut ) delCut = newCut - self.map_cut # print " %%%%%% Roll Map %%%%%%: world_cut=%.1f, map_cut=%.1f, newCut=%.1f " % ( float(self.world_cut), float(self.map_cut), float(newCut) ) imageLen = x1 - x0 + 1 sliceSize = imageLen * ( delCut / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent = list( baseExtent ) extent[0:2] = [ x0, x0 + sliceCoord - 1 ] clip0 = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip0.SetInput( baseImage ) else: clip0.SetInputData( baseImage ) clip0.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] ) extent[0:2] = [ x0 + sliceCoord, x1 ] clip1 = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip1.SetInput( baseImage ) else: clip1.SetInputData( baseImage ) clip1.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] ) append = vtk.vtkImageAppend() append.SetAppendAxis( 0 ) append.SetInputConnection ( clip1.GetOutputPort() ) append.AddInputConnection ( clip0.GetOutputPort() ) imageInfo = vtk.vtkImageChangeInformation() imageInfo.SetInputConnection( append.GetOutputPort() ) imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 ) imageInfo.SetOutputExtentStart( 0, 0, 0 ) imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] ) imageInfo.Update() result = imageInfo.GetOutput() return result
def RollMap( self, baseImage ): if self.world_cut == self.map_cut: return baseImage baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] newCut = self.NormalizeMapLon( self.world_cut ) delCut = newCut - self.map_cut # print " %%%%%% Roll Map %%%%%%: world_cut=%.1f, map_cut=%.1f, newCut=%.1f " % ( float(self.world_cut), float(self.map_cut), float(newCut) ) imageLen = x1 - x0 + 1 sliceSize = imageLen * ( delCut / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent = list( baseExtent ) extent[0:2] = [ x0, x0 + sliceCoord - 1 ] clip0 = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip0.SetInput(baseImage) else: clip0.SetInputData(baseImage) clip0.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] ) extent[0:2] = [ x0 + sliceCoord, x1 ] clip1 = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip1.SetInput(baseImage) else: clip1.SetInputData(baseImage) clip1.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] ) append = vtk.vtkImageAppend() append.SetAppendAxis( 0 ) append.AddInputConnection( clip1.GetOutputPort() ) append.AddInputConnection( clip0.GetOutputPort() ) imageInfo = vtk.vtkImageChangeInformation() imageInfo.SetInputConnection( append.GetOutputPort() ) imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 ) imageInfo.SetOutputExtentStart( 0, 0, 0 ) imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] ) imageInfo.Update() result = imageInfo.GetOutput() return result
def append(self, volumes, axis='z', preserveExtents=False): """ Take the components from multiple inputs and merges them into one output. Except for the append axis, all inputs must have the same extent. All inputs must have the same number of scalar components. The output has the same origin and spacing as the first input. The origin and spacing of all other inputs are ignored. All inputs must have the same scalar type. :param int,str axis: axis expanded to hold the multiple images. :param bool preserveExtents: if True, the extent of the inputs is used to place the image in the output. The whole extent of the output is the union of the input whole extents. Any portion of the output not covered by the inputs is set to zero. The origin and spacing is taken from the first input. .. code-block:: python from vedo import load, datadir vol = load(datadir+'embryo.tif') vol.append(vol, axis='x').show() """ ima = vtk.vtkImageAppend() ima.SetInputData(self.imagedata()) if not utils.isSequence(volumes): volumes = [volumes] for volume in volumes: if isinstance(volume, vtk.vtkImageData): ima.AddInputData(volume) else: ima.AddInputData(volume.imagedata()) ima.SetPreserveExtents(preserveExtents) if axis == "x": axis = 0 elif axis == "y": axis = 1 elif axis == "z": axis = 2 ima.SetAppendAxis(axis) ima.Update() return self._update(ima.GetOutput())
def append(self, pictures, axis='z', preserveExtents=False): """ Append the input images to the current one along the specified axis. Except for the append axis, all inputs must have the same extent. All inputs must have the same number of scalar components. The output has the same origin and spacing as the first input. The origin and spacing of all other inputs are ignored. All inputs must have the same scalar type. :param int,str axis: axis expanded to hold the multiple images. :param bool preserveExtents: if True, the extent of the inputs is used to place the image in the output. The whole extent of the output is the union of the input whole extents. Any portion of the output not covered by the inputs is set to zero. The origin and spacing is taken from the first input. .. code-block:: python from vedo import Picture, dataurl pic = Picture(dataurl+'dog.jpg').pad() pic.append([pic,pic,pic], axis='y') pic.append([pic,pic,pic,pic], axis='x') pic.show(axes=1) """ ima = vtk.vtkImageAppend() ima.SetInputData(self._data) if not utils.isSequence(pictures): pictures = [pictures] for p in pictures: if isinstance(p, vtk.vtkImageData): ima.AddInputData(p) else: ima.AddInputData(p._data) ima.SetPreserveExtents(preserveExtents) if axis == "x": axis = 0 elif axis == "y": axis = 1 ima.SetAppendAxis(axis) ima.Update() return self._update(ima.GetOutput())
def RollMap( self, baseImage ): baseImage.Update() if self.world_cut == self.map_cut: return baseImage baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] newCut = NormalizeLon( self.world_cut ) delCut = NormalizeLon( self.map_cut - newCut ) imageLen = x1 - x0 + 1 sliceSize = imageLen * ( delCut / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent = list( baseExtent ) extent[0:2] = [ x0, x0 + sliceCoord - 1 ] clip0 = vtk.vtkImageClip() clip0.SetInput( baseImage ) clip0.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] ) extent[0:2] = [ x0 + sliceCoord, x1 ] clip1 = vtk.vtkImageClip() clip1.SetInput( baseImage ) clip1.SetOutputWholeExtent( extent[0], extent[1], extent[2], extent[3], extent[4], extent[5] ) append = vtk.vtkImageAppend() append.SetAppendAxis( 0 ) append.AddInput( clip1.GetOutput() ) append.AddInput( clip0.GetOutput() ) imageInfo = vtk.vtkImageChangeInformation() imageInfo.SetInputConnection( append.GetOutputPort() ) imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 ) imageInfo.SetOutputExtentStart( 0, 0, 0 ) imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] ) result = imageInfo.GetOutput() result.Update() return result
def reader_vti(filename): logging.debug("In data.reader_vti()") append = vtk.vtkImageAppend() append.ReleaseDataFlagOn() append.SetAppendAxis(2) reader = vtk.vtkXMLImageDataReader() reader.ReleaseDataFlagOn() if os.path.exists(filename): reader.SetFileName(filename) # reader.GetOutput().Register(reader) reader.Update() return vtk.vtkImageData.SafeDownCast(reader.GetOutput()) else: i = 0 paths = [] while True: partName = filename.replace(".vti", "{0}.vti".format(i)) # print partName if os.path.exists(partName): paths.append(partName) else: break i = i + 1 # paths.reverse() for i, partName in enumerate(paths): reader = vtk.vtkXMLImageDataReader() reader.ReleaseDataFlagOn() reader.SetFileName(partName) # reader.GetOutput().Register(reader) reader.Update() append.SetInput(i, reader.GetOutput()) append.Update() output = append.GetOutput() for i in range(append.GetNumberOfInputs()): append.GetInput(i).ReleaseData() return output
def GetNodeBasisImages(self, node_id, antialias = False): """Returns a vtkImageData of all wavelet or scaling function basis images for a given node.""" if self.data_loaded: if self.WordleImages: self.WordleView.SetRandomSeed(0); # Scaling functions coeffs are defined wrt parent node scaling functions... # Need to create separate images (Z) for each column of matrix result # Bases is D x N matrix image_cols = self.Bases[node_id] self.WordleView.SetColorByArray(True) imgAppend = vtk.vtkImageAppend() imgAppend.SetAppendAxis(2) # Z for ii in range(self.Bases[node_id].shape[1]): coeffs = VN.numpy_to_vtk(self.Bases[node_id][:,ii]*100, deep=True) coeffs.SetName('coefficient') c_sign = VN.numpy_to_vtk(N.sign(self.Bases[node_id][:,ii]), deep=True) c_sign.SetName('sign') self.WordleTable.RemoveColumn(2) self.WordleTable.RemoveColumn(1) self.WordleTable.AddColumn(coeffs) self.WordleTable.AddColumn(c_sign) self.WordleView.RemoveAllRepresentations() self.WordleView.AddRepresentationFromInput(self.WordleTable) self.WordleTable.Modified() img = vtk.vtkImageData() img.DeepCopy(self.WordleView.GetImageData(antialias)) img.GetPointData().GetScalars().SetName('DiffIntensity') imgAppend.AddInput(img) imgAppend.Update() return imgAppend.GetOutput() else: # Scaling functions coeffs are defined wrt parent node scaling functions... # Display all detail coordinates for a given leaf node # Need to create separate images (Z) for each column of matrix result if self.isCompressed: # V now already chopped to AmbientDimension # Compute all detail images for that dimension # print "DS Calculating center image" # print node_id, self.Centers[node_id].shape, self.V.T.shape, self.cm.shape image_cols = self.V*self.Bases[node_id] imR = self.imR imC = self.imC else: image_cols = self.Bases[node_id] imR = self.imR imC = self.imC # To make it linear, it is the correct order (one image after another) to .ravel() images_linear = N.asarray(image_cols.T).ravel() intensity = VN.numpy_to_vtk(images_linear, deep=True) intensity.SetName('DiffIntensity') imageData = vtk.vtkImageData() imageData.SetOrigin(0,0,0) imageData.SetSpacing(1,1,1) imageData.SetDimensions(imR, imC, image_cols.shape[1]) imageData.GetPointData().AddArray(intensity) imageData.GetPointData().SetActiveScalars('DiffIntensity') return imageData else: raise IOError, "Can't get image until data is loaded successfully"
def __init__( self, inputobj=None, c='RdBu_r', alpha=(0.0, 0.0, 0.2, 0.4, 0.8, 1.0), alphaGradient=None, alphaUnit=1, mode=0, shade=False, spacing=None, dims=None, origin=None, mapper='smart', ): vtk.vtkVolume.__init__(self) BaseGrid.__init__(self) ################### if isinstance(inputobj, str): if "https://" in inputobj: from vedo.io import download inputobj = download(inputobj, verbose=False) # fpath elif os.path.isfile(inputobj): pass else: inputobj = sorted(glob.glob(inputobj)) ################### if 'gpu' in mapper: self._mapper = vtk.vtkGPUVolumeRayCastMapper() elif 'opengl_gpu' in mapper: self._mapper = vtk.vtkOpenGLGPUVolumeRayCastMapper() elif 'smart' in mapper: self._mapper = vtk.vtkSmartVolumeMapper() elif 'fixed' in mapper: self._mapper = vtk.vtkFixedPointVolumeRayCastMapper() elif isinstance(mapper, vtk.vtkMapper): self._mapper = mapper else: print("Error unknown mapper type", [mapper]) raise RuntimeError() self.SetMapper(self._mapper) ################### inputtype = str(type(inputobj)) #colors.printc('Volume inputtype', inputtype) if inputobj is None: img = vtk.vtkImageData() elif utils.isSequence(inputobj): if isinstance(inputobj[0], str): # scan sequence of BMP files ima = vtk.vtkImageAppend() ima.SetAppendAxis(2) pb = utils.ProgressBar(0, len(inputobj)) for i in pb.range(): f = inputobj[i] picr = vtk.vtkBMPReader() picr.SetFileName(f) picr.Update() mgf = vtk.vtkImageMagnitude() mgf.SetInputData(picr.GetOutput()) mgf.Update() ima.AddInputData(mgf.GetOutput()) pb.print('loading...') ima.Update() img = ima.GetOutput() else: if "ndarray" not in inputtype: inputobj = np.array(inputobj) if len(inputobj.shape) == 1: varr = numpy_to_vtk(inputobj, deep=True, array_type=vtk.VTK_FLOAT) else: if len(inputobj.shape) > 2: inputobj = np.transpose(inputobj, axes=[2, 1, 0]) varr = numpy_to_vtk(inputobj.ravel(order='F'), deep=True, array_type=vtk.VTK_FLOAT) varr.SetName('input_scalars') img = vtk.vtkImageData() if dims is not None: img.SetDimensions(dims) else: if len(inputobj.shape) == 1: colors.printc( "Error: must set dimensions (dims keyword) in Volume.", c='r') raise RuntimeError() img.SetDimensions(inputobj.shape) img.GetPointData().SetScalars(varr) #to convert rgb to numpy # img_scalar = data.GetPointData().GetScalars() # dims = data.GetDimensions() # n_comp = img_scalar.GetNumberOfComponents() # temp = numpy_support.vtk_to_numpy(img_scalar) # numpy_data = temp.reshape(dims[1],dims[0],n_comp) # numpy_data = numpy_data.transpose(0,1,2) # numpy_data = np.flipud(numpy_data) elif "ImageData" in inputtype: img = inputobj elif isinstance(inputobj, Volume): img = inputobj.inputdata() elif "UniformGrid" in inputtype: img = inputobj elif hasattr( inputobj, "GetOutput"): # passing vtk object, try extract imagdedata if hasattr(inputobj, "Update"): inputobj.Update() img = inputobj.GetOutput() elif isinstance(inputobj, str): from vedo.io import loadImageData, download if "https://" in inputobj: inputobj = download(inputobj, verbose=False) img = loadImageData(inputobj) else: colors.printc("Volume(): cannot understand input type:\n", inputtype, c='r') return if dims is not None: img.SetDimensions(dims) if origin is not None: img.SetOrigin(origin) ### DIFFERENT from volume.origin()! if spacing is not None: img.SetSpacing(spacing) self._data = img self._mapper.SetInputData(img) self.mode(mode).color(c).alpha(alpha).alphaGradient(alphaGradient) self.GetProperty().SetShade(True) self.GetProperty().SetInterpolationType(1) self.GetProperty().SetScalarOpacityUnitDistance(alphaUnit) # remember stuff: self._mode = mode self._color = c self._alpha = alpha self._alphaGrad = alphaGradient self._alphaUnit = alphaUnit
def straightenVolume(self, outputStraightenedVolume, curveNode, volumeNode, sliceSizeMm, outputSpacingMm, rotationAngleDeg=0.0): """ Compute straightened volume (useful for example for visualization of curved vessels) """ originalCurvePoints = curveNode.GetCurvePointsWorld() sampledPoints = vtk.vtkPoints() if not slicer.vtkMRMLMarkupsCurveNode.ResamplePoints( originalCurvePoints, sampledPoints, outputSpacingMm[2], False): return False sliceExtent = [ int(sliceSizeMm[0] / outputSpacingMm[0]), int(sliceSizeMm[1] / outputSpacingMm[1]) ] inputSpacing = volumeNode.GetSpacing() lines = vtk.vtkCellArray() lines.InsertNextCell(sampledPoints.GetNumberOfPoints()) for pointIndex in range(sampledPoints.GetNumberOfPoints()): lines.InsertCellPoint(pointIndex) sampledCurvePoly = vtk.vtkPolyData() sampledCurvePoly.SetPoints(sampledPoints) sampledCurvePoly.SetLines(lines) #print(sampledPoints.GetPoint(3)) # Get physical coordinates from voxel coordinates volumeRasToIjkTransformMatrix = vtk.vtkMatrix4x4() volumeNode.GetRASToIJKMatrix(volumeRasToIjkTransformMatrix) transformWorldToVolumeRas = vtk.vtkMatrix4x4() slicer.vtkMRMLTransformNode.GetMatrixTransformBetweenNodes( None, volumeNode.GetParentTransformNode(), transformWorldToVolumeRas) transformWorldToIjk = vtk.vtkTransform() transformWorldToIjk.Concatenate(transformWorldToVolumeRas) transformWorldToIjk.Scale(inputSpacing) transformWorldToIjk.Concatenate(volumeRasToIjkTransformMatrix) transformPolydataWorldToIjk = vtk.vtkTransformPolyDataFilter() transformPolydataWorldToIjk.SetInputData(sampledCurvePoly) transformPolydataWorldToIjk.SetTransform(transformWorldToIjk) reslicer = vtk.vtkSplineDrivenImageSlicer() append = vtk.vtkImageAppend() scaledImageData = vtk.vtkImageData() scaledImageData.ShallowCopy(volumeNode.GetImageData()) scaledImageData.SetSpacing(inputSpacing) reslicer.SetInputData(scaledImageData) reslicer.SetPathConnection(transformPolydataWorldToIjk.GetOutputPort()) reslicer.SetSliceExtent(*sliceExtent) reslicer.SetSliceSpacing(outputSpacingMm[0], outputSpacingMm[1]) reslicer.SetIncidence(vtk.vtkMath.RadiansFromDegrees(rotationAngleDeg)) nbPoints = sampledPoints.GetNumberOfPoints() for ptId in reversed(range(nbPoints)): reslicer.SetOffsetPoint(ptId) reslicer.Update() tempSlice = vtk.vtkImageData() tempSlice.DeepCopy(reslicer.GetOutput(0)) append.AddInputData(tempSlice) append.SetAppendAxis(2) append.Update() straightenedVolumeImageData = append.GetOutput() straightenedVolumeImageData.SetOrigin(0, 0, 0) straightenedVolumeImageData.SetSpacing(1.0, 1.0, 1.0) dims = straightenedVolumeImageData.GetDimensions() ijkToRas = vtk.vtkMatrix4x4() ijkToRas.SetElement(0, 0, 0.0) ijkToRas.SetElement(1, 0, 0.0) ijkToRas.SetElement(2, 0, -outputSpacingMm[0]) ijkToRas.SetElement(0, 1, 0.0) ijkToRas.SetElement(1, 1, outputSpacingMm[1]) ijkToRas.SetElement(2, 1, 0.0) ijkToRas.SetElement(0, 2, outputSpacingMm[2]) ijkToRas.SetElement(1, 2, 0.0) ijkToRas.SetElement(2, 2, 0.0) outputStraightenedVolume.SetIJKToRASMatrix(ijkToRas) outputStraightenedVolume.SetAndObserveImageData( straightenedVolumeImageData) outputStraightenedVolume.CreateDefaultDisplayNodes() return True
def main(): fn = get_program_parameters() # A script to test the stencil filter with a polydata stencil. # Image pipeline reader = vtk.vtkPNGReader() reader.SetDataSpacing(0.8, 0.8, 1.5) reader.SetDataOrigin(0.0, 0.0, 0.0) reader.SetFileName(fn) sphere = vtk.vtkSphereSource() sphere.SetPhiResolution(12) sphere.SetThetaResolution(12) sphere.SetCenter(102, 102, 0) sphere.SetRadius(60) triangle = vtk.vtkTriangleFilter() triangle.SetInputConnection(sphere.GetOutputPort()) stripper = vtk.vtkStripper() stripper.SetInputConnection(triangle.GetOutputPort()) dataToStencil = vtk.vtkPolyDataToImageStencil() dataToStencil.SetInputConnection(stripper.GetOutputPort()) dataToStencil.SetOutputSpacing(0.8, 0.8, 1.5) dataToStencil.SetOutputOrigin(0.0, 0.0, 0.0) stencil = vtk.vtkImageStencil() stencil.SetInputConnection(reader.GetOutputPort()) stencil.SetStencilConnection(dataToStencil.GetOutputPort()) stencil.ReverseStencilOn() stencil.SetBackgroundValue(500) # test again with a contour reader2 = vtk.vtkPNGReader() reader2.SetDataSpacing(0.8, 0.8, 1.5) reader2.SetDataOrigin(0.0, 0.0, 0.0) reader2.SetFileName(fn) plane = vtk.vtkPlane() plane.SetOrigin(0, 0, 0) plane.SetNormal(0, 0, 1) cutter = vtk.vtkCutter() cutter.SetInputConnection(sphere.GetOutputPort()) cutter.SetCutFunction(plane) stripper2 = vtk.vtkStripper() stripper2.SetInputConnection(cutter.GetOutputPort()) dataToStencil2 = vtk.vtkPolyDataToImageStencil() dataToStencil2.SetInputConnection(stripper2.GetOutputPort()) dataToStencil2.SetOutputSpacing(0.8, 0.8, 1.5) dataToStencil2.SetOutputOrigin(0.0, 0.0, 0.0) stencil2 = vtk.vtkImageStencil() stencil2.SetInputConnection(reader2.GetOutputPort()) stencil2.SetStencilConnection(dataToStencil2.GetOutputPort()) stencil2.SetBackgroundValue(500) imageAppend = vtk.vtkImageAppend() imageAppend.SetInputConnection(stencil.GetOutputPort()) imageAppend.AddInputConnection(stencil2.GetOutputPort()) viewer = vtk.vtkImageViewer() interator = vtk.vtkRenderWindowInteractor() viewer.SetInputConnection(imageAppend.GetOutputPort()) viewer.SetupInteractor(interator) viewer.SetZSlice(0) viewer.SetColorWindow(2000) viewer.SetColorLevel(1000) viewer.GetRenderWindow().SetWindowName('PolyDataToImageDataStencil') viewer.Render() interator.Start()
def Execute(self): if self.Mesh == None: self.PrintError('Error: no Mesh.') ## if (self.FOVNormal != [0.0, 0.0, 1.0]): ## ## translation = [-self.FOVCenter[0], -self.FOVCenter[1], -self.FOVCenter[2]] ## ## referenceNormal = [0.0, 0.0, 1.0] ## rotationAxis = [0.0, 0.0, 0.0] ## vtk.vtkMath.Normalize(self.FOVNormal) ## vtk.vtkMath.Cross(self.FOVNormal,referenceNormal,rotationAxis) ## angle = self.AngleBetweenNormals(referenceNormal,self.FOVNormal) / vtk.vtkMath.Pi() * 180.0 ## ## transform = vtk.vtkTransform() ## transform.PostMultiply() ## transform.Translate(translation) ## transform.RotateWXYZ(angle,rotationAxis) ## transform.Translate(self.FOVCenter) ## ## transformFilter = vtk.vtkTransformFilter() ## transformFilter.SetInput(self.Mesh) ## transformFilter.SetTransform(transform) ## transformFilter.Update() ## ## acquiredMesh = transformFilter.GetOutput() if (self.KSpaceDimensionality == 3) or not self.SliceModel: origin = [self.FOVCenter[0] - self.FOV[0]/2.0, self.FOVCenter[1] - self.FOV[1]/2.0, self.FOVCenter[2] - self.FOV[2]/2.0] spacing = [self.FOV[0] / self.MatrixSize[0], self.FOV[1] / self.MatrixSize[1], self.FOV[2] / self.MatrixSize[2]] self.KSpace = self.AcquireKSpace(self.Mesh,origin,spacing) elif self.KSpaceDimensionality == 2: kSpaceAppend = vtk.vtkImageAppend() kSpaceAppend.SetAppendAxis(2) sliceLocations = [] sliceLocation = self.FOVCenter[2] - self.FOV[2]/2.0 while (sliceLocation < self.FOVCenter[2] + self.FOV[2]/2.0): sliceLocations.append(sliceLocation) sliceLocation += self.SliceSpacing spacing = [self.FOV[0] / self.MatrixSize[0], self.FOV[1] / self.MatrixSize[1], self.FOV[2] / self.MatrixSize[2]] bounds = self.Mesh.GetBounds() for sliceLocation in sliceLocations: self.PrintLog("Processing slice at" + float(sliceLocation)) origin = [self.FOVCenter[0] - self.FOV[0]/2.0, self.FOVCenter[1] - self.FOV[1]/2.0, sliceLocation] clipper1 = vtk.vtkClipDataSet() clipper1.SetInput(self.Mesh) clipper1.InsideOutOff() plane1 = vtk.vtkPlane() plane1.SetNormal(0.0,0.0,1.0) plane1.SetOrigin(0.0,0.0,sliceLocation - self.SliceThickness / 2.0) clipper1.SetClipFunction(plane1) clipper1.Update() clipper2 = vtk.vtkClipDataSet() clipper2.SetInput(clipper1.GetOutput()) clipper2.InsideOutOn() plane2 = vtk.vtkPlane() plane2.SetNormal(0.0,0.0,1.0) plane2.SetOrigin(0.0,0.0,sliceLocation + self.SliceThickness / 2.0) clipper2.SetClipFunction(plane2) clipper2.Update() clipper2Bounds = clipper2.GetOutput().GetBounds() cleaner = vtk.vtkExtractUnstructuredGrid() cleaner.SetInput(clipper2.GetOutput()) cleaner.ExtentClippingOn() cleaner.SetExtent(clipper2Bounds[0],clipper2Bounds[1], clipper2Bounds[2],clipper2Bounds[3], sliceLocation-self.SliceThickness/2.0,sliceLocation+self.SliceThickness/2.0) cleaner.Update() tetraFilter = vtk.vtkDataSetTriangleFilter() tetraFilter.SetInput(cleaner.GetOutput()) tetraFilter.Update() sliceMesh = tetraFilter.GetOutput() self.PrintLog("Number of integration elements:" + int(sliceMesh.GetNumberOfCells())) sliceKSpace = self.AcquireKSpace(sliceMesh,origin,spacing) kSpaceAppend.AddInput(sliceKSpace) kSpaceAppend.Update() self.KSpace = self.ComputeKSpaceOperation(kSpaceAppend.GetOutput())
def getBoundedMap(self, baseImage, dataLocation, map_cut_size, map_border_size): baseImage.Update() baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] y0 = baseExtent[2] y1 = baseExtent[3] imageLen = [x1 - x0 + 1, y1 - y0 + 1] selectionDim = [map_cut_size[0] / 2, map_cut_size[1] / 2] dataXLoc = dataLocation[0] imageInfo = vtk.vtkImageChangeInformation() dataYbounds = [ dataLocation[1] - selectionDim[1], dataLocation[1] + selectionDim[1] ] vertExtent = [y0, y1] bounded_dims = None if dataYbounds[0] > -90.0: yOffset = dataYbounds[0] + 90.0 extOffset = int(round((yOffset / 180.0) * imageLen[1])) vertExtent[0] = y0 + extOffset self.y0 = dataYbounds[0] if dataYbounds[1] < 90.0: yOffset = 90.0 - dataYbounds[1] extOffset = int(round((yOffset / 180.0) * imageLen[1])) vertExtent[1] = y1 - extOffset overlapsBorder = ( self.NormalizeMapLon(dataLocation[0] - selectionDim[0]) > self.NormalizeMapLon(dataLocation[0] + selectionDim[0])) if overlapsBorder: cut0 = self.NormalizeMapLon(dataXLoc + selectionDim[0]) sliceSize = imageLen[0] * ((cut0 - self.map_cut) / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent = list(baseExtent) extent[0:2] = [x0, x0 + sliceCoord - 1] clip0 = vtk.vtkImageClip() clip0.SetInput(baseImage) clip0.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5]) size0 = extent[1] - extent[0] + 1 self.x0 = dataLocation[0] - selectionDim[0] cut1 = self.NormalizeMapLon(self.x0) sliceSize = imageLen[0] * ((cut1 - self.map_cut) / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent[0:2] = [x0 + sliceCoord, x1] clip1 = vtk.vtkImageClip() clip1.SetInput(baseImage) clip1.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5]) size1 = extent[1] - extent[0] + 1 # print "Set Corner pos: %s, cuts: %s " % ( str(self.x0), str( (cut0, cut1) ) ) append = vtk.vtkImageAppend() append.SetAppendAxis(0) append.AddInput(clip1.GetOutput()) append.AddInput(clip0.GetOutput()) bounded_dims = (size0 + size1, vertExtent[1] - vertExtent[0] + 1) imageInfo.SetInputConnection(append.GetOutputPort()) else: self.x0 = dataXLoc - selectionDim[0] cut0 = self.NormalizeMapLon(self.x0) sliceSize = imageLen[0] * ((cut0 - self.map_cut) / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent = list(baseExtent) extent[0] = x0 + sliceCoord - 1 cut1 = self.NormalizeMapLon(dataXLoc + selectionDim[0]) sliceSize = imageLen[0] * ((cut1 - self.map_cut) / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent[1] = x0 + sliceCoord clip = vtk.vtkImageClip() clip.SetInput(baseImage) clip.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5]) bounded_dims = (extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1) # print "Set Corner pos: %s, dataXLoc: %s " % ( str(self.x0), str( (dataXLoc, selectionDim[0]) ) ) imageInfo.SetInputConnection(clip.GetOutputPort()) imageInfo.SetOutputOrigin(0.0, 0.0, 0.0) imageInfo.SetOutputExtentStart(0, 0, 0) imageInfo.SetOutputSpacing(baseSpacing[0], baseSpacing[1], baseSpacing[2]) result = imageInfo.GetOutput() result.Update() return result, bounded_dims
def getBoundedMap(self, baseImage, dataLocation, map_cut_size): baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] y0 = baseExtent[2] y1 = baseExtent[3] imageLen = [x1 - x0 + 1, y1 - y0 + 1] selectionDim = [map_cut_size[0] / 2, map_cut_size[1] / 2] dataXLoc = NormalizeLon(dataLocation[0]) imageInfo = vtk.vtkImageChangeInformation() dataYbounds = [ dataLocation[1] - selectionDim[1], dataLocation[1] + selectionDim[1] ] vertExtent = [y0, y1] bounded_dims = None if dataYbounds[0] > -90.0: yOffset = dataYbounds[0] + 90.0 extOffset = int(round((yOffset / 180.0) * imageLen[1])) vertExtent[0] = y0 + extOffset self.y0 = dataYbounds[0] if dataYbounds[1] < 90.0: yOffset = 90.0 - dataYbounds[1] extOffset = int(round((yOffset / 180.0) * imageLen[1])) vertExtent[1] = y1 - extOffset if ((dataXLoc > selectionDim[0]) and (dataXLoc < (360 - selectionDim[0]))): cut0 = dataXLoc - selectionDim[0] sliceSize = imageLen[0] * (cut0 / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent = list(baseExtent) extent[0] = x0 + sliceCoord - 1 cut1 = dataXLoc + selectionDim[0] sliceSize = imageLen[0] * (cut1 / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent[1] = x0 + sliceCoord clip = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip.SetInput(baseImage) else: clip.SetInputData(baseImage) clip.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5]) self.x0 = cut0 bounded_dims = (extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1) imageInfo.SetInputConnection(clip.GetOutputPort()) else: cut0 = NormalizeLon(dataXLoc + selectionDim[0]) sliceSize = imageLen[0] * (cut0 / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent = list(baseExtent) extent[0:2] = [x0, x0 + sliceCoord - 1] clip0 = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip0.SetInput(baseImage) else: clip0.SetInputData(baseImage) clip0.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5]) size0 = extent[1] - extent[0] + 1 cut1 = NormalizeLon(dataLocation[0] - selectionDim[0]) sliceSize = imageLen[0] * (cut1 / 360.0) sliceCoord = int(round(x0 + sliceSize)) extent[0:2] = [x0 + sliceCoord, x1] clip1 = vtk.vtkImageClip() if vtk.VTK_MAJOR_VERSION <= 5: clip1.SetInput(baseImage) else: clip1.SetInputData(baseImage) clip1.SetOutputWholeExtent(extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5]) size1 = extent[1] - extent[0] + 1 self.x0 = cut1 append = vtk.vtkImageAppend() append.SetAppendAxis(0) append.AddInput(clip1.GetOutput()) append.AddInput(clip0.GetOutput()) bounded_dims = (size0 + size1, vertExtent[1] - vertExtent[0] + 1) imageInfo.SetInputConnection(append.GetOutputPort()) imageInfo.SetOutputOrigin(0.0, 0.0, 0.0) imageInfo.SetOutputExtentStart(0, 0, 0) imageInfo.SetOutputSpacing(baseSpacing[0], baseSpacing[1], baseSpacing[2]) imageInfo.Update() result = imageInfo.GetOutput() return result, bounded_dims
magnify2 = vtk.vtkImageMagnify() magnify2.SetInputConnection(reader.GetOutputPort()) magnify2.SetMagnificationFactors(IMAGE_MAG_X, IMAGE_MAG_Y, IMAGE_MAG_Z) magnify2.ReleaseDataFlagOn() # a filter that does in place processing (magnify ReleaseDataFlagOn) cursor = vtk.vtkImageCursor3D() cursor.SetInputConnection(magnify1.GetOutputPort()) cursor.SetCursorPosition(CURSOR_X * IMAGE_MAG_X, CURSOR_Y * IMAGE_MAG_Y, CURSOR_Z * IMAGE_MAG_Z) cursor.SetCursorValue(255) cursor.SetCursorRadius(50 * IMAGE_MAG_X) # stream to increase coverage of in place filter. # put the two together in one image imageAppend = vtk.vtkImageAppend() imageAppend.SetAppendAxis(0) imageAppend.AddInputConnection(magnify2.GetOutputPort()) imageAppend.AddInputConnection(cursor.GetOutputPort()) viewer = vtk.vtkImageViewer() viewer.SetInputConnection(imageAppend.GetOutputPort()) viewer.SetZSlice(CURSOR_Z * IMAGE_MAG_Z) viewer.SetColorWindow(200) viewer.SetColorLevel(80) # viewer DebugOn viewer.Render() viewer.SetPosition(50, 50) # make interface viewer.Render()
def __init__( self, inputobj=None, c=('b', 'lb', 'lg', 'y', 'r'), alpha=(0.0, 0.0, 0.2, 0.4, 0.8, 1), alphaGradient=None, mode=0, origin=None, spacing=None, shape=None, mapperType='smart', ): vtk.vtkVolume.__init__(self) ActorBase.__init__(self) inputtype = str(type(inputobj)) #colors.printc('Volume inputtype', inputtype) if isinstance(inputobj, str): import glob inputobj = sorted(glob.glob(inputobj)) if inputobj is None: img = vtk.vtkImageData() elif utils.isSequence(inputobj): if isinstance(inputobj[0], str): # scan sequence of BMP files ima = vtk.vtkImageAppend() ima.SetAppendAxis(2) pb = utils.ProgressBar(0, len(inputobj)) for i in pb.range(): f = inputobj[i] picr = vtk.vtkBMPReader() picr.SetFileName(f) picr.Update() mgf = vtk.vtkImageMagnitude() mgf.SetInputData(picr.GetOutput()) mgf.Update() ima.AddInputData(mgf.GetOutput()) pb.print('loading..') ima.Update() img = ima.GetOutput() else: if "ndarray" not in inputtype: inputobj = np.array(inputobj) varr = numpy_to_vtk(inputobj.ravel(order='F'), deep=True, array_type=vtk.VTK_FLOAT) varr.SetName('input_scalars') img = vtk.vtkImageData() if shape is not None: img.SetDimensions(shape) else: img.SetDimensions(inputobj.shape) img.GetPointData().SetScalars(varr) #to convert rgb to numpy # img_scalar = data.GetPointData().GetScalars() # dims = data.GetDimensions() # n_comp = img_scalar.GetNumberOfComponents() # temp = numpy_support.vtk_to_numpy(img_scalar) # numpy_data = temp.reshape(dims[1],dims[0],n_comp) # numpy_data = numpy_data.transpose(0,1,2) # numpy_data = np.flipud(numpy_data) elif "ImageData" in inputtype: img = inputobj elif "UniformGrid" in inputtype: img = inputobj elif "UnstructuredGrid" in inputtype: img = inputobj mapperType = 'tetra' elif hasattr( inputobj, "GetOutput"): # passing vtk object, try extract imagdedata if hasattr(inputobj, "Update"): inputobj.Update() img = inputobj.GetOutput() else: colors.printc("Volume(): cannot understand input type:\n", inputtype, c=1) return if 'gpu' in mapperType: self._mapper = vtk.vtkGPUVolumeRayCastMapper() elif 'opengl_gpu' in mapperType: self._mapper = vtk.vtkOpenGLGPUVolumeRayCastMapper() elif 'smart' in mapperType: self._mapper = vtk.vtkSmartVolumeMapper() elif 'fixed' in mapperType: self._mapper = vtk.vtkFixedPointVolumeRayCastMapper() elif 'tetra' in mapperType: self._mapper = vtk.vtkProjectedTetrahedraMapper() elif 'unstr' in mapperType: self._mapper = vtk.vtkUnstructuredGridVolumeRayCastMapper() else: print("Error unknown mapperType", mapperType) raise RuntimeError() if origin is not None: img.SetOrigin(origin) if spacing is not None: img.SetSpacing(spacing) if shape is not None: img.SetDimensions(shape) self._imagedata = img self._mapper.SetInputData(img) self.SetMapper(self._mapper) self.mode(mode).color(c).alpha(alpha).alphaGradient(alphaGradient) self.GetProperty().SetInterpolationType(1) # remember stuff: self._mode = mode self._color = c self._alpha = alpha self._alphaGrad = alphaGradient
magnify2.SetInputConnection(reader.GetOutputPort()) magnify2.SetMagnificationFactors(IMAGE_MAG_X, IMAGE_MAG_Y, IMAGE_MAG_Z) magnify2.ReleaseDataFlagOn() # a filter that does in place processing (magnify ReleaseDataFlagOn) cursor = vtk.vtkImageCursor3D() cursor.SetInputConnection(magnify1.GetOutputPort()) cursor.SetCursorPosition(CURSOR_X * IMAGE_MAG_X, CURSOR_Y * IMAGE_MAG_Y, CURSOR_Z * IMAGE_MAG_Z) cursor.SetCursorValue(255) cursor.SetCursorRadius(50 * IMAGE_MAG_X) # stream to increase coverage of in place filter. # put the two together in one image imageAppend = vtk.vtkImageAppend() imageAppend.SetAppendAxis(0) imageAppend.AddInputConnection(magnify2.GetOutputPort()) imageAppend.AddInputConnection(cursor.GetOutputPort()) viewer = vtk.vtkImageViewer() viewer.SetInputConnection(imageAppend.GetOutputPort()) viewer.SetZSlice(CURSOR_Z * IMAGE_MAG_Z) viewer.SetColorWindow(200) viewer.SetColorLevel(80) # viewer DebugOn viewer.Render() viewer.SetPosition(50, 50) # make interface viewer.Render()
def CreateImageData(self, filelist, zspacing, size, bits): message = _("Generating multiplanar visualization...") if not const.VTK_WARNING: log_path = os.path.join(const.USER_LOG_DIR, 'vtkoutput.txt') fow = vtk.vtkFileOutputWindow() fow.SetFileName(log_path) ow = vtk.vtkOutputWindow() ow.SetInstance(fow) x,y = size px, py = utils.predict_memory(len(filelist), x, y, bits) utils.debug("Image Resized to >>> %f x %f" % (px, py)) if (x == px) and (y == py): const.REDUCE_IMAGEDATA_QUALITY = 0 else: const.REDUCE_IMAGEDATA_QUALITY = 1 if not(const.REDUCE_IMAGEDATA_QUALITY): update_progress= vtk_utils.ShowProgress(1, dialog_type = "ProgressDialog") array = vtk.vtkStringArray() for x in range(len(filelist)): if not self.running: return False array.InsertValue(x,filelist[x]) if not self.running: return False reader = vtkgdcm.vtkGDCMImageReader() reader.SetFileNames(array) reader.AddObserver("ProgressEvent", lambda obj,evt: update_progress(reader,message)) reader.Update() if not self.running: reader.AbortExecuteOn() return False # The zpacing is a DicomGroup property, so we need to set it imagedata = vtk.vtkImageData() imagedata.DeepCopy(reader.GetOutput()) spacing = imagedata.GetSpacing() imagedata.SetSpacing(spacing[0], spacing[1], zspacing) else: update_progress= vtk_utils.ShowProgress(2*len(filelist), dialog_type = "ProgressDialog") # Reformat each slice and future append them appender = vtk.vtkImageAppend() appender.SetAppendAxis(2) #Define Stack in Z # Reformat each slice for x in range(len(filelist)): # TODO: We need to check this automatically according # to each computer's architecture # If the resolution of the matrix is too large if not self.running: return False reader = vtkgdcm.vtkGDCMImageReader() reader.SetFileName(filelist[x]) reader.AddObserver("ProgressEvent", lambda obj,evt: update_progress(reader,message)) reader.Update() #Resample image in x,y dimension slice_imagedata = ResampleImage2D(reader.GetOutput(), px, py, update_progress) #Stack images in Z axes appender.AddInput(slice_imagedata) #appender.AddObserver("ProgressEvent", lambda obj,evt:update_progress(appender)) appender.Update() # The zpacing is a DicomGroup property, so we need to set it if not self.running: return False imagedata = vtk.vtkImageData() imagedata.DeepCopy(appender.GetOutput()) spacing = imagedata.GetSpacing() imagedata.SetSpacing(spacing[0], spacing[1], zspacing) imagedata.AddObserver("ProgressEvent", lambda obj,evt: update_progress(imagedata,message)) imagedata.Update() return imagedata
def CreateImageData(self, filelist, zspacing, size, bits): message = _("Generating multiplanar visualization...") if not const.VTK_WARNING: log_path = os.path.join(const.LOG_FOLDER, 'vtkoutput.txt') fow = vtk.vtkFileOutputWindow() fow.SetFileName(log_path) ow = vtk.vtkOutputWindow() ow.SetInstance(fow) x, y = size px, py = utils.predict_memory(len(filelist), x, y, bits) utils.debug("Image Resized to >>> %f x %f" % (px, py)) if (x == px) and (y == py): const.REDUCE_IMAGEDATA_QUALITY = 0 else: const.REDUCE_IMAGEDATA_QUALITY = 1 if not (const.REDUCE_IMAGEDATA_QUALITY): update_progress = vtk_utils.ShowProgress( 1, dialog_type="ProgressDialog") array = vtk.vtkStringArray() for x in xrange(len(filelist)): if not self.running: return False array.InsertValue(x, filelist[x]) if not self.running: return False reader = vtkgdcm.vtkGDCMImageReader() reader.SetFileNames(array) reader.AddObserver( "ProgressEvent", lambda obj, evt: update_progress(reader, message)) reader.Update() if not self.running: reader.AbortExecuteOn() return False # The zpacing is a DicomGroup property, so we need to set it imagedata = vtk.vtkImageData() imagedata.DeepCopy(reader.GetOutput()) spacing = imagedata.GetSpacing() imagedata.SetSpacing(spacing[0], spacing[1], zspacing) else: update_progress = vtk_utils.ShowProgress( 2 * len(filelist), dialog_type="ProgressDialog") # Reformat each slice and future append them appender = vtk.vtkImageAppend() appender.SetAppendAxis(2) #Define Stack in Z # Reformat each slice for x in xrange(len(filelist)): # TODO: We need to check this automatically according # to each computer's architecture # If the resolution of the matrix is too large if not self.running: return False reader = vtkgdcm.vtkGDCMImageReader() reader.SetFileName(filelist[x]) reader.AddObserver( "ProgressEvent", lambda obj, evt: update_progress(reader, message)) reader.Update() #Resample image in x,y dimension slice_imagedata = ResampleImage2D(reader.GetOutput(), px, py, update_progress) #Stack images in Z axes appender.AddInput(slice_imagedata) #appender.AddObserver("ProgressEvent", lambda obj,evt:update_progress(appender)) appender.Update() # The zpacing is a DicomGroup property, so we need to set it if not self.running: return False imagedata = vtk.vtkImageData() imagedata.DeepCopy(appender.GetOutput()) spacing = imagedata.GetSpacing() imagedata.SetSpacing(spacing[0], spacing[1], zspacing) imagedata.AddObserver( "ProgressEvent", lambda obj, evt: update_progress(imagedata, message)) imagedata.Update() return imagedata
def GetProjectedImages(self, IDlist, wordle_on = True, antialias = False): """Given a list of IDs selected from a parallel coordinates plot, returns a vtkImageData with all of the projected (reduced dimensionality by SVD) images for those IDs. (e.g. typically 120 dim rather than original 768 dim for MNIST digits)""" if self.data_loaded: if self.WordleImages and wordle_on: self.WordleView.SetRandomSeed(0); # Need to create separate images (Z) for each column of matrix result # Bases is D x N matrix if self.isCompressed: Xtmp = self.X[:,IDlist]*self.V # numpy should automatically do tiling!! X_orig = Xtmp + self.cm else: X_orig = self.X[:,IDlist] self.WordleView.SetColorByArray(False) self.WordleView.Update() imgAppend = vtk.vtkImageAppend() imgAppend.SetAppendAxis(2) # Z for ii in range(X_orig.shape[1]): coeffs = VN.numpy_to_vtk(X_orig[:,ii]*100, deep=True) coeffs.SetName('coefficient') c_sign = VN.numpy_to_vtk(N.sign(X_orig[:,ii]), deep=True) c_sign.SetName('sign') self.WordleTable.RemoveColumn(2) self.WordleTable.RemoveColumn(1) self.WordleTable.AddColumn(coeffs) self.WordleTable.AddColumn(c_sign) self.WordleView.RemoveAllRepresentations() self.WordleView.AddRepresentationFromInput(self.WordleTable) self.WordleTable.Modified() img = vtk.vtkImageData() img.DeepCopy(self.WordleView.GetImageData(antialias)) img.GetPointData().GetScalars().SetName('Intensity') imgAppend.AddInput(img) imgAppend.Update() return imgAppend.GetOutput() else: if self.isCompressed: # V now already chopped to AmbientDimension Xtmp = (self.V*self.X[:,IDlist]).T # numpy should automatically do tiling!! X_orig = Xtmp + self.cm imR = self.imR imC = self.imC else: X_orig = self.X[:,IDlist] imR = self.imR imC = self.imC # To make it linear, it is the correct order (one image after another) to .ravel() X_linear = N.asarray(X_orig.T).ravel() # Going ahead and using numpy_support here... Much faster!!! Xvtk = VN.numpy_to_vtk(X_linear, deep=True) # even with the (necessary) deep copy Xvtk.SetName('Intensity') imageData = vtk.vtkImageData() imageData.SetOrigin(0,0,0) imageData.SetSpacing(1,1,1) imageData.SetDimensions(imR, imC, X_orig.shape[1]) imageData.GetPointData().AddArray(Xvtk) imageData.GetPointData().SetActiveScalars('Intensity') return imageData else: raise IOError, "Can't get image until data is loaded successfully"
def getBoundedMap( self, baseImage, dataLocation, map_cut_size ): baseImage.Update() baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] y0 = baseExtent[2] y1 = baseExtent[3] imageLen = [ x1 - x0 + 1, y1 - y0 + 1 ] selectionDim = [ map_cut_size[0]/2, map_cut_size[1]/2 ] dataXLoc = NormalizeLon( dataLocation[0] ) imageInfo = vtk.vtkImageChangeInformation() dataYbounds = [ dataLocation[1]-selectionDim[1], dataLocation[1]+selectionDim[1] ] vertExtent = [ y0, y1 ] bounded_dims = None if dataYbounds[0] > -90.0: yOffset = dataYbounds[0] + 90.0 extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) ) vertExtent[0] = y0 + extOffset self.y0 = dataYbounds[0] if dataYbounds[1] < 90.0: yOffset = 90.0 - dataYbounds[1] extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) ) vertExtent[1] = y1 - extOffset if (( dataXLoc > selectionDim[0] ) and ( dataXLoc < ( 360 - selectionDim[0]) )): cut0 = dataXLoc - selectionDim[0] sliceSize = imageLen[0] * ( cut0 / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent = list( baseExtent ) extent[0] = x0 + sliceCoord - 1 cut1 = dataXLoc + selectionDim[0] sliceSize = imageLen[0] * ( cut1 / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent[1] = x0 + sliceCoord clip = vtk.vtkImageClip() clip.SetInput( baseImage ) clip.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] ) self.x0 = cut0 bounded_dims = ( extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1 ) imageInfo.SetInputConnection( clip.GetOutputPort() ) else: cut0 = NormalizeLon( dataXLoc + selectionDim[0] ) sliceSize = imageLen[0] * ( cut0 / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent = list( baseExtent ) extent[0:2] = [ x0, x0 + sliceCoord - 1 ] clip0 = vtk.vtkImageClip() clip0.SetInput( baseImage ) clip0.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] ) size0 = extent[1] - extent[0] + 1 cut1 = NormalizeLon( dataLocation[0] - selectionDim[0] ) sliceSize = imageLen[0] * ( cut1 / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent[0:2] = [ x0 + sliceCoord, x1 ] clip1 = vtk.vtkImageClip() clip1.SetInput( baseImage ) clip1.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] ) size1 = extent[1] - extent[0] + 1 self.x0 = cut1 append = vtk.vtkImageAppend() append.SetAppendAxis( 0 ) append.AddInput( clip1.GetOutput() ) append.AddInput( clip0.GetOutput() ) bounded_dims = ( size0 + size1, vertExtent[1] - vertExtent[0] + 1 ) imageInfo.SetInputConnection( append.GetOutputPort() ) imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 ) imageInfo.SetOutputExtentStart( 0, 0, 0 ) imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] ) result = imageInfo.GetOutput() result.Update() return result, bounded_dims
def Execute(self): if self.Mesh == None: self.PrintError('Error: no Mesh.') ## if (self.FOVNormal != [0.0, 0.0, 1.0]): ## ## translation = [-self.FOVCenter[0], -self.FOVCenter[1], -self.FOVCenter[2]] ## ## referenceNormal = [0.0, 0.0, 1.0] ## rotationAxis = [0.0, 0.0, 0.0] ## vtk.vtkMath.Normalize(self.FOVNormal) ## vtk.vtkMath.Cross(self.FOVNormal,referenceNormal,rotationAxis) ## angle = self.AngleBetweenNormals(referenceNormal,self.FOVNormal) / vtk.vtkMath.Pi() * 180.0 ## ## transform = vtk.vtkTransform() ## transform.PostMultiply() ## transform.Translate(translation) ## transform.RotateWXYZ(angle,rotationAxis) ## transform.Translate(self.FOVCenter) ## ## transformFilter = vtk.vtkTransformFilter() ## transformFilter.SetInput(self.Mesh) ## transformFilter.SetTransform(transform) ## transformFilter.Update() ## ## acquiredMesh = transformFilter.GetOutput() if (self.KSpaceDimensionality == 3) or not self.SliceModel: origin = [ self.FOVCenter[0] - self.FOV[0] / 2.0, self.FOVCenter[1] - self.FOV[1] / 2.0, self.FOVCenter[2] - self.FOV[2] / 2.0 ] spacing = [ self.FOV[0] / self.MatrixSize[0], self.FOV[1] / self.MatrixSize[1], self.FOV[2] / self.MatrixSize[2] ] self.KSpace = self.AcquireKSpace(self.Mesh, origin, spacing) elif self.KSpaceDimensionality == 2: kSpaceAppend = vtk.vtkImageAppend() kSpaceAppend.SetAppendAxis(2) sliceLocations = [] sliceLocation = self.FOVCenter[2] - self.FOV[2] / 2.0 while (sliceLocation < self.FOVCenter[2] + self.FOV[2] / 2.0): sliceLocations.append(sliceLocation) sliceLocation += self.SliceSpacing spacing = [ self.FOV[0] / self.MatrixSize[0], self.FOV[1] / self.MatrixSize[1], self.FOV[2] / self.MatrixSize[2] ] bounds = self.Mesh.GetBounds() for sliceLocation in sliceLocations: self.PrintLog("Processing slice at" + float(sliceLocation)) origin = [ self.FOVCenter[0] - self.FOV[0] / 2.0, self.FOVCenter[1] - self.FOV[1] / 2.0, sliceLocation ] clipper1 = vtk.vtkClipDataSet() clipper1.SetInput(self.Mesh) clipper1.InsideOutOff() plane1 = vtk.vtkPlane() plane1.SetNormal(0.0, 0.0, 1.0) plane1.SetOrigin(0.0, 0.0, sliceLocation - self.SliceThickness / 2.0) clipper1.SetClipFunction(plane1) clipper1.Update() clipper2 = vtk.vtkClipDataSet() clipper2.SetInput(clipper1.GetOutput()) clipper2.InsideOutOn() plane2 = vtk.vtkPlane() plane2.SetNormal(0.0, 0.0, 1.0) plane2.SetOrigin(0.0, 0.0, sliceLocation + self.SliceThickness / 2.0) clipper2.SetClipFunction(plane2) clipper2.Update() clipper2Bounds = clipper2.GetOutput().GetBounds() cleaner = vtk.vtkExtractUnstructuredGrid() cleaner.SetInput(clipper2.GetOutput()) cleaner.ExtentClippingOn() cleaner.SetExtent(clipper2Bounds[0], clipper2Bounds[1], clipper2Bounds[2], clipper2Bounds[3], sliceLocation - self.SliceThickness / 2.0, sliceLocation + self.SliceThickness / 2.0) cleaner.Update() tetraFilter = vtk.vtkDataSetTriangleFilter() tetraFilter.SetInput(cleaner.GetOutput()) tetraFilter.Update() sliceMesh = tetraFilter.GetOutput() self.PrintLog("Number of integration elements:" + int(sliceMesh.GetNumberOfCells())) sliceKSpace = self.AcquireKSpace(sliceMesh, origin, spacing) kSpaceAppend.AddInput(sliceKSpace) kSpaceAppend.Update() self.KSpace = self.ComputeKSpaceOperation(kSpaceAppend.GetOutput())
def getBoundedMap( self, baseImage, dataLocation ): # print " @@@ MapManager: getBoundedMap " baseExtent = baseImage.GetExtent() baseSpacing = baseImage.GetSpacing() x0 = baseExtent[0] x1 = baseExtent[1] y0 = baseExtent[2] y1 = baseExtent[3] imageLen = [ x1 - x0 + 1, y1 - y0 + 1 ] selectionDim = [ self.map_cut_size[0]/2, self.map_cut_size[1]/2 ] dataXLoc = dataLocation[0] imageInfo = vtk.vtkImageChangeInformation() dataYbounds = [ dataLocation[1]-selectionDim[1], dataLocation[1]+selectionDim[1] ] vertExtent = [ y0, y1 ] bounded_dims = None if dataYbounds[0] > -90.0: yOffset = dataYbounds[0] + 90.0 extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) ) vertExtent[0] = y0 + extOffset self.y0 = dataYbounds[0] if dataYbounds[1] < 90.0: yOffset = 90.0 - dataYbounds[1] extOffset = int( round( ( yOffset / 180.0 ) * imageLen[1] ) ) vertExtent[1] = y1 - extOffset overlapsBorder = ( self.NormalizeMapLon(dataLocation[0]-selectionDim[0]) > self.NormalizeMapLon(dataLocation[0]+selectionDim[0]) ) if overlapsBorder: cut0 = self.NormalizeMapLon( dataXLoc + selectionDim[0] ) sliceSize = imageLen[0] * ( ( cut0 - self.map_cut ) / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent = list( baseExtent ) extent[0:2] = [ x0, x0 + sliceCoord - 1 ] clip0 = vtk.vtkImageClip() clip0.ClipDataOn() clip0.SetInput( baseImage ) clip0.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] ) size0 = extent[1] - extent[0] + 1 self.x0 = dataLocation[0] - selectionDim[0] cut1 = self.NormalizeMapLon( self.x0 ) sliceSize = imageLen[0] * ( ( cut1 - self.map_cut )/ 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent[0:2] = [ x0 + sliceCoord, x1 ] clip1 = vtk.vtkImageClip() clip1.ClipDataOn() if vtk.VTK_MAJOR_VERSION <= 5: clip1.SetInput( baseImage ) else: clip1.SetInputData( baseImage ) clip1.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] ) size1 = extent[1] - extent[0] + 1 # print "Set Corner pos: %s, cuts: %s " % ( str(self.x0), str( (cut0, cut1) ) ) append = vtk.vtkImageAppend() append.SetAppendAxis( 0 ) append.AddInputConnection( clip1.GetOutputPort() ) append.AddInputConnection( clip0.GetOutputPort() ) bounded_dims = ( size0 + size1, vertExtent[1] - vertExtent[0] + 1 ) imageInfo.SetInputConnection( append.GetOutputPort() ) else: self.x0 = dataXLoc - selectionDim[0] cut0 = self.NormalizeMapLon( self.x0 ) sliceSize = imageLen[0] * ( ( cut0 - self.map_cut ) / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent = list( baseExtent ) extent[0] = x0 + sliceCoord - 1 cut1 = self.NormalizeMapLon( dataXLoc + selectionDim[0] ) sliceSize = imageLen[0] * ( ( cut1 - self.map_cut ) / 360.0 ) sliceCoord = int( round( x0 + sliceSize) ) extent[1] = x0 + sliceCoord clip = vtk.vtkImageClip() clip.ClipDataOn() if vtk.VTK_MAJOR_VERSION <= 5: clip.SetInput( baseImage ) else: clip.SetInputData( baseImage ) clip.SetOutputWholeExtent( extent[0], extent[1], vertExtent[0], vertExtent[1], extent[4], extent[5] ) bounded_dims = ( extent[1] - extent[0] + 1, vertExtent[1] - vertExtent[0] + 1 ) # print "Set Corner pos: %s, dataXLoc: %s " % ( str(self.x0), str( (dataXLoc, selectionDim[0]) ) ) clip.Update() imageInfo.SetInputConnection( clip.GetOutputPort() ) imageInfo.SetOutputOrigin( 0.0, 0.0, 0.0 ) imageInfo.SetOutputExtentStart( 0, 0, 0 ) imageInfo.SetOutputSpacing( baseSpacing[0], baseSpacing[1], baseSpacing[2] ) imageInfo.Update() result = imageInfo.GetOutput() return result, bounded_dims
def __init__(self, inputobj=None): vtk.vtkImageSlice.__init__(self) Base3DProp.__init__(self) BaseVolume.__init__(self) self._mapper = vtk.vtkImageResliceMapper() self._mapper.SliceFacesCameraOn() self._mapper.SliceAtFocalPointOn() self._mapper.SetAutoAdjustImageQuality(False) self._mapper.BorderOff() self.lut = None self.property = vtk.vtkImageProperty() self.property.SetInterpolationTypeToLinear() self.SetProperty(self.property) ################### if isinstance(inputobj, str): if "https://" in inputobj: from vedo.io import download inputobj = download(inputobj, verbose=False) # fpath elif os.path.isfile(inputobj): pass else: inputobj = sorted(glob.glob(inputobj)) ################### inputtype = str(type(inputobj)) if inputobj is None: img = vtk.vtkImageData() if isinstance(inputobj, Volume): img = inputobj.imagedata() self.lut = utils.ctf2lut(inputobj) elif utils.isSequence(inputobj): if isinstance(inputobj[0], str): # scan sequence of BMP files ima = vtk.vtkImageAppend() ima.SetAppendAxis(2) pb = utils.ProgressBar(0, len(inputobj)) for i in pb.range(): f = inputobj[i] picr = vtk.vtkBMPReader() picr.SetFileName(f) picr.Update() mgf = vtk.vtkImageMagnitude() mgf.SetInputData(picr.GetOutput()) mgf.Update() ima.AddInputData(mgf.GetOutput()) pb.print('loading...') ima.Update() img = ima.GetOutput() else: if "ndarray" not in inputtype: inputobj = np.array(inputobj) if len(inputobj.shape) == 1: varr = utils.numpy2vtk(inputobj, dtype=float) else: if len(inputobj.shape) > 2: inputobj = np.transpose(inputobj, axes=[2, 1, 0]) varr = utils.numpy2vtk(inputobj.ravel(order='F'), dtype=float) varr.SetName('input_scalars') img = vtk.vtkImageData() img.SetDimensions(inputobj.shape) img.GetPointData().AddArray(varr) img.GetPointData().SetActiveScalars(varr.GetName()) elif "ImageData" in inputtype: img = inputobj elif isinstance(inputobj, Volume): img = inputobj.inputdata() elif "UniformGrid" in inputtype: img = inputobj elif hasattr( inputobj, "GetOutput"): # passing vtk object, try extract imagdedata if hasattr(inputobj, "Update"): inputobj.Update() img = inputobj.GetOutput() elif isinstance(inputobj, str): from vedo.io import loadImageData, download if "https://" in inputobj: inputobj = download(inputobj, verbose=False) img = loadImageData(inputobj) else: colors.printc("VolumeSlice: cannot understand input type:\n", inputtype, c='r') return self._data = img self._mapper.SetInputData(img) self.SetMapper(self._mapper)