def getRAWReader(self, Series_Info, Channel): """ create a tiff reader that reads then given channel of the given series """ XYDim = Series_Info['Resolution_X'] - 1 NumSect = Series_Info['Number_Sections'] - 1 XSpace = Series_Info['Voxel_Width_X'] YSpace = Series_Info['Voxel_Height_Y'] ZSpace = Series_Info['Voxel_Depth_Z'] RAWReader = vtk.vtkImageReader2() if self.progressCallback: RAWReader.AddObserver("ProgressEvent", lib.messenger.send) lib.messenger.connect(RAWReader, 'ProgressEvent', self.progressCallback) arr = vtk.vtkStringArray() for i in Channel: arr.InsertNextValue(os.path.join(self.path, i)) RAWReader.SetFileNames(arr) if Series_Info['Bit_Depth'] == 8: RAWReader.SetDataScalarTypeToUnsignedChar() elif Series_Info['Bit_Depth'] == 12: RAWReader.SetDataScalarTypeToUnsignedShort() RAWReader.FileLowerLeftOff() spacingX,spacingY,spacingZ = 1.0,1.0,1.0 if XSpace != 0.0 and YSpace != 0.0: spacingY = YSpace / XSpace if XSpace != 0.0 and ZSpace != 0.0: spacingZ = ZSpace / XSpace RAWReader.SetDataExtent(0, XYDim, 0, XYDim, 0, NumSect) RAWReader.SetDataSpacing(spacingX, spacingY, spacingZ) RAWReader.Update() return RAWReader
def getTimepoint(self, n, onlyDims = 0): """ Return the nth timepoint """ if not self.reader: self.reader = vtk.vtkImageReader2() self.reader.AddObserver('ProgressEvent', lib.messenger.send) lib.messenger.connect(self.reader, 'ProgressEvent', self.updateProgress) eval("self.reader.SetDataScalarTypeTo%s()" % self.datatype) x, y, z = self.dimensions if z == 0: z += 1 self.reader.SetDataExtent(0, x - 1, 0, y - 1, 0, z - 1) self.reader.SetFileDimensionality(3) self.reader.SetDataSpacing(self.spacing) eval("self.reader.SetDataByteOrderTo%s()" % self.endianness) #if self.tps == 1: # self.reader.SetFileName(self.imgfile) #else: # print "Switching to dataset ", self.filepattern % (n + 1) # self.reader.SetFileName(self.filepattern % (n + 1)) self.reader.SetFileName(self.dataFileName) skip = n for i in self.dimensions: skip *= i skip *= self.bytesPerPixel self.reader.SetHeaderSize(skip) self.reader.Update() print self.reader.GetOutput() return self.reader.GetOutput()
def __init__(self, module_manager): SimpleVTKClassModuleBase.__init__(self, module_manager, vtk.vtkImageReader2(), 'Processing.', (), ('vtkImageData', ), replaceDoc=True, inputFunctions=None, outputFunctions=None)
def get_image_data(): reader = vtk.vtkImageReader2() reader.SetDataScalarTypeToUnsignedShort() reader.SetFileDimensionality(2) reader.SetFilePrefix("data/slice") reader.SetDataExtent(0, 255, 0, 255, 1, 94) reader.SetDataSpacing(1, 1, 2) reader.UpdateWholeExtent() return reader.GetOutput()
def main(argv): colors = vtk.vtkNamedColors() # Parse input arguments if len(argv) != 3: print("Usage: %s Input1Filename Input2Filename e.g. Ox.jpg Gourds2.jpg" % (argv[0])) return # Read the images readerFactory = vtk.vtkImageReader2Factory() imgReader1 = vtk.vtkImageReader2() imgReader1 = readerFactory.CreateImageReader2(argv[1]) imgReader1.SetFileName(argv[1]) imgReader2 = vtk.vtkImageReader2() # imgReader2.TakeReference(readerFactory.CreateImageReader2(argv[2])) imgReader2 = readerFactory.CreateImageReader2(argv[2]) imgReader2.SetFileName(argv[2]) # Combine the images (blend takes multiple connections on the 0th input port) blend = vtk.vtkImageBlend() blend.AddInputConnection(imgReader1.GetOutputPort()) blend.AddInputConnection(imgReader2.GetOutputPort()) blend.SetOpacity(0, 0.5) blend.SetOpacity(1, 0.5) # Display the result renderWindowInteractor = vtk.vtkRenderWindowInteractor() imageViewer = vtk.vtkImageViewer2() imageViewer.SetInputConnection(blend.GetOutputPort()) imageViewer.SetupInteractor(renderWindowInteractor) imageViewer.GetRenderer().ResetCamera() imageViewer.GetRenderer().SetBackground(colors.GetColor3d("Peru")) imageViewer.GetRenderWindow().SetWindowName("CombineImages") imageViewer.GetRenderer().Render() renderWindowInteractor.Initialize() renderWindowInteractor.Start() return 0
def get_image_data(): """ Reads the image data using the class vtkImageReader2. Returns the result of the GetOutput() function call.""" reader = vtk.vtkImageReader2() reader.SetDataScalarTypeToUnsignedShort() reader.SetFileDimensionality(2) reader.SetFilePrefix("data/slice") reader.SetDataExtent(0, 255, 0, 255, 1, 94) reader.SetDataSpacing(1, 1, 2) #reader.SetDataByteOrderToBigEndian() reader.SetNumberOfScalarComponents( 1 ) reader.UpdateWholeExtent() return reader.GetOutput()
import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # --------------------------------------------------------- # renderer and interactor ren = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(ren) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) # --------------------------------------------------------- # read the volume reader = vtk.vtkImageReader2() reader.SetDataExtent(0, 63, 0, 63, 0, 92) reader.SetFileNameSliceOffset(1) reader.SetDataScalarTypeToUnsignedShort() reader.SetDataByteOrderToLittleEndian() reader.SetFilePrefix(str(VTK_DATA_ROOT) + "/Data/headsq/quarter") reader.SetDataSpacing(3.2, 3.2, 1.5) # --------------------------------------------------------- # set up the volume rendering volumeMapper = vtk.vtkVolumeTextureMapper3D() volumeMapper.SetInputConnection(reader.GetOutputPort()) volumeMapper.CroppingOn() volumeMapper.SetCroppingRegionPlanes((0.0, 141.6, 0.0, 201.6, 0.0, 138.0)) volumeColor = vtk.vtkColorTransferFunction()
def onButtonUpdate(self, evt): try: first = int(self.m_spinCtrlFirstNum.GetValue()) last = int(self.m_spinCtrlLastNum.GetValue()) except: first = last = 0 fspec = self.m_filePicker.GetPath() if self.m_check3DImage.IsChecked(): l = 0 fileName = fspec else: p0 = fspec.find('#') p1 = fspec.rfind('#') if p0 != -1: l = p1 - p0 + 1 filePrefix = fspec[0:p0] filePattern = '%%s%%0%dd' % (l) + fspec[p1 + 1:] # This is the slice that we'll try to read middle = int((first + last) / 2.0) z0 = z1 = (middle - first) fileName = (filePrefix + filePattern) % ('', middle) else: l = 0 fileName = fspec if self.bIsDICOM: # TODO: we're sorting this data in more than one place it seems... indices = np.argsort( np.array([float(f) for f in self._slice_locations])) # choose a card from the middle of the deck fileName = self._file_list[indices[len(indices) / 2]] xspacing = float(self.m_textCtrlXSpacing.GetValue()) yspacing = float(self.m_textCtrlYSpacing.GetValue()) zspacing = float(self.m_textCtrlZSpacing.GetValue()) xsize = int(self.m_textCtrlXSize.GetValue()) ysize = int(self.m_textCtrlYSize.GetValue()) zsize = int(self.m_textCtrlZSize.GetValue()) header_size = int(self.m_textCtrlHeaderSize.GetValue()) numC = int(self.m_textCtrlNumberChannels.GetValue()) # this isn't quite correct, but will do for now... swap_bytes = ( self.m_choiceDataEndian.GetStringSelection() == 'big endian') if self.m_checkRawImage.IsChecked(): reader = vtk.vtkImageReader2() reader.FileLowerLeftOn() reader.SetSwapBytes(swap_bytes) reader.SetHeaderSize(header_size) reader.SetDataSpacing(xspacing, yspacing, zspacing) reader.SetNumberOfScalarComponents(numC) dt = self.m_choiceDataType.GetStringSelection() if dt == 'unsigned char': reader.SetDataScalarTypeToUnsignedChar() elif dt == 'unsigned short': reader.SetDataScalarTypeToUnsignedShort() elif dt == 'short': reader.SetDataScalarTypeToShort() elif dt == 'int': reader.SetDataScalarTypeToInt() elif dt == 'float': reader.SetDataScalarTypeToFloat() elif dt == 'double': reader.SetDataScalarTypeToDouble() else: reader = self._reader reader.SetFileName(fileName) if self.m_check3DImage.IsChecked(): z0 = z1 = int(zsize / 2) reader.SetFileDimensionality(3) else: reader.SetFileDimensionality(2) z0 = z1 = 0 # if image is either a 3D image or using raw importer, we need to explicitly set # data extent if self.m_check3DImage.IsChecked() or self.m_checkRawImage.IsChecked(): reader.SetDataExtent(0, xsize - 1, 0, ysize - 1, z0, z1) w, h = self.m_bitmapPreview.GetSize() try: # update reader rather than image (for VTK-6 compatibility) if vtk.vtkVersion().GetVTKMajorVersion() > 5: reader.Update() else: reader.GetOutput().Update() image = reader.GetOutput() flip = self.m_checkBoxFlipImage.GetValue() wxBitmap = MicroViewIO.VTKImageToBitmap(image, w, h, flip=flip) except: w, h = self.m_bitmapPreview.GetSize() wxBitmap = wx.EmptyBitmap(w, h) logging.error("ImageImportDialog") # paste into GUI self.m_bitmapPreview.SetBitmap(wxBitmap)
def loadNRRDImage(filename): import imagingTools inFile = open(filename, 'r') tag = inFile.readline() if tag[0:8] != 'NRRD0004': print "bad format!" sys.exit() line = inFile.readline().split() while line[0] != 'type:': line = inFile.readline().split() coding = line[1] print "coding", coding while line[0] != 'dimension:': line = inFile.readline().split() dimensionality = int(line[1]) print "dimensionality", dimensionality while line[0] != 'space:': line = inFile.readline().split() space = line[1] print "space", space while line[0] != 'sizes:': line = inFile.readline().split() dimensions = (int(line[1]), int(line[2]), int(line[3])) print "dimensions", dimensions while line[0] != 'space': line = inFile.readline().split() directionX = line[2] directionY = line[3] directionZ = line[4] directionX = directionX[1:(len(directionX)) - 1].rsplit(',', 3) directionY = directionY[1:(len(directionY)) - 1].rsplit(',', 3) directionZ = directionZ[1:(len(directionZ)) - 1].rsplit(',', 3) spacing = [0, 0, 0] ordering = [] for i in range(3): if directionX[i] != '0': spacing[0] = float(directionX[i]) ordering.append(0) elif directionY[i] != '0': spacing[1] = float(directionY[i]) ordering.append(1) else: spacing[2] = float(directionZ[i]) ordering.append(2) for i in range(3): if spacing[i] < 0: spacing[i] = -spacing[i] print "spacing", spacing while line[0] != 'endian:': line = inFile.readline().split() byteorder = line[1] print "byteorder", byteorder while line[0] != 'space': line = inFile.readline().split() originStr = line[2] originSpl = originStr[1:(len(originStr)) - 1].rsplit(',', 3) origin = [float(originSpl[0]), float(originSpl[1]), float(originSpl[2])] print "origin", origin print "ordering", ordering if (space == "left-posterior-superior") or (space == "LPS"): origin[1] = -origin[1] reader = vtk.vtkImageReader2() reader.SetDataExtent( (0, dimensions[0] - 1, 0, dimensions[1] - 1, 0, dimensions[2] - 1)) # reader.SetDataDimensions(dimensions) reader.SetDataOrigin(origin) reader.SetDataSpacing([spacing[0], spacing[1], spacing[2]]) reader.SetFileDimensionality(dimensionality) filenameSp = filename.rsplit( '.', 2) # pas d'espaces ni de point dans le num du fichier! if filenameSp[1] == "nhdr": reader.SetFileName(filenameSp[0] + '.raw') else: reader.SetFileName(filename) if byteorder == 'little': reader.SetDataByteOrderToLittleEndian() else: reader.SetDataByteOrderToBigEndian() if coding == 'uchar': reader.SetDataScalarTypeToUnsignedChar() elif coding == 'char': reader.SetDataScalarTypeToUnsignedChar() elif coding == 'ushort': reader.SetDataScalarTypeToUnsignedShort() elif coding == 'short': reader.SetDataScalarTypeToUnsignedShort() elif coding == 'float': reader.SetDataScalarTypeToFloat() else: reader.SetDataScalarTypeToDouble() reader.Update() im = reader.GetOutput() # if (space == "left-posterior-superior") or (space == "LPS"): # im = imagingTools.permute(im,0,2,1) # im = imagingTools.flipImage(im,2) # #im = imagingTools.flipImage(im,0) # im = imagingTools.flipImage(im,1) return im
#!/usr/bin/env python # This example shows how to load a 3D image into VTK and then reformat # that image into a different orientation for viewing. It uses # vtkImageReslice for reformatting the image, and uses vtkImageActor # and vtkInteractorStyleImage to display the image. This InteractorStyle # forces the camera to stay perpendicular to the XY plane. import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() # Start by loading some data. reader = vtk.vtkImageReader2() reader.SetFilePrefix(VTK_DATA_ROOT + "/Data/headsq/quarter") reader.SetDataExtent(0, 63, 0, 63, 1, 93) reader.SetDataSpacing(3.2, 3.2, 1.5) reader.SetDataOrigin(0.0, 0.0, 0.0) reader.SetDataScalarTypeToUnsignedShort() reader.UpdateWholeExtent() # Calculate the center of the volume reader.Update() (xMin, xMax, yMin, yMax, zMin, zMax) = reader.GetExecutive().GetWholeExtent(reader.GetOutputInformation(0)) (xSpacing, ySpacing, zSpacing) = reader.GetOutput().GetSpacing() (x0, y0, z0) = reader.GetOutput().GetOrigin() center = [ x0 + xSpacing * 0.5 * (xMin + xMax), y0 + ySpacing * 0.5 * (yMin + yMax), z0 + zSpacing * 0.5 * (zMin + zMax)
def newImage(self): # If a new image is selected then we create an independent reader # (to prevent overwriting previous volumes with updateImage). # We do not create a new reader on each updateImage to improve performence # (avoid reallocation of the image). self.reader = vtk.vtkImageReader2()
def __init__(self): self.reader = vtk.vtkImageReader2()
def load(self, properties): try: filePath = properties['fileName'] headerInfo = ImportSliceOmaticFileReader.readHeader(filePath) scalarType = vtk.VTK_CHAR numberOfComponents = 1 sliceSize = headerInfo['dims'][0] * headerInfo['dims'][ 1] * vtk.vtkDataArray.GetDataTypeSize( scalarType) * numberOfComponents headerSize = headerInfo['headerSize'] totalFilesize = os.path.getsize(filePath) voxelDataSize = totalFilesize - headerSize maxNumberOfSlices = int(voxelDataSize / sliceSize) if headerInfo['dims'][2] > maxNumberOfSlices: logging.error( f"Tag file is expected to contain {headerInfo['dims'][2]} slices but it has only {maxNumberOfSlices}" ) return False reader = vtk.vtkImageReader2() reader.SetFileName(filePath) reader.SetFileDimensionality(3) reader.SetDataExtent(0, headerInfo['dims'][0] - 1, 0, headerInfo['dims'][1] - 1, 0, headerInfo['dims'][2] - 1) # reader.SetDataByteOrderToLittleEndian() reader.SetDataScalarType(scalarType) reader.SetNumberOfScalarComponents(numberOfComponents) reader.SetHeaderSize(headerSize) reader.SetFileLowerLeft(True) # to match input from NRRD reader reader.Update() tempLabelmapNode = slicer.mrmlScene.AddNewNodeByClass( 'vtkMRMLLabelMapVolumeNode', "__temp_SliceOmatic__") tempLabelmapNode.SetImageDataConnection(reader.GetOutputPort()) # We assume file is in LPS and invert first and second axes # to get volume in RAS. import numpy as np axisX = headerInfo['axisX'] axisY = headerInfo['axisY'] axisZ = np.cross(axisX, axisY) spacing = headerInfo['spacing'] origin = headerInfo['origin'] ijkToLps = np.eye(4) for row in range(3): ijkToLps[row, 0] = axisX[row] * spacing[0] ijkToLps[row, 1] = axisY[row] * spacing[1] ijkToLps[row, 2] = axisZ[row] * spacing[2] ijkToLps[row, 3] = origin[row] lpsToRas = np.diag([-1.0, -1.0, 1.0, 1.0]) ijkToRas = np.dot(lpsToRas, ijkToLps) ijkToRasVtk = slicer.util.vtkMatrixFromArray(ijkToRas) tempLabelmapNode.SetIJKToRASMatrix(ijkToRasVtk) tempLabelmapNode.Modified() # Get node base name from filename if 'name' in properties.keys(): baseName = properties['name'] else: baseName = os.path.splitext(os.path.basename(filePath))[0] baseName = slicer.mrmlScene.GenerateUniqueName(baseName) loadedSegmentationNode = slicer.mrmlScene.AddNewNodeByClass( 'vtkMRMLSegmentationNode', baseName) slicer.modules.segmentations.logic( ).ImportLabelmapToSegmentationNode(tempLabelmapNode, loadedSegmentationNode) slicer.mrmlScene.RemoveNode(tempLabelmapNode) except Exception as e: logging.error('Failed to load file: ' + str(e)) import traceback traceback.print_exc() return False self.parent.loadedNodes = [loadedSegmentationNode.GetID()] return True