def GetRawDICOMData(filenames,fileID):
  print filenames,fileID
  vtkRealDcmReader = vtk.vtkDICOMImageReader()
  vtkRealDcmReader.SetFileName("%s/%s"%(rootdir,filenames[0]) )
  vtkRealDcmReader.Update()
  vtkRealData = vtk.vtkImageCast()
  vtkRealData.SetOutputScalarTypeToFloat()
  vtkRealData.SetInput( vtkRealDcmReader.GetOutput() )
  vtkRealData.Update( )
  real_image = vtkRealData.GetOutput().GetPointData() 
  real_array = vtkNumPy.vtk_to_numpy(real_image.GetArray(0)) 

  vtkImagDcmReader = vtk.vtkDICOMImageReader()
  vtkImagDcmReader.SetFileName("%s/%s"%(rootdir,filenames[1]) )
  vtkImagDcmReader.Update()
  vtkImagData = vtk.vtkImageCast()
  vtkImagData.SetOutputScalarTypeToFloat()
  vtkImagData.SetInput( vtkImagDcmReader.GetOutput() )
  vtkImagData.Update( )
  imag_image = vtkImagData.GetOutput().GetPointData() 
  imag_array = vtkNumPy.vtk_to_numpy(imag_image.GetArray(0)) 

  vtkAppend = vtk.vtkImageAppendComponents()
  vtkAppend.SetInput( 0,vtkRealDcmReader.GetOutput() )
  vtkAppend.SetInput( 1,vtkImagDcmReader.GetOutput() )
  vtkAppend.Update( )

  vtkDcmWriter = vtk.vtkDataSetWriter()
  vtkDcmWriter.SetFileName("rawdata.%04d.vtk" % fileID )
  vtkDcmWriter.SetInput(vtkAppend.GetOutput())
  vtkDcmWriter.Update()

  return (real_array,imag_array)
Ejemplo n.º 2
0
def GetRawDICOMData(filenames,fileID):
  print filenames,fileID
  vtkRealDcmReader = vtk.vtkDICOMImageReader()
  vtkRealDcmReader.SetFileName("%s/%s"%(rootdir,filenames[0]) )
  vtkRealDcmReader.Update()
  vtkRealData = vtk.vtkImageCast()
  vtkRealData.SetOutputScalarTypeToFloat()
  vtkRealData.SetInput( vtkRealDcmReader.GetOutput() )
  vtkRealData.Update( )
  real_image = vtkRealData.GetOutput().GetPointData() 
  real_array = vtkNumPy.vtk_to_numpy(real_image.GetArray(0)) 

  vtkImagDcmReader = vtk.vtkDICOMImageReader()
  vtkImagDcmReader.SetFileName("%s/%s"%(rootdir,filenames[1]) )
  vtkImagDcmReader.Update()
  vtkImagData = vtk.vtkImageCast()
  vtkImagData.SetOutputScalarTypeToFloat()
  vtkImagData.SetInput( vtkImagDcmReader.GetOutput() )
  vtkImagData.Update( )
  imag_image = vtkImagData.GetOutput().GetPointData() 
  imag_array = vtkNumPy.vtk_to_numpy(imag_image.GetArray(0)) 

  vtkAppend = vtk.vtkImageAppendComponents()
  vtkAppend.SetInput( 0,vtkRealDcmReader.GetOutput() )
  vtkAppend.SetInput( 1,vtkImagDcmReader.GetOutput() )
  vtkAppend.Update( )

  # write raw data
  vtkRawData = vtkAppend.GetOutput()
  vtkRawData.SetSpacing( spacing )
  vtkDcmWriter = vtk.vtkDataSetWriter()
  vtkDcmWriter.SetFileTypeToBinary()
  vtkDcmWriter.SetFileName("s%d/rawdata.%04d.vtk" % (dirID,fileID) )
  vtkDcmWriter.SetInput( vtkRawData )
  vtkDcmWriter.Update()

  # write raw phase data
  vtkPhase = vtk.vtkImageMathematics()
  vtkPhase.SetInput1( vtkRealData.GetOutput() )
  vtkPhase.SetInput2( vtkImagData.GetOutput() )
  vtkPhase.SetOperationToATAN2( )
  vtkPhase.Update( )
  vtkPhaseData = vtkPhase.GetOutput()
  vtkPhaseData.SetSpacing( spacing )
  vtkDcmWriter = vtk.vtkDataSetWriter()
  vtkDcmWriter.SetFileTypeToBinary()
  vtkDcmWriter.SetFileName("s%d/phase.%04d.vtk" % (dirID,fileID) )
  vtkDcmWriter.SetInput( vtkPhaseData)
  vtkDcmWriter.Update()

  return (real_array,imag_array)
Ejemplo n.º 3
0
def rendering(dataPath, label, lowerThreshold, upperThreshold, surface,
              dualSurface, volume, dual_volume, sigmoid):

    # Read the data
    if dataPath.endswith('.nrrd'):
        reader = vtk.vtkNrrdReader()
        reader.SetFileName(dataPath)
        reader.Update()
    # if dataPath.endswith('.nii'):
    #     reader = vtk.vtkNIFTIImageReader()
    #     reader.SetFileName(dataPath)
    #     reader.Update()
    else:
        reader = vtk.vtkDICOMImageReader()
        reader.SetDirectoryName(dataPath)
        reader.Update()

    if label.endswith('.nrrd'):
        reader2 = vtk.vtkNrrdReader()
        reader2.SetFileName(label)
        reader2.Update()
    else:
        reader2 = vtk.vtkDICOMImageReader()
        reader2.SetDirectoryName(label)
        reader2.Update()

    # if sigmoid.endswith('.nii'):
    #     reader3 = vtk.vtkNIFTIImageReader()
    #     reader3.SetFileName(sigmoid)
    #     reader3.Update()
    # else:
    #     reader3 = vtk.vtkDICOMImageReader()
    #     reader3.SetDirectoryName(sigmoid)
    #     reader3.Update()
    # Smooth the image
    filteredImage = gaussianFilter(reader)

    # Surface rendering
    if surface:
        surfaceRendering(reader2.GetOutput(), lowerThreshold, upperThreshold)

    if dualSurface:
        dualSurfaceRendering(filteredImage, reader2.GetOutput())

    # Volume rendering
    if volume:
        volumeRendering(reader2.GetOutput(), lowerThreshold, upperThreshold)
    if dual_volume:
        dual_volumeRendering(reader.GetOutput(), reader2.GetOutput(),
                             lowerThreshold, upperThreshold,
                             reader3.GetOutput())
Ejemplo n.º 4
0
def load_dicom_vtk(path):
    #Load all the images in the DICOM directory
    imagevtk = vtk.vtkDICOMImageReader()
    imagevtk.SetDirectoryName(path)
    imagevtk.Update()

    return imagevtk
Ejemplo n.º 5
0
def loadData():
    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName(file_path)
    reader.Update()
    imageData = vtk.vtkImageData()
    imageData.DeepCopy(reader.GetOutput())
    return reader
Ejemplo n.º 6
0
    def __init__(self, scan_dir, spacing='auto'):
        """Load image to scale
        :param scan_dir: path to dicom file
        :param spacing: [x,y,z] spacing in mm, or 'auto' if we want to use min spacing already present in a scan,
               'none' if we are not doing any resamplig
        """

        # read dicom
        self.reader = vtkDICOMImageReader()
        self.reader.ReleaseDataFlagOff()
        self.reader.SetDirectoryName(scan_dir)
        self.reader.Update()

        # prepare parameters for shear transform (gantry tilt)
        x1, y1, z1, x2, y2, z2 = self.image_orientation = self.reader.GetImageOrientationPatient(
        )

        # if non-standard orientation, then it's non-standard series
        if y2 == 0:
            raise Exception(
                f"Wrong patient orientation: {self.image_orientation}")

        rad_tilt = atan(z2 / y2)
        center_z = self.reader.GetOutput().GetBounds()[5] / 2
        self.shear_params = ShearParams(rad_tilt, -center_z)

        self.scan_dir = scan_dir
        self.spacing = spacing

        self.angle_z = 0
        self.angle_y = 0
        self.origin_x = None
        self.image = None
Ejemplo n.º 7
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkDICOMImageReader(), 'Reading vtkDICOMImage.',
         (), ('vtkDICOMImage',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Ejemplo n.º 8
0
def FolderRead(folder_path):
    """Read DICOM files inside the given folder path, and read them as one 3D array
    Using: VTK"""
    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName(folder_path)
    reader.Update()
    # Load dimensions using `GetDataExtent`
    _extent = reader.GetDataExtent()
    ConstPixelDims = [
        _extent[1] - _extent[0] + 1, _extent[3] - _extent[2] + 1,
        _extent[5] - _extent[4] + 1, 1
    ]
    # Load spacing values
    ConstPixelSpacing = reader.GetPixelSpacing()
    # Get the 'vtkImageData' object from the reader
    imageData = reader.GetOutput()
    # Get the 'vtkPointData' object from the 'vtkImageData' object
    pointData = imageData.GetPointData()
    # Get the `vtkArray` (or whatever derived type) which is needed for the `numpy_support.vtk_to_numpy` function
    arrayData = pointData.GetArray(0)
    # Convert the `vtkArray` to a NumPy array
    ArrayDicom = numpy_support.vtk_to_numpy(arrayData)
    # Reshape the NumPy array to 3D using 'ConstPixelDims' as a 'shape'
    data = ArrayDicom.reshape(ConstPixelDims, order='F')
    if (np.shape(np.shape(data))[0] == 3):  #If channel data not present
        data = np.expand_dims(data, 3)
    return data
Ejemplo n.º 9
0
 def viz_VisualizeDICOM(self, path):
     volume = vtk.vtkVolume()
     dc_img_reader = vtk.vtkDICOMImageReader()
     dc_img_reader.SetDirectoryName(path)
     dc_img_reader.Update()
     dc_color_func = vtk.vtkColorTransferFunction()
     dc_color_func.AddRGBPoint(-3024, 0.0, 0.0, 0.0)
     dc_color_func.AddRGBPoint(-77, 0.55, 0.25, 0.15)
     dc_color_func.AddRGBPoint(94, 0.88, 0.60, 0.29)
     dc_color_func.AddRGBPoint(179, 1.0, 0.94, 0.95)
     dc_color_func.AddRGBPoint(260, 0.62, 0.0, 0.0)
     dc_color_func.AddRGBPoint(3071, 0.82, 0.66, 1.0)
     dc_alpha_func = vtk.vtkPiecewiseFunction()
     dc_alpha_func.AddPoint(-3024, 0.0)
     dc_alpha_func.AddPoint(-77, 0.0)
     dc_alpha_func.AddPoint(94, 0.29)
     dc_alpha_func.AddPoint(179, 0.55)
     dc_alpha_func.AddPoint(260, 0.84)
     dc_alpha_func.AddPoint(3071, 0.875)
     volumeProperty = vtk.vtkVolumeProperty()
     volumeProperty.SetColor(dc_color_func)
     volumeProperty.SetScalarOpacity(dc_alpha_func)
     volumeProperty.ShadeOn()
     volumeProperty.SetInterpolationTypeToLinear()
     volumeMapper = vtk.vtkGPUVolumeRayCastMapper()
     volumeMapper.SetInputConnection(dc_img_reader.GetOutputPort())
     volume.SetMapper(volumeMapper)
     volume.SetProperty(volumeProperty)
     self.__ren.AddVolume(volume)
Ejemplo n.º 10
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.reader = vtk.vtkDICOMImageReader()

        #self.viewerL = vtk.vtkImageViewer2()
        #self.viewerR = vtk.vtkImageViewer2()

        self.renL = vtk.vtkRenderer()
        self.ui.leftVtk.GetRenderWindow().AddRenderer(self.renL)
        self.renR = vtk.vtkRenderer()
        self.ui.rightVtk.GetRenderWindow().AddRenderer(self.renR)

        self.mapperL = vtk.vtkImageMapper()
        self.mapperL.SetInputConnection(self.reader.GetOutputPort())
        self.mapperR = vtk.vtkImageMapper()

        self.actorL = vtk.vtkActor2D()
        self.actorL.SetMapper(self.mapperL)
        self.actorR = vtk.vtkActor2D()
        self.actorR.SetMapper(self.mapperR)

        self.renL.AddActor2D(self.actorL)
        self.renR.AddActor2D(self.actorR)

        self.importer = vtk.vtkImageImport()
        self.mapperR.SetInputConnection(self.importer.GetOutputPort())

        self.loadImage(os.path.join(STARTINGPATH, FILENAME))
        self.setWindowingAlg()
Ejemplo n.º 11
0
def get_vtk_reader(filename):
    '''Get the appropriate vtkImageReader given the filename

    This function utilizes the factory method classes in VTK with
    some added functionality for working with the AIM, nifti, and
    dicom readers.

    Args:
        filename (string):      Image to be read in

    Returns:
        vtkImageReader:         The corresponding vtkImageReader or None
                                if one cannot be found.
    '''
    # Try factory method
    reader = vtk.vtkImageReader2Factory.CreateImageReader2(filename)

    # If it doesn't work, try specific cases
    if reader is None:
        if filename.lower().endswith('.aim'):
            reader = vtkbone.vtkboneAIMReader()
            reader.DataOnCellsOff()
        elif filename.lower().endswith('.nii'):
            reader = vtk.vtkNIFTIImageReader()
        elif filename.lower().endswith('.nii.gz'):
            reader = vtk.vtkNIFTIImageReader()
        elif filename.lower().endswith('.dcm'):
            reader = vtk.vtkDICOMImageReader()

    return reader
Ejemplo n.º 12
0
Archivo: io.py Proyecto: piro0321/AI
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 load_dicom(foldername, doflipz = True):
    reader = vtk.vtkDICOMImageReader()
    reader.SetFileName(foldername)
    reader.Update()

    #note: It workes when the OS sorts the files correctly by itself. If the files weren’t properly named, lexicographical sorting would have given a messed up array. In that 
    # case you need to loop and pass each file to a separate reader through the SetFileName method, or you’d have to create a vtkStringArray, push the sorted filenames, and use 
    # the vtkDICOMImageReader.SetFileNames method.

    # Load meta data: dimensions using `GetDataExtent`
    _extent = reader.GetDataExtent()
    ConstPixelDims = [_extent[1]-_extent[0]+1, _extent[3]-_extent[2]+1, _extent[5]-_extent[4]+1]

    # Get the 'vtkImageData' object from the reader
    imageData = reader.GetOutput()
    # Get the 'vtkPointData' object from the 'vtkImageData' object
    pointData = imageData.GetPointData()
    # Ensure that only one array exists within the 'vtkPointData' object
    assert (pointData.GetNumberOfArrays()==1)
    # Get the `vtkArray` (or whatever derived type) which is needed for the `numpy_support.vtk_to_numpy` function
    arrayData = pointData.GetArray(0)

    # Convert the `vtkArray` to a NumPy array
    ArrayDicom = numpy_support.vtk_to_numpy(arrayData)
    # Reshape the NumPy array to 3D using 'ConstPixelDims' as a 'shape'
    ArrayDicom = ArrayDicom.reshape(ConstPixelDims, order='F')


    return (ArrayDicom)
Ejemplo n.º 14
0
def convert(filepath):

	filepath = "./display/"
	reader = vtk.vtkDICOMImageReader() #we create a new vtkDICOMImageReader under the name of reader which we use to read the DICOM images.
	reader.SetDirectoryName(filepath)
	reader.Update()
	image = reader.GetOutput()

	shiftScaleFilter = vtkImageShiftScale()
	shiftScaleFilter.SetOutputScalarTypeToUnsignedChar()
	shiftScaleFilter.SetInputConnection(reader.GetOutputPort())

	shiftScaleFilter.SetShift(-1.0*image.GetScalarRange()[0])
	oldRange = image.GetScalarRange()[1] - image.GetScalarRange()[0]
	newRange = 255

	shiftScaleFilter.SetScale(newRange/oldRange)
	shiftScaleFilter.Update()

	writer = vtkPNGWriter()
	writer.SetFileName('./display/output.png') # you give the path-filename where you want the output to be
	writer.SetInputConnection(shiftScaleFilter.GetOutputPort())
	writer.Write()

	return 1
Ejemplo n.º 15
0
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent)

        self.frame = QtGui.QFrame()

        self.vl = QtGui.QVBoxLayout()
        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        self.vl.addWidget(self.vtkWidget)

        self.ren = vtk.vtkRenderer()
        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        # Create source
        source = vtk.vtkDICOMImageReader()
        source.SetFileName("D:\Anaconda\workspace\pytest\patient\\1.dcm")

        # Create a mapper
        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(source.GetOutputPort())

        # Create an actor
        actor = vtk.vtkActor()
        actor.SetMapper(mapper)

        self.ren.AddActor(actor)

        self.ren.ResetCamera()

        self.frame.setLayout(self.vl)
        self.setCentralWidget(self.frame)

        self.show()
        self.iren.Initialize()
Ejemplo n.º 16
0
def view_dicom(PathDicom):

    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName(PathDicom)
    reader.Update()

    # Load dimensions using `GetDataExtent`
    _extent = reader.GetDataExtent()
    ConstPixelDims = [
        _extent[1] - _extent[0] + 1, _extent[3] - _extent[2] + 1,
        _extent[5] - _extent[4] + 1
    ]

    # Load spacing values
    ConstPixelSpacing = reader.GetPixelSpacing()

    # Get the 'vtkImageData' object from the reader
    imageData = reader.GetOutput()
    # Get the 'vtkPointData' object from the 'vtkImageData' object
    pointData = imageData.GetPointData()
    # Ensure that only one array exists within the 'vtkPointData' object
    assert (pointData.GetNumberOfArrays() == 1)
    # Get the `vtkArray` (or whatever derived type) which is needed for the `numpy_support.vtk_to_numpy` function
    arrayData = pointData.GetArray(0)

    # Convert the `vtkArray` to a NumPy array
    ArrayDicom = numpy_support.vtk_to_numpy(arrayData)
    # Reshape the NumPy array to 3D using 'ConstPixelDims' as a 'shape'
    ArrayDicom = ArrayDicom.reshape(ConstPixelDims, order='F')
Ejemplo n.º 17
0
def loadData():
    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName(file_path)
    reader.Update()
    imageData = vtk.vtkImageData()
    imageData.DeepCopy(reader.GetOutput())
    return reader
Ejemplo n.º 18
0
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)

        self.frame = QtWidgets.QFrame()
        self.vl = QtWidgets.QVBoxLayout()
        self.QtInteractor = QVTKRenderWindowInteractor(self.frame)
        self.vl.addWidget(self.QtInteractor)

        self.dicom_image_path = 'IM-0008-0034.dcm'

        # '----------set up dicom reader---------------'
        self.dcmReader = vtk.vtkDICOMImageReader()
        self.dcmReader.SetDataByteOrderToLittleEndian()
        self.dcmReader.SetFileName(self.dicom_image_path)
        self.dcmReader.Update()

        # '----------init render---------------'
        self.ren = vtk.vtkRenderer()

        # show the dicom flie
        self.imageViewer = vtk.vtkImageViewer2()
        self.imageViewer.SetInputConnection(self.dcmReader.GetOutputPort())

        self.renderWindowInteractor = vtk.vtkRenderWindowInteractor()
        self.imageViewer.SetupInteractor(self.renderWindowInteractor)

        self.imageViewer.Render()
        self.imageViewer.GetRenderer().ResetCamera()
        self.imageViewer.Render()
        self.renderWindowInteractor.Start()
Ejemplo n.º 19
0
def read_dicom_vtk(dir_path, show_shape=False):
    """A function that read dicom series file
        Args: 
            dir_path, a string for dicom path
            show_shape, boolean of whether to show image shape
        Returns:
            Tuple of dicom image spacing and dicom image in numpy format, 
            note dicom file has origin (0,0,0)
    """
    if not os.path.exists(dir_path):
        raise ValueError('Input path does not exist!')
    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName(dir_path)
    reader.Update()
    spacing = list(reader.GetPixelSpacing())  # x, y, z
    spacing.reverse()  # z, y, x
    _extent = reader.GetDataExtent()
    ConstPixelDims = [
        _extent[1] - _extent[0] + 1, _extent[3] - _extent[2] + 1,
        _extent[5] - _extent[4] + 1
    ]
    imageData = reader.GetOutput()
    pointData = imageData.GetPointData()
    assert (pointData.GetNumberOfArrays() == 1)
    arrayData = pointData.GetArray(0)
    ArrayDicom = numpy_support.vtk_to_numpy(arrayData)
    # sometimes vtk does not work
    if ArrayDicom.sum() == 0:
        raise ValueError('The output image is empty, try read_dicom_itk!')
    ArrayDicom = ArrayDicom.reshape(ConstPixelDims, order='F')
    ArrayDicom = np.rot90(ArrayDicom, 1)
    ArrayDicom = np.transpose(ArrayDicom, [2, 0, 1])
    if show_shape:
        print "Image shape is %s" % (ArrayDicom.shape, )
    return np.array(spacing), ArrayDicom
Ejemplo n.º 20
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)

        self.reader = vtk.vtkDICOMImageReader()

        #self.viewerL = vtk.vtkImageViewer2()
        #self.viewerR = vtk.vtkImageViewer2()

        self.renL = vtk.vtkRenderer()
        self.ui.leftVtk.GetRenderWindow().AddRenderer(self.renL)
        self.renR = vtk.vtkRenderer()
        self.ui.rightVtk.GetRenderWindow().AddRenderer(self.renR)

        self.mapperL = vtk.vtkImageMapper()
        self.mapperL.SetInputConnection(self.reader.GetOutputPort())
        self.mapperR = vtk.vtkImageMapper()

        self.actorL = vtk.vtkActor2D()
        self.actorL.SetMapper(self.mapperL)
        self.actorR = vtk.vtkActor2D()
        self.actorR.SetMapper(self.mapperR)

        self.renL.AddActor2D(self.actorL)
        self.renR.AddActor2D(self.actorR)

        self.importer = vtk.vtkImageImport()
        self.mapperR.SetInputConnection(self.importer.GetOutputPort())

        self.loadImage(os.path.join(STARTINGPATH, FILENAME))
        self.setWindowingAlg()
Ejemplo n.º 21
0
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)

        self.frame = QtWidgets.QFrame()

        self.vl = QtWidgets.QVBoxLayout()
        self.vtkWidget = QVTKRenderWindowInteractor(self.frame)
        self.vl.addWidget(self.vtkWidget)

        self.dicom_image_path = './IM-0008-0034.dcm'

        # '----------set up dicom reader---------------'
        self.dcmReader = vtk.vtkDICOMImageReader()
        self.dcmReader.SetDataByteOrderToLittleEndian()
        self.dcmReader.SetDirectoryName(
            r"D:\Users\user\Desktop\NTUCT\1323\Ct_Without_ContrastBrain - 1323\InnerEar_C_06_U70u_4"
        )
        self.dcmReader.Update()

        # '----------init render---------------'
        self.ren = vtk.vtkRenderer()

        # '---------set up mapper----------'
        self.slice_mapper = vtk.vtkImageSliceMapper()
        self.slice_mapper.SetInputConnection(self.dcmReader.GetOutputPort())
        # set random slice number
        # self.slice_mapper.SetSliceNumber(50)

        # set up image_slice
        self.image_slice = vtk.vtkImageSlice()
        self.image_slice.SetMapper(self.slice_mapper)

        # '-----set up window and level of image_slice----'
        # self.MinMax = self.dcmReader.GetOutput().GetScalarRange()
        # self.image_slice_property = self.image_slice.GetProperty()
        # self.image_slice_property.SetColorWindow(self.MinMax[1])
        # self.image_slice_property.SetColorLevel((self.MinMax[1] - self.MinMax[0]) / 2)
        # self.image_slice.Update()

        # '---------set image_slice as input for renderer------'
        self.ren.AddViewProp(self.image_slice)

        mapper = vtk.vtkPolyDataMapper()
        mapper.SetInputConnection(self.dcmReader.GetOutputPort())
        # # Create an actor
        # actor = vtk.vtkActor()
        # actor.SetMapper(mapper)
        # self.ren.AddActor(actor)

        self.vtkWidget.GetRenderWindow().AddRenderer(self.ren)
        self.iren = self.vtkWidget.GetRenderWindow().GetInteractor()

        self.ren.ResetCamera()

        self.frame.setLayout(self.vl)
        self.setCentralWidget(self.frame)

        self.show()
        self.iren.Initialize()
Ejemplo n.º 22
0
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)

        self.dicom_image_path = './IM-0008-0034.dcm'

        # '----------set up dicom reader---------------'
        self.dcmReader = vtk.vtkDICOMImageReader()
        self.dcmReader.SetDataByteOrderToLittleEndian()
        self.dcmReader.SetDirectoryName(
            r"D:\Users\user\Desktop\NTUCT\1323\Ct_Without_ContrastBrain - 1323\InnerEar_C_06_U70u_4"
        )
        self.dcmRescaleSlope = self.dcmReader.GetRescaleSlope()
        self.dcmRescaleOffset = self.dcmReader.GetRescaleOffset()
        self.dcmReader.Update()

        # '----------viewer---------'
        self.dcmViewer = vtk.vtkImageViewer2()
        self.dcmViewer.SetInputConnection(self.dcmReader.GetOutputPort())
        # '------deal with WW & WL-----'
        self.ww = 3500  # WW
        self.wl = 600  # WL
        self.dcmViewer.SetColorLevel(self.wl)
        self.dcmViewer.SetColorWindow(self.ww)

        # '----------TextOverLay---------'
        # slice status message
        self.sliceTextProp = vtk.vtkTextProperty()
        self.sliceTextProp.SetFontFamilyToCourier()
        self.sliceTextProp.SetFontSize(20)
        self.sliceTextProp.SetVerticalJustificationToBottom()
        self.sliceTextProp.SetJustificationToLeft()
        # '---------set up Text Overlay mapper----------'
        self.sliceTextMapper = vtk.vtkTextMapper()
        cur_slice = self.dcmViewer.GetSlice()
        print('cur_slice  = ', cur_slice, ' viewer.GetSliceMax() = ',
              self.dcmViewer.GetSliceMax())
        msg = (
            ' %d / %d ' %
            (self.dcmViewer.GetSlice() + 1, self.dcmViewer.GetSliceMax() + 1))
        # '---------set up Text Overlay Actor----------'
        self.sliceTextMapper.SetInput(msg)
        sliceTextActor = vtk.vtkActor2D()
        sliceTextActor.SetMapper(self.sliceTextMapper)
        sliceTextActor.SetPosition(15, 10)

        self.window_interactor = vtk.vtkRenderWindowInteractor()
        self.dcmViewer.SetupInteractor(self.window_interactor)

        self.dcmViewer.GetRenderer().AddActor2D(sliceTextActor)

        '----------add keyboard observer---------'
        self.window_interactor.AddObserver(vtk.vtkCommand.KeyPressEvent,
                                           self.keyboard_callback_func)
        self.window_interactor.Initialize()

        self.dcmViewer.Render()
        self.dcmViewer.GetRenderer().ResetCamera()
        self.dcmViewer.Render()
        self.window_interactor.Start()
Ejemplo n.º 23
0
    def __init__(self):
        QFrame.__init__(self)

        self.rendering_threshold = 0
        self.arter = vtk.vtkActor()
        self.outline = vtk.vtkActor()
        self.vtk_image_reader = vtk.vtkDICOMImageReader()
        self.window_initialization()
Ejemplo n.º 24
0
    def readDICOM(self, *args):

        # create reader
        reader = vtk.vtkDICOMImageReader()
        reader.SetDirectoryName(self.directory)
        reader.Update()

        return reader
Ejemplo n.º 25
0
def load_dcm(filename):
    reader = vtk.vtkDICOMImageReader()
    if ".dcm" in filename:
        filename = filename.replace(filename.split('/')[-1], "")
    reader.SetDirectoryName(filename)
    reader.Update()

    return reader.GetOutput()
def DiconSeriesReader(path):
    '''
    http://www.vtk.org/Wiki/VTK/Examples/Cxx/IO/ReadDICOMSeries
    '''
    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName(ff)
    reader.Update()
    return reader.GetOutput()
Ejemplo n.º 27
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkDICOMImageReader(),
                                       'Reading vtkDICOMImage.', (),
                                       ('vtkDICOMImage', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Ejemplo n.º 28
0
def new(renderWindowInteractor):
    a = vtk.QVTKWidget()
    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName("D:\Anaconda\workspace\pytest\patient")
    # reader.SetDirectoryName("G:\Win64\Anaconda3.4\workplace\\vtk\dicom")
    reader.Update()
    imageViewer = vtk.vtkImageViewer2()
    imageViewer.SetInputConnection(reader.GetOutputPort())
    sliceTextProp = vtk.vtkTextProperty()
    sliceTextProp.SetFontFamilyToCourier()
    sliceTextProp.SetFontSize(20)
    sliceTextProp.SetVerticalJustificationToBottom()
    sliceTextProp.SetJustificationToLeft()

    sliceTextMapper = vtk.vtkTextMapper()
    msg = str(imageViewer.GetSliceMin()) + '/' + str(imageViewer.GetSliceMax())
    sliceTextMapper.SetInput(msg)
    sliceTextMapper.SetTextProperty(sliceTextProp)

    sliceTextActor = vtk.vtkActor2D()
    sliceTextActor.SetMapper(sliceTextMapper)
    sliceTextActor.SetPosition(15, 10)

    usageTextProp = vtk.vtkTextProperty()
    usageTextProp.SetFontFamilyToCourier()
    usageTextProp.SetFontSize(14)
    usageTextProp.SetVerticalJustificationToTop()
    usageTextProp.SetJustificationToLeft()

    usageTextMapper = vtk.vtkTextMapper()
    usageTextMapper.SetInput(
        "- Slice with mouse wheel\n  or Up/Down-Key\n- Zoom with pressed right\n  mouse button while dragging"
    )
    usageTextMapper.SetTextProperty(usageTextProp)

    usageTextActor = vtk.vtkActor2D()
    usageTextActor.SetMapper(usageTextMapper)
    usageTextActor.GetPositionCoordinate(
    ).SetCoordinateSystemToNormalizedDisplay()
    usageTextActor.GetPositionCoordinate().SetValue(0.05, 0.95)

    # renderWindowInteractor =vtk.vtkRenderWindowInteractor()

    # myInteractorStyle = vtk. myVtkInteractorStyleImage()
    #
    # myInteractorStyle.SetImageViewer(imageViewer)
    # myInteractorStyle.SetStatusMapper(sliceTextMapper)

    imageViewer.SetupInteractor(renderWindowInteractor)
    imageViewer.SetSlice(12)
    # style= vtk.vtkInteractorStyleUser(imageViewer=imageViewer)
    # renderWindowInteractor.SetInteractorStyle(style)
    imageViewer.GetRenderer().AddActor2D(sliceTextActor)
    imageViewer.GetRenderer().AddActor2D(usageTextActor)
    imageViewer.Render()
    imageViewer.GetRenderer().ResetCamera()
    imageViewer.Render()
Ejemplo n.º 29
0
    def createPipeline(self, _filename):
        # Read in the file
        if _filename.lower().endswith('.nii'):
            self.reader = vtk.vtkNIFTIImageReader()
            self.reader.SetFileName(_filename)
        elif _filename.lower().endswith('.nii.gz'):
            self.reader = vtk.vtkNIFTIImageReader()
            self.reader.SetFileName(_filename)
        elif _filename.lower().endswith('.dcm'):
            self.reader = vtk.vtkDICOMImageReader()
            self.reader.SetDirectoryName(os.path.dirname(_filename))
        elif os.path.isdir(_filename):
            self.reader = vtk.vtkDICOMImageReader()
            self.reader.SetDirectoryName(_filename)

        if self.reader is None:
            os.sys.exit("[ERROR] Cannot find reader for file \"{}\"".format(
                self.filename))
        self.reader.Update()

        # Gaussian smoothing
        self.gauss.SetStandardDeviation(self.gaussian, self.gaussian,
                                        self.gaussian)
        self.gauss.SetRadiusFactors(self.radius, self.radius, self.radius)
        self.gauss.SetInputConnection(self.reader.GetOutputPort())

        # Marching Cubes
        self.marchingCubes.SetInputConnection(self.gauss.GetOutputPort())
        self.marchingCubes.ComputeGradientsOn()
        self.marchingCubes.ComputeNormalsOn()
        self.marchingCubes.ComputeScalarsOff()
        self.marchingCubes.SetNumberOfContours(1)
        self.marchingCubes.SetValue(0, self.isosurface)

        # Set mapper for image data
        self.mapper.SetInputConnection(self.marchingCubes.GetOutputPort())

        # Actor
        self.actor.SetMapper(self.mapper)
        self.actor.GetProperty().SetColor((0.890, 0.855, 0.788))
        self.renderer.AddActor(self.actor)

        self.refreshRenderWindow()
        return
Ejemplo n.º 30
0
 def readInputFile(self):
     # Read the file
     if os.path.isdir(self.inputFileName): # DICOM dir
         self.reader = vtk.vtkDICOMImageReader()
         self.reader.SetDirectoryName(self.inputFileName)
         #print("DICOM dir")
     elif self.inputFileName.lower().endswith('.nii'): # NIfTI file
         self.reader = vtk.vtkNIFTIImageReader()
         self.reader.SetFileName(self.inputFileName)
         #print("NIfTI file")
     elif self.inputFileName.lower().endswith(('.dicom', '.dcm')): # DICOM file
         self.reader = vtk.vtkDICOMImageReader()
         self.reader.SetFileName(self.inputFileName)
         #print("DICOM file")
     else: # Not recognized
         self.inputFileName = None
         self.reader = None
         return
     self.reader.Update()
Ejemplo n.º 31
0
def read_dicom(directory):
    # Create reader object ans set directory name
    reader = vtkDICOMImageReader()
    reader.SetDirectoryName(directory)
    # Set other settings and update
    reader.SetDataByteOrderToLittleEndian()
    #data_spacing = (1, 1, 2)
    #reader.SetDataSpacing(data_spacing[0], data_spacing[1], data_spacing[2])
    reader.Update()
    return reader
Ejemplo n.º 32
0
 def change_data(self, path_to_data, data_type):
     if data_type is DataType.DICOM:
         image_reader = vtk.vtkDICOMImageReader()
         image_reader.SetDirectoryName(path_to_data)
         self.__setup_default_volume_parameters(image_reader)
         self.volume_data_changed.emit()
     elif data_type is DataType.META_IMAGE:
         image_reader = vtk.vtkMetaImageReader()
         image_reader.SetFileName(path_to_data)
         self.__setup_default_volume_parameters(image_reader)
         self.volume_data_changed.emit()
Ejemplo n.º 33
0
def read_dicom(dicom_dir):
    # fnames = os.listdir(dicom_dir)
    # fnames = [f for f in fnames if ".dcm" in f]
    # fnames = sorted(fnames)
    # fnames = [os.path.join(dicom_dir,f) for f in fnames]

    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName(dicom_dir)
    reader.Update()

    return reader.GetOutput()
Ejemplo n.º 34
0
 def __init__(self,
              inputs,
              use_vtk=False):
     self.inputs = inputs
     if use_vtk:
         print('Using VTK to read DICOMs ...')
         self.load_dicom_array = self.load_with_vtk
         self.reader = vtk.vtkDICOMImageReader()
     else:
         print('Using pydicom to read DICOMS ...')
         self.load_dicom_array = self.load_with_pydicom
def TestGPUVolumeRender():
    """
    Test GPU DICOM Loader Usage, uncomment the DEBUG TEST lines before use
    :return:
    """
    reader = vtk.vtkDICOMImageReader()
    reader.SetDataByteOrderToLittleEndian()
    reader.SetDirectoryName("../TestData/cta_output")
    reader.SetDataSpacing(3.2, 3.2, 1.5)
    reader.SetDataOrigin(0, 0, 0)
    print "test"
    vol = VolumeRenderingGPUDICOMLoader(reader)
Ejemplo n.º 36
0
def rendering(
        dataPath,
        dualSurface):

    import SimpleITK as sitk


    #
    # writing_path='data.nii'
    # reader = itk.ImageFileReader.New(FileName=dataPath)
    # reader.SetFileName(dataPath)
    # reader.Update()
    # image_input=reader.GetOutput()
    #
    # # imagee_out=sitk.GetImageFromArray(imagee)
    #
    # writer =itk.ImageFileWriter.New()
    # writer.SetFileName(writing_path)
    # writer.SetInput(image_input)
    # writer.Update()
    img=sitk.ReadImage(dataPath)
    img.SetSpacing([0.18,0.18,0.18])
    sitk.WriteImage(img,dataPath)
    # Read the data
    if dataPath.endswith('.nii'):
        reader = vtk.vtkNIFTIImageReader()
        # reader.SetSpacing(1,1,1)
        reader.SetFileName(dataPath)
        reader.Update()
    elif dataPath.endswith('.nhdr') or dataPath.endswith('.nrrd'):
        reader = vtk.vtkNrrdReader()

        reader.SetFileName(dataPath)
        # reader.SetSpacing(0.18,0.18,0.18)
        reader.Update()
    else:
        reader = vtk.vtkDICOMImageReader()
        reader.SetDirectoryName(dataPath)
        reader.Update()





    # Smooth the image
    filteredImage = gaussianFilter(reader)

    # Surface rendering


    if dualSurface:
        dualSurfaceRendering(filteredImage)
	def GetImageDataFromDirectory(self, dirName):
		"""
		This method is just for DICOM image data. So input is a directory name
		and it will output an vtkImageData object.
		:type dirName: basestr
		:rtype: vtkImageData
		"""
		imageReader = vtkDICOMImageReader()
		imageReader.SetDirectoryName(dirName)
		imageReader.Update()
		imageData = imageReader.GetOutput()
		self.SanitizeImageData(imageReader, imageData)
		return imageData
Ejemplo n.º 38
0
    def readT2(self, path_T2Series):
        """
        ARGUMENTS:
        =============
        StudyID (str)           Study CAD patient number      
        DicomExamNumber (str)   Imaging Study Number    
        SeriesID  (str)         T2 Series number (e.g S600, S3)     
        Lesions_id (str)        Older database LesionID identifier
        
        OUTPUTS:
        =============
        DICOMImages list(vtkImageData)      List of vtkImageData objects corresponding to dynamic series
        
        """
        # Get total number of files and some DICOM tags needed fro DICOM coords
        [len_listSeries_files, FileNms_slices_sorted_stack] = self.ReadDicomfiles(path_T2Series)
        mostleft_slice = FileNms_slices_sorted_stack.slices[0]
        
        # Get dicom header, retrieve: image_pos_pat and image_ori_pat
        dicomInfoT2 = dicom.read_file(path_T2Series+os.sep+str(mostleft_slice)) 
        self.slice_thicknT2 = float(dicomInfoT2[0x0018,0x0050].value)  
        
        # Image Position (0020,0032): specifies the x, y, and z coordinates of the upper left hand corner of the image. This tag specifies the coordinates 
        self.T2image_pos_pat = list(dicomInfoT2[0x0020,0x0032].value)
        self.T2image_ori_pat = list(dicomInfoT2[0x0020,0x0037].value)
        self.T2fatsat = dicomInfoT2[0x0019,0x10a4].value

       
        os.chdir(path_T2Series)               
        dicomReader  = vtk.vtkDICOMImageReader()
        dicomReader.SetDirectoryName( path_T2Series )
        dicomReader.Update()
        
        im = vtk.vtkImageData()
        im =  dicomReader.GetOutput()
        self.T2dims = im.GetDimensions()
        self.T2spacing = im.GetSpacing()
        
        print "VTK Dimensions im.GetDimensions(): %d %d %d" % self.T2dims
        print "VTK Spacing im.GetSpacing(): %f %f %f\n" % self.T2spacing
        
        # to objects image            
        self.T2Images = im 
        
        return self.T2Images
def TestVolumeRender():
    """
    Test DICOM loader usage, uncomment the DEBUG TEST lines before use
    :return:
    """
    reader = vtk.vtkDICOMImageReader()
    reader.SetDataByteOrderToLittleEndian()
    reader.SetDirectoryName("../TestData/cta_output")
    reader.SetDataSpacing(3.2, 3.2, 1.5)
    reader.SetDataOrigin(0, 0, 0)
    vol = VolumeRenderingDICOMLoader(reader)
    renderer = vtk.vtkRenderer()
    renderer.AddVolume(vol)
    renWin = vtk.vtkRenderWindow()
    renWin.AddRenderer(renderer)

    # vdisplay = xvfbwrapper.Xvfb()
    # vdisplay.start()
    ImageWriter(renderer, outFileName="tmp")
    renderer.GetActiveCamera().Azimuth(40)
    ImageWriter(renderer, outFileName="tmp2")
Ejemplo n.º 40
0
def main():

   argc = len(sys.argv)

   # Verify input arguments
   if argc != 2:
      print "Usage: ", sys.argv[0], " FolderName"
      return sys.exit(1)
 
   folder = sys.argv[1]
 
   # Read all the DICOM files in the specified directory.
   reader = vtk.vtkDICOMImageReader()
   reader.SetDirectoryName(folder)
   reader.Update()
 
   # Visualize
   imageViewer = vtk.vtkImageViewer2()
   imageViewer.SetInputConnection(reader.GetOutputPort())
 
   # slice status message
   sliceTextProp = vtk.vtkTextProperty()
   sliceTextProp.SetFontFamilyToCourier()
   sliceTextProp.SetFontSize(20)
   sliceTextProp.SetVerticalJustificationToBottom()
   sliceTextProp.SetJustificationToLeft()
 
   sliceTextMapper = vtk.vtkTextMapper()
   msg = "Slice {} out of {}".format(imageViewer.GetSliceMin() + 1, \
                                     imageViewer.GetSliceMax() + 1)
   sliceTextMapper.SetInput(msg)
   sliceTextMapper.SetTextProperty(sliceTextProp)
 
   sliceTextActor = vtk.vtkActor2D()
   sliceTextActor.SetMapper(sliceTextMapper)
   sliceTextActor.SetPosition(15, 10)
 
   # usage hint message
   usageTextProp = vtk.vtkTextProperty()
   usageTextProp.SetFontFamilyToCourier()
   usageTextProp.SetFontSize(14)
   usageTextProp.SetVerticalJustificationToTop()
   usageTextProp.SetJustificationToLeft()
 
   usageTextMapper = vtk.vtkTextMapper()
   usageTextMapper.SetInput("- Slice with mouse wheel\n  or Up/Down-Key\n- Zoom with pressed right\n  mouse button while dragging")
   usageTextMapper.SetTextProperty(usageTextProp)
 
   usageTextActor = vtk.vtkActor2D()
   usageTextActor.SetMapper(usageTextMapper)
   usageTextActor.GetPositionCoordinate().SetCoordinateSystemToNormalizedDisplay()
   usageTextActor.GetPositionCoordinate().SetValue( 0.05, 0.95)

   interactor = vtk.vtkInteractorStyleImage()
   #interactor.SetImageViewer(imageViewer)
   #interactor.SetStatusMapper(sliceTextMapper)
 
   #imageViewer.SetupInteractor(renWin)
   #renderWindowInteractor.SetInteractorStyle(myInteractorStyle)
   # add slice status message and usage hint message to the renderer
   imageViewer.GetRenderer().AddActor2D(sliceTextActor)
   imageViewer.GetRenderer().AddActor2D(usageTextActor)
  def GetRawDICOMData(self,idtime,outDirectoryID):
    
    # loop until files are ready to be read in
    realImageFilenames = []
    imagImageFilenames = []
    # FIXME: index fun, slice start from 0, echo start from 1
    for idslice in range(self.nslice):
      for idecho in range(1,self.NumberEcho+1):
        realImageFilenames.append( self.QueryDictionary( idtime,idecho,idslice,2 ) )  
        imagImageFilenames.append( self.QueryDictionary( idtime,idecho,idslice,3 ) )  
  
    #create local vars
    rootdir = self.dataDirectory
    RawDim  = self.RawDimensions
    real_array=numpy.zeros(self.FullSizeRaw,dtype=numpy.float32)
    imag_array=numpy.zeros(self.FullSizeRaw,dtype=numpy.float32) 

    vtkAppendReal = vtk.vtkImageAppendComponents()
    vtkAppendImag = vtk.vtkImageAppendComponents()

    for idEchoLoc,(fileNameReal,fileNameImag) in enumerate(zip(realImageFilenames,imagImageFilenames)):
      # FIXME: index nightmare
      # FIXME: will be wrong for different ordering
      # arrange such that echo varies fast then x, then y, then z
      # example of how slicing behaves
      #>>> x = range(100)
      #>>> x
      #[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
      #>>> x[0:100:10]
      #[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
      #>>> x[1:100:10]
      #[1, 11, 21, 31, 41, 51, 61, 71, 81, 91]
      #>>> x[2:100:10]
      #[2, 12, 22, 32, 42, 52, 62, 72, 82, 92]
      #>>> x[3:100:10]
      #[3, 13, 23, 33, 43, 53, 63, 73, 83, 93]
      idEcho  = idEchoLoc % RawDim[3]
      idSlice = idEchoLoc / RawDim[3]
      beginIndex = RawDim[0]*RawDim[1]*RawDim[3]* idSlice   +idEcho
      finalIndex = RawDim[0]*RawDim[1]*RawDim[3]*(idSlice+1)
      stepIndex  = RawDim[3]
  
      ## realds = dicom.read_file( "%s/%s"%(rootdir,fileNameReal) )
      ## imagds = dicom.read_file( "%s/%s"%(rootdir,fileNameImag) )
      ## realsliceID = int( round((float(realds.SliceLocation) - float(realds[0x0019,0x1019].value))/ realds.SliceThickness))
      ## imagsliceID = int( round((float(imagds.SliceLocation) - float(imagds[0x0019,0x1019].value))/ imagds.SliceThickness))
  
      ## print "%03d echo %03d slice %03d slice [%d:%d:%d] %03d %s %03d %s "% (idEchoLoc,idEcho,idSlice,beginIndex,finalIndex,stepIndex,realsliceID,fileNameReal,imagsliceID,fileNameImag )
  
      vtkRealDcmReader = vtk.vtkDICOMImageReader()
      vtkRealDcmReader.SetFileName("%s/%s"%(rootdir,fileNameReal) )
      vtkRealDcmReader.Update()
      vtkRealData = vtk.vtkImageCast()
      vtkRealData.SetOutputScalarTypeToFloat()
      vtkRealData.SetInput( vtkRealDcmReader.GetOutput() )
      vtkRealData.Update( )
      real_image = vtkRealData.GetOutput().GetPointData() 
      real_array[ beginIndex: finalIndex : stepIndex ] = vtkNumPy.vtk_to_numpy(real_image.GetArray(0)) 
  
      vtkImagDcmReader = vtk.vtkDICOMImageReader()
      vtkImagDcmReader.SetFileName("%s/%s"%(rootdir,fileNameImag) )
      vtkImagDcmReader.Update()
      vtkImagData = vtk.vtkImageCast()
      vtkImagData.SetOutputScalarTypeToFloat()
      vtkImagData.SetInput( vtkImagDcmReader.GetOutput() )
      vtkImagData.Update( )
      imag_image = vtkImagData.GetOutput().GetPointData() 
      imag_array[ beginIndex: finalIndex : stepIndex ] = vtkNumPy.vtk_to_numpy(imag_image.GetArray(0)) 
  
      vtkAppendReal.SetInput( idEchoLoc ,vtkRealDcmReader.GetOutput() )
      vtkAppendImag.SetInput( idEchoLoc ,vtkImagDcmReader.GetOutput() )
      vtkAppendReal.Update( )
      vtkAppendImag.Update( )
    if (SetFalseToReduceFileSystemUsage):
      vtkRealDcmWriter = vtk.vtkDataSetWriter()
      vtkRealDcmWriter.SetFileName("Processed/%s/realrawdata.%04d.vtk" % (outDirectoryID,idtime) )
      vtkRealDcmWriter.SetInput(vtkAppendReal.GetOutput())
      vtkRealDcmWriter.Update()
  
    if (SetFalseToReduceFileSystemUsage):
      vtkImagDcmWriter = vtk.vtkDataSetWriter()
      vtkImagDcmWriter.SetFileName("Processed/%s/imagrawdata.%04d.vtk" % (outDirectoryID,idtime) )
      vtkImagDcmWriter.SetInput(vtkAppendImag.GetOutput())
      vtkImagDcmWriter.Update()
  
    # write numpy to disk in matlab
    echoTimes = []
    for idecho in range(1,self.NumberEcho+1):
       localKey = self.keyTemplate % ( idtime,idecho,0,2 )
       echoTimes.append(self.DicomDataDictionary[localKey][1])
    if (SetFalseToReduceFileSystemUsage):
      scipyio.savemat("Processed/%s/rawdata.%04d.mat"%(outDirectoryID,idtime), {'dimensions':RawDim,'echoTimes':echoTimes,'real':real_array,'imag':imag_array})
  
    # end GetRawDICOMData
    return ((real_array,imag_array),echoTimes)
Ejemplo n.º 42
0
			file_series = open(filename_series,'r')
			files_toRead = file_series.read()
			try:
				for slicename in files_toRead.split():
					print "adding : %s" %  slicename
					vtkStringArray.InsertNextValue( slicename )
			finally:
				file_series.close()
			
			# Read dicom Vol from DIRCONTENTS.txt
			dicomReader  = vtkgdcmPython.vtkGDCMImageReader()
			dicomReader.SetFileNames( vtkStringArray )
			dicomReader.FileLowerLeftOn()
			dicomReader.Update()
		else:
			dicomReader  = vtk.vtkDICOMImageReader()
			dicomReader.SetDirectoryName( chosen_folderID ) # neccesarily, most VTK image readers flip the images from their original top-to-bottom rasterization to a bottom-to-top rasterization instead.
			dicomReader.FileLowerLeftOn()
			dicomReader.Update()
	
		# display the results.
		renderer1 = vtk.vtkRenderer()
		renWin1 = vtk.vtkRenderWindow()
		iren1 = vtk.vtkRenderWindowInteractor()
		
		renWin1.SetSize(1000, 800);
		renWin1.AddRenderer(renderer1);
		iren1.SetRenderWindow(renWin1);
		
							
		[transform_cube, z_visualSerie] = display(dicomReader.GetOutput(), image_pos_pat_visual_SerieID, image_ori_pat_visual_SerieID)
Ejemplo n.º 43
0
import sys
import vtk
import os

testReader = vtk.vtkDICOMImageReader()
fullPath = os.path.realpath(__file__)
projectPath= os.path.dirname(os.path.dirname(os.path.dirname(fullPath)))
testReader.SetFileName(projectPath + "/res/3.dcm")
testReader.Update()

viewer = vtk.vtkImageViewer()
viewer.SetInputConnection(testReader.GetOutputPort())
viewer.Render()
viewer.GetRenderer().ResetCamera()
viewer.Render()


b = raw_input("Im Weroniczka and I know it: ")
# generate file names
dirID =  115298
rootdir = "/FUS4/data2/CHUN_LI/070131/e114985/s%d" % dirID

dirID =  8980
rootdir = "/FUS4/data2/nanorods/20101019nanorods/e7605/s%d" % dirID

nsteps = 60
realimagdata = []
for idfile in range(1,nsteps*2,2):
  realimagdata.append( ("i%d.MRDC.%d"%(dirID+idfile + 0,idfile + 0),
                        "i%d.MRDC.%d"%(dirID+idfile + 1,idfile + 1) )  ) 

# get some header data
vtkDicomInfo = vtk.vtkDICOMImageReader()
vtkDicomInfo.SetFileName("%s/%s"%(rootdir,"i%d.MRDC.%d"%(dirID+1,1) ) )
vtkDicomInfo.Update()
dimensions = vtkDicomInfo.GetOutput().GetDimensions()
spacing_mm = vtkDicomInfo.GetOutput().GetSpacing()
origin_mm  = vtkDicomInfo.GetOutput().GetOrigin()
#convert to meter
spacing = [ 0.001 * dXi for dXi in spacing_mm  ]
origin  = [ 0.001 * Xi for Xi in origin_mm   ]
print dimensions, spacing, origin

# temperature map factor
alpha = +0.0097   # FIXME should be negative but phase messed up somewhere
# FIXME need to extract automagically at some point
#(0018|0081) Echo Time = 9.648
#(0018|0082) Inversion Time = 0
def DisplayDicom(folder=directory):
    reader = vtk.vtkDICOMImageReader()
    reader.SetDirectoryName(directory)
    reader.Update()
    DisplayImageData(reader.GetOutput())
Ejemplo n.º 46
0
def main(argv):
  if len(argv) < 2:
    print "usage: ",argv[0]," <data>"
    exit(1)
  data_fn = argv[1]
  
  mapper = vtk.vtkPolyDataMapper()
  if data_fn.find('.vtk') != -1:
    reader = vtk.vtkPolyDataReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()
    trianglize = vtk.vtkDelaunay2D()
    trianglize.SetInput(data)
    trianglize.Update()
    mapper.SetInputConnection(trianglize.GetOutputPort())
  elif data_fn.find('.pgm') != -1:
    reader = vtk.vtkPNMReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()
    trianglize = vtk.vtkImageDataGeometryFilter()
    trianglize.SetInput(data)
    trianglize.Update()
    warp = vtk.vtkWarpScalar()
    warp.SetScaleFactor(0.2) # arbitrary choice
    warp.SetInputConnection(trianglize.GetOutputPort())
    warp.Update()
    mapper.SetInputConnection(warp.GetOutputPort())
  elif data_fn.find('.dcm') != -1:
    reader =vtk.vtkDICOMImageReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()
    trianglize = vtk.vtkImageDataGeometryFilter()
    trianglize.SetInput(data)
    trianglize.Update()
    warp = vtk.vtkWarpScalar()
    #warp.SetScaleFactor(0.2) # arbitrary choice
    warp.SetInputConnection(trianglize.GetOutputPort())
    warp.Update()
    mapper.SetInputConnection(warp.GetOutputPort())
  else:
    print "unrecognized data file:",data_fn
    exit(1)
  
 
  actor = vtk.vtkActor()
  actor.SetMapper(mapper)
  
  renderer = vtk.vtkRenderer()
  renderWindow = vtk.vtkRenderWindow()
  renderWindow.SetSize(700,700)
  renderWindow.AddRenderer(renderer)
  renderWindow.SetWindowName("heightfield")
 
  renderer.AddActor(actor)
  renderer.SetBackground(0.4,0.3,0.2)

  interactor = vtk.vtkRenderWindowInteractor()
  interactor.SetRenderWindow(renderWindow)
  
  renderWindow.Render()
  interactor.Start()
Ejemplo n.º 47
0
    def _VolumeRender(self, m_contrastRange=None):
        # try:
        # TODO: Write document for the parameter of Volume Render
        m_imagePath = str(self._inDataDirectory)         # TODO: Fill in document
        m_acceptedFormat = ['nii', 'vtk', 'DICOM']

        # Handle contrast range
        if m_contrastRange == None:
            m_contrastUpper = None
            m_contrastLower = 0
        else:
            m_contrastUpper = m_contrastRange[1]
            m_contrastLower = m_contrastRange[0]

        # Image type check TODO: nii.gz, DICOM, ECAT, finish nii.gz first
        m_imagePathSplitted = m_imagePath.split('.')
        m_suffix = m_imagePathSplitted[-1]

        # Create rendere first
        renderer = config.rendererDict[str(self._visualizationJobID)]
        renderer.SetBackground(0,0,0)


        # since nifti might be compressed
        if m_suffix == 'gz':
            m_suffix = m_imagePathSplitted[-2]

        if m_acceptedFormat.count(m_suffix) == 0:
            raise TypeError("Wrong input format, currently except %s"%m_acceptedFormat)

        # TODO: Write the following part to a reader function
        # if nifti - Load image as numpy array
        if m_suffix == 'nii':
            m_reader = vtk.vtkNIFTIImageReader()
            m_reader.SetFileName(self._inDataDirectory)

            # -- Use function from Main Process.
            mp = MainProcess.MainProcess()
            m_volume = mp.VolumeRenderingGPURayCast(m_reader, upperThreshold=m_contrastUpper, lowerThreshold=m_contrastLower)
            renderer.AddVolume(m_volume)

        # if vtk - Load by vtk methods
        elif m_suffix == 'vtk':
            m_reader = vtk.vtkPolyDataReader()
            m_reader.SetFileName(m_imagePath)

            # -- Call volume rendering function
            mp = MainProcess.MainProcess()
            m_actor = mp.VolumeRenderingDTILoader(m_reader)
            renderer.AddActor(m_actor)

        # if DICOM - Load VolumeRenderingDICOMLoader, note that if data is dicom, suffix ".DICOM" show be added to the inDataDirectory
        elif m_suffix == 'DICOM':
            # TODO: allows user defined Threshold
            # -- Construct dicom reader for function in main process
            m_reader = vtk.vtkDICOMImageReader()
            m_reader.SetDataByteOrderToLittleEndian() # TODO: allow user input
            m_reader.SetDirectoryName(m_imagePath.replace(".DICOM", ""))
            m_reader.SetDataSpacing(3.2,3.2,1.5) # TODO: allow user input
            m_reader.SetDataOrigin(0,0,0) # TODO: allow user input

            mp = MainProcess.MainProcess()
            m_volume = mp.VolumeRenderingGPUDICOMLoader(m_reader)
            renderer.AddVolume(m_volume)

        renWin = config.renWinDict[str(self._visualizationJobID)]
        renWin.AddRenderer(renderer)
        result = mp.ImageWriter(renderer, dimension=config.dimensionDict[self._visualizationJobID], outCompressionType=self._outCompressionType)
        return result
Ejemplo n.º 48
0
    def readVolumes(self, path_rootFolder, StudyID, DicomExamNumber, SeriesID, Lesions_id):
        """
        ARGUMENTS:
        =============
        StudyID (str)           Study CAD patient number      
        DicomExamNumber (str)   Imaging Study Number    
        SeriesID  (str)         Dynamic Series number (e.g S600, S3)     
        Lesions_id (str)        Older database LesionID identifier
        
        OUTPUTS:
        =============
        series_path (str)       Path to series location      
        phases_series (list)      list of pre and post contrast volume names      
        lesionID_path  (str)      path to lesion segmentation      
        DICOMImages list(vtkImageData)      List of vtkImageData objects corresponding to dynamic series
        
        """
        series_path = path_rootFolder+os.sep+str(StudyID)+os.sep+str(DicomExamNumber)
        print series_path
        # test
        ###############################################################
        os.chdir(series_path)   
        if os.path.exists('DynPhases'):
            print '''DynPhases'''
            
            # Get series to load
            series_path = path_rootFolder+os.sep+str(StudyID)+os.sep+str(DicomExamNumber)
            lesionID_path = series_path+os.sep+'DynPhases'+os.sep+'VOIlesions_id'+str(Lesions_id)
            
            phases_series=[]
            testSID = str(SeriesID)
            if 'S' in str(testSID):
                #print testSID[1:]
                chosen_phase = int(testSID[1:])
            else:
                chosen_phase = int(testSID)
            
            if(testSID[0] == 'S'):
                phases_series.append('S'+str(chosen_phase))
                                
                for chSer in [chosen_phase+1, chosen_phase+2, chosen_phase+3, chosen_phase+4]:
                    phases_series.append( 'S'+str(chSer) )    
            else:
                phases_series.append(str(chosen_phase))
                                
                for chSer in [chosen_phase+1, chosen_phase+2, chosen_phase+3, chosen_phase+4]:
                    phases_series.append( str(chSer) )

        if not os.path.exists('DynPhases'):
            print '''SeriesPhases'''
            
            # Get series to load
            series_path = path_rootFolder+os.sep+str(StudyID)+os.sep+str(DicomExamNumber)+os.sep+str(SeriesID)
            lesionID_path = series_path+os.sep+'VOIlesions_id'+str(Lesions_id)           
                                                        
            # process all Volumes when in stacks of Dyn Volumes
            if os.path.exists(series_path+os.sep+'pre-Contrast'):
                phases_series = []
                phases_series.append('pre-Contrast')
                        
                #"Arranging series scans"
                for i in range(1,5):
                    phases_series.append('post_Contrast-'+str(i))
        
        # Get total number of files and some DICOM tags needed fro DICOM coords
        pre_abspath_PhaseID = series_path+os.sep+phases_series[0]
        [len_listSeries_files, FileNms_slices_sorted_stack] = self.ReadDicomfiles(pre_abspath_PhaseID)
        mostleft_slice = FileNms_slices_sorted_stack.slices[0]
        
        # Get dicom header, retrieve: image_pos_pat and image_ori_pat
        dicomInfo_series = dicom.read_file(pre_abspath_PhaseID+os.sep+str(mostleft_slice)) 
        self.slice_thickn = float(dicomInfo_series[0x0018,0x0050].value)  
        
        # Image Position (0020,0032): specifies the x, y, and z coordinates of the upper left hand corner of the image. This tag specifies the coordinates 
        # of the the first voxel transmitted.
        self.image_pos_pat = list(dicomInfo_series[0x0020,0x0032].value)
        # Image Orientation (0020,0037): specifies the direction cosines 
        # of the first row and the first column with respect to the patient. 
        # The direction of the axes are defined by the patients orientation 
        # to ensure LPS system ( x-axis increasing to the left hand side of the patient, 
        # y-axis increasing to the posterior side of the patient and z-axis increasing toward
        # the head of the patient )
        self.image_ori_pat = list(dicomInfo_series[0x0020,0x0037].value)
        
        for i in range(0,len(phases_series)):
            abspath_PhaseID = series_path+os.sep+phases_series[i] 
            print abspath_PhaseID
                                     
            # Done reading volume filenames now load them to DICOMimageReader                                         
            os.chdir(abspath_PhaseID)               
            dicomReader  = vtk.vtkDICOMImageReader()
            dicomReader.SetDirectoryName( abspath_PhaseID )
            dicomReader.Update()
            
            im = vtk.vtkImageData()
            im =  dicomReader.GetOutput()
            self.dims = im.GetDimensions()
            self.spacing = im.GetSpacing()
            
            print "VTK Dimensions im.GetDimensions(): %d %d %d" % self.dims
            print "VTK Spacing im.GetSpacing(): %f %f %f\n" % self.spacing
            
            # Append to objects image            
            self.DICOMImages.append( im )
            
        
        return(series_path, phases_series, lesionID_path)        
Ejemplo n.º 49
0
    def __init__(self, parent=None):

        QMainWindow.__init__(self, parent)

        self.setWindowTitle(self.tr("Nirfast"))

        # splitters are used for generating the four views
        self.VSplitter = QSplitter(Qt.Vertical)
        self.HSplitterTop = QSplitter(Qt.Horizontal)
        self.HSplitterBottom = QSplitter(Qt.Horizontal)

        # one instance of each of the VTK_Widget classes
        self.vtk_widget_2 = VTK_Widget2(0)
        self.vtk_widget_3 = VTK_Widget2(1)
        self.vtk_widget_4 = VTK_Widget2(2)
        self.vtk_widget_1 = VTK_Widget1(
            self.vtk_widget_2.cutPlaneSlider, self.vtk_widget_3.cutPlaneSlider, self.vtk_widget_4.cutPlaneSlider
        )

        # the VTK widgets are added to the splitters
        self.VSplitter.addWidget(self.HSplitterTop)
        self.VSplitter.addWidget(self.HSplitterBottom)
        self.HSplitterTop.addWidget(self.vtk_widget_1)
        self.HSplitterTop.addWidget(self.vtk_widget_2)
        self.HSplitterBottom.addWidget(self.vtk_widget_3)
        self.HSplitterBottom.addWidget(self.vtk_widget_4)

        # the top splitter (vertical) is set as central widget
        self.setCentralWidget(self.VSplitter)

        # we embed a reader in the main window, which will fan out the data to all VTK views
        self.reader = vtk.vtkUnstructuredGridReader()
        self.reader2 = vtk.vtkDICOMImageReader()
        self.reader.SetFileName("")
        self.reader2.SetDirectoryName("")

        # we declare a file open action
        self.fileOpenAction = QAction("&Open Solution", self)
        self.fileOpenAction.setShortcut("Ctrl+O")
        self.fileOpenAction.setToolTip("Opens a VTK volume file")
        self.fileOpenAction.setStatusTip("Opens a VTK volume file")

        self.fileOpenAction2 = QAction("&Open DICOMs", self)
        self.fileOpenAction2.setShortcut("Ctrl+D")
        self.fileOpenAction2.setToolTip("Opens a set of DICOMs")
        self.fileOpenAction2.setStatusTip("Opens a set of DICOMs")

        self.connect(self.fileOpenAction, SIGNAL("triggered()"), self.fileOpen)
        self.connect(self.fileOpenAction2, SIGNAL("triggered()"), self.fileOpen2)

        self.fileMenu = self.menuBar().addMenu("&File")
        self.fileMenu.addAction(self.fileOpenAction)
        self.fileMenu.addAction(self.fileOpenAction2)

        # property label
        self.label_property = QLabel("Property: ")

        # property dropdown
        self.dropdown_property = QComboBox()

        # spacing label
        self.label_spacing = QLabel("      ")

        # clip buttons
        self.button_clipx = QPushButton("Clip x")
        self.button_clipy = QPushButton("Clip y")
        self.button_clipz = QPushButton("Clip z")

        # toolbar
        self.viewToolbar = self.addToolBar("View")
        self.viewToolbar.setObjectName("ViewToolbar")
        self.viewToolbar.addWidget(self.label_property)
        self.viewToolbar.addWidget(self.dropdown_property)
        self.viewToolbar.addWidget(self.label_spacing)
        self.viewToolbar.addWidget(self.button_clipx)
        self.viewToolbar.addWidget(self.button_clipy)
        self.viewToolbar.addWidget(self.button_clipz)

        self.connect(self.button_clipx, SIGNAL("clicked()"), self.Clipx)
        self.connect(self.button_clipy, SIGNAL("clicked()"), self.Clipy)
        self.connect(self.button_clipz, SIGNAL("clicked()"), self.Clipz)
        self.connect(self.dropdown_property, SIGNAL("currentIndexChanged(int)"), self.SetProperty)
'''



import vtk





dir1 = '/home/qinshuo/Data/Data1'
dir2 = '/home/qinshuo/Data/Data2'


reader1 = vtk.vtkDICOMImageReader()
reader1.SetDirectoryName(dir1)
reader1.Update()
img1 = reader1.GetOutput()

reader2 = vtk.vtkDICOMImageReader()
reader2.SetDirectoryName(dir2)
reader2.Update()
img2 = reader2.GetOutput()

# reslice direction
dir_X = [0,0,0]
dir_Y = [0,0,0]
dir_Z = [0,0,0]

# reslice center
Ejemplo n.º 51
0
    def __init__(self, parent = None):

        self.reader = vtk.vtkDICOMImageReader()
        self.dataExtent = []
        self.dataDimensions = []
        self.dataRange = ()

        # initialize GUI
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.ui.WindowCenterSlider.setRange(0, 1000)
        self.ui.WindowWidthSlider.setRange(0, 1000)

        # define viewers
        [self.viewerXY, self.viewerYZ, self.viewerXZ] = [vtk.vtkImageViewer2() for x in range(3)]

        # attach interactors to viewers
        self.viewerXY.SetupInteractor(self.ui.XYPlaneWidget)
        self.viewerYZ.SetupInteractor(self.ui.YZPlaneWidget)
        self.viewerXZ.SetupInteractor(self.ui.XZPlaneWidget)

        # set render windows for viewers
        self.viewerXY.SetRenderWindow(self.ui.XYPlaneWidget.GetRenderWindow())
        self.viewerYZ.SetRenderWindow(self.ui.YZPlaneWidget.GetRenderWindow())
        self.viewerXZ.SetRenderWindow(self.ui.XZPlaneWidget.GetRenderWindow())

        # set slicing orientation for viewers
        self.viewerXY.SetSliceOrientationToXZ()
        self.viewerYZ.SetSliceOrientationToYZ()
        self.viewerXZ.SetSliceOrientationToXY()

        # rotate image
        act = self.viewerYZ.GetImageActor()
        act.SetOrientation(90, 0, 0)

        # setup volume rendering
        self.volRender = vtk.vtkRenderer()
        self.volRenWin = self.ui.VolumeWidget.GetRenderWindow()
        self.volRenWin.AddRenderer(self.volRender)

        self.rayCastFunction = vtk.vtkVolumeRayCastCompositeFunction()
        self.volumeMapper = vtk.vtkVolumeRayCastMapper()
        self.volumeMapper.SetVolumeRayCastFunction(self.rayCastFunction)

        volumeColor = vtk.vtkColorTransferFunction()
        volumeColor.AddRGBPoint(0,    0.0, 0.0, 0.0)
        volumeColor.AddRGBPoint(500,  1.0, 0.5, 0.3)
        volumeColor.AddRGBPoint(1000, 1.0, 0.5, 0.3)
        volumeColor.AddRGBPoint(1150, 1.0, 1.0, 0.9)
        self.volumeColor = volumeColor

        volumeScalarOpacity = vtk.vtkPiecewiseFunction()
        volumeScalarOpacity.AddPoint(0,    0.00)
        volumeScalarOpacity.AddPoint(50,  0.15)
        volumeScalarOpacity.AddPoint(100, 0.15)
        volumeScalarOpacity.AddPoint(115, 0.85)
        self.volumeScalarOpacity = volumeScalarOpacity

        volumeGradientOpacity = vtk.vtkPiecewiseFunction()
        volumeGradientOpacity.AddPoint(0,   0.0)
        volumeGradientOpacity.AddPoint(100,  0.5)
        volumeGradientOpacity.AddPoint(500, 1)
        self.volumeGradientOpacity = volumeGradientOpacity

        volumeProperty = vtk.vtkVolumeProperty()
        volumeProperty.SetColor(volumeColor)
        volumeProperty.SetScalarOpacity(volumeScalarOpacity)
        volumeProperty.SetGradientOpacity(volumeGradientOpacity)
        volumeProperty.SetInterpolationTypeToLinear()
        volumeProperty.ShadeOn()
        volumeProperty.SetAmbient(0.4)
        volumeProperty.SetDiffuse(0.6)
        volumeProperty.SetSpecular(0.2)
        self.volumeProperty = volumeProperty

        volume = vtk.vtkVolume()
        volume.SetMapper(self.volumeMapper)
        volume.SetProperty(self.volumeProperty)
        self.volume = volume

        self.volRender.AddViewProp(volume)
Ejemplo n.º 52
0
def main(argv):
  if len(argv) < 2:
    print "usage: ",argv[0]," <data> [flat]"
    exit(1)
  data_fn = argv[1]
  flat = False
  if len(argv) > 2:
    flat = True
  
  mapper = vtk.vtkPolyDataMapper()
  if data_fn.find('.vtk') != -1:
    reader = vtk.vtkPolyDataReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()
    trianglize = vtk.vtkDelaunay2D()
    trianglize.SetInput(data)
    trianglize.Update()
    mapper.SetInputConnection(trianglize.GetOutputPort())
  elif data_fn.find('.pgm') != -1:
    reader = vtk.vtkPNMReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()
    geometry = vtk.vtkImageDataGeometryFilter()
    geometry.SetInputConnection(reader.GetOutputPort())
    geometry.Update()
    if flat:
      merge = vtk.vtkMergeFilter()
      merge.SetGeometry(geometry.GetOutput())
      merge.SetScalars(data)
      mapper.SetInputConnection(merge.GetOutputPort())
    else:
      warp = vtk.vtkWarpScalar()
      warp.SetInputConnection(geometry.GetOutputPort())
      warp.SetScaleFactor(0.3) # looked good
      warp.Update()
      merge = vtk.vtkMergeFilter()
      merge.SetGeometry(warp.GetOutput())
      merge.SetScalars(data)
      mapper.SetInputConnection(merge.GetOutputPort())
  elif data_fn.find('.dcm') != -1:
    reader =vtk.vtkDICOMImageReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()
    geometry = vtk.vtkImageDataGeometryFilter()
    geometry.SetInput(data)
    geometry.Update()
    if flat:
      mapper.SetInputConnection(geometry.GetOutputPort())
    else:
      warp = vtk.vtkWarpScalar()
      warp.SetInputConnection(geometry.GetOutputPort())
      warp.Update()
      mapper.SetInputConnection(warp.GetOutputPort())
  else:
    print "unrecognized data file:",data_fn
    exit(1)
  
  lut = vtk.vtkLookupTable()
  lut.SetNumberOfColors(10)
  lut.SetHueRange(0.5,0.3)
  lut.SetSaturationRange(0.6,0.5)
  lut.SetValueRange(1.0,0.5)
  lut.Build()

  mapper.ImmediateModeRenderingOff()
  mapper.SetLookupTable(lut)
 
  actor = vtk.vtkActor()
  actor.SetMapper(mapper)
  
  renderer = vtk.vtkRenderer()
  renderWindow = vtk.vtkRenderWindow()
  renderWindow.SetSize(700,700)
  renderWindow.AddRenderer(renderer)
 
  renderer.AddActor(actor)
  renderer.SetBackground(0.4,0.3,0.2)

  interactor = vtk.vtkRenderWindowInteractor()
  interactor.SetRenderWindow(renderWindow)
  
  renderWindow.Render()
  interactor.Start()
Ejemplo n.º 53
0
def main(argv):
  if len(argv) < 2:
    print "usage: ",argv[0]," <data>"
    exit(1)
  data_fn = argv[1]
  
  data = None
  if data_fn.find('.vtk') != -1:
    reader = vtk.vtkStructuredPointsReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()
  elif data_fn.find('.dcm') != -1:
    reader =vtk.vtkDICOMImageReader()
    reader.SetFileName(data_fn)
    reader.Update()
    data = reader.GetOutput()

  ptdata = data.GetPointData()
  scalars = ptdata.GetScalars()  
  data_range = scalars.GetValueRange()
  print "data range:",data_range
  contourer = vtk.vtkContourFilter()
  if data_fn.find('body') != -1:
    contourer.GenerateValues(10,data_range[0],data_range[1])
    #contourer.GenerateValues(5,data_range[0],data_range[1])
  elif data_fn.find('brain') != -1:
    contourer.GenerateValues(10,data_range[0],data_range[1])
  elif data_fn.find('artichoke') != -1:
    contourer.GenerateValues(50,data_range[0],data_range[1])
  elif data_fn.find('watermelon') != -1:
    contourer.GenerateValues(20,data_range[0],data_range[1])
    #contourer.GenerateValues(5,data_range[0],data_range[1])
  else:
    contourer.GenerateValues(10,data_range[0],data_range[1])
    #contourer.SetNumberOfContours(3)
    #contourer.SetValue(0, 100)
    #contourer.SetValue(1, 300)
    #contourer.SetValue(2, 400)
  contourer.SetInput(data)
  contourer.Update()

  mapper = vtk.vtkPolyDataMapper()
  mapper.SetInputConnection(contourer.GetOutputPort())

  actor = vtk.vtkActor()
  actor.SetMapper(mapper)
  
  renderer = vtk.vtkRenderer()
  renderWindow = vtk.vtkRenderWindow()
  renderWindow.SetSize(700,700)
  renderWindow.AddRenderer(renderer)
 
  renderer.AddActor(actor)
  renderer.SetBackground(0.4,0.3,0.2)

  interactor = vtk.vtkRenderWindowInteractor()
  interactor.SetRenderWindow(renderWindow)
  
  renderWindow.Render()
  interactor.Start()
import os
import numpy
import matplotlib.pyplot as plt

#function to convert the vtk image into a numpy array, useful for showing images
def vtkImageToNumPy(image, pixelDims):
    pointData = image.GetPointData()
    arrayData = pointData.GetArray(0)
    ArrayDicom = numpy_support.vtk_to_numpy(arrayData)
    ArrayDicom = ArrayDicom.reshape(pixelDims, order = 'F') #reshape the array into Fourier space
    
    return ArrayDicom

#---code start---    
path = os.getcwd() #define path from current working directory
reader = vtk.vtkDICOMImageReader()  #load DICOM reader
reader.SetDirectoryName(path)
reader.Update() #read in DICOM files

dims = reader.GetDataExtent() #extract pixel dimensions
ConstPixelDims = [dims[1]-dims[0]+1, dims[3]-dims[2]+1, dims[5]-dims[4]+1] #calculate true pixel dimensions
ConstPixelSpacing = reader.GetPixelSpacing() #extract pixel spacing information



#ArrayDicom = vtkImageToNumPy(reader.GetOutput(), ConstPixelDims)
img = reader.GetOutputPort()

threshold = vtk.vtkImageThreshold () #load threshold function
threshold.SetInputConnection(img) #load image from reader
threshold.ThresholdByUpper(400)  # set the upper Threshold Value, using Hounsfield Values