Пример #1
0
def image_reader(fn_tup):

    img_fn, truth_fn, path_fn, grp_fn = fn_tup
    reader = vtk.vtkMetaImageReader()
    reader2 = vtk.vtkMetaImageReader()

    img_name = img_fn.split('/')[-2]

    reader.SetFileName(img_fn)
    reader.Update()
    the_image = reader.GetOutput()
    the_image = resample_image(the_image)

    model = truth_fn
    model_name = model.split('/')[-2]

    print img_fn, truth_fn

    reader2.SetFileName(model)
    reader2.Update()
    the_model = reader2.GetOutput()
    the_model = resample_image(the_model)

    path_dict = utility.parsePathFile(path_fn)

    return (the_image, the_model, path_dict, grp_fn)
Пример #2
0
def display_substract(file1, file2):
    source1 = vtk.vtkMetaImageReader()
    source1.SetFileName(file1)
    source1.Update()
    source2 = vtk.vtkMetaImageReader()
    source2.SetFileName(file2)
    source2.Update()
    substract = vtk.vtkImageMathematics()
    substract.SetOperationToSubtract()
    substract.SetInput1Data(source1.GetOutput())
    substract.SetInput2Data(source2.GetOutput())
    substract.Update()
    visualize_3d(substract)
Пример #3
0
  def sumManualSegmentations(self, manualSegmentationsDirectory, mergedVolume):
    # Get the manual segmentations and create a single summed image
    import glob
    manualSegmentationFilenames = glob.glob(manualSegmentationsDirectory+"/*.mha")

    # Get the first image which each successive image will be added to
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(manualSegmentationFilenames[0])
    reader.Update()
    summedImage = vtk.vtkImageData()
    summedImage.SetExtent(reader.GetOutput().GetExtent())
    summedImage.AllocateScalars(vtk.VTK_UNSIGNED_CHAR,1)
    summedImage.ShallowCopy(reader.GetOutput())

    # Initialize filter to add images together
    mathFilter = vtk.vtkImageMathematics()

    # Iterate list and add each new image
    for currentFile in manualSegmentationFilenames[1:]:
      # Get new image
      reader.SetFileName(currentFile)
      reader.Update()

      # Add it to existing summation
      mathFilter.SetInput1Data(summedImage)
      mathFilter.SetInput2Data(reader.GetOutput())
      mathFilter.Update()

      # Get new summation
      summedImage.ShallowCopy(mathFilter.GetOutput())

    # Add summed image to slicer scene
    mergedVolume.SetRASToIJKMatrix(self.rasToIjk)
    mergedVolume.SetIJKToRASMatrix(self.ijkToRas)
    mergedVolume.SetAndObserveImageData(summedImage)
Пример #4
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)

        self._reader = vtk.vtkMetaImageReader()

        module_utils.setup_vtk_object_progress(self, self._reader,
                                           'Reading MetaImage data.')
        

        self._config.filename = ''

        configList = [
            ('File name:', 'filename', 'base:str', 'filebrowser',
             'The name of the MetaImage file you want to load.',
             {'fileMode' : wx.OPEN,
              'fileMask' :
              'MetaImage single file (*.mha)|*.mha|MetaImage separate header '
              '(*.mhd)|*.mhd|All files (*.*)|*.*'})]

        ScriptedConfigModuleMixin.__init__(
            self, configList,
            {'Module (self)' : self,
             'vtkMetaImageReader' : self._reader})

        self.sync_module_logic_with_config()
Пример #5
0
def write_3slices_files(fn_mha="t.mha", fn_info="i.txt", dir_out=os.getcwd()):
    """ write the 3-slice group specified in fn_info
    each line: angle center size file_name_base
    specifically: a1 a2 a3     c1 c2 c3     sz label fnbase
    the 3*N output files would be: fnbase_1_1.mha, ..., fnbase_1_3.mha, fnbase_2_1.mha,..., fnbase_N_3.mha,
    where N is the number of lines in fn_info"""

    # get the image
    rd = vtk.vtkMetaImageReader()
    rd.SetFileName(fn_mha)
    rd.Update()
    img = rd.GetOutput()

    # make sure th output dir exists
    if not os.path.exists(dir_out):
        os.makedirs(dir_out)

    # loop the lines in info file and generate the 3-slice accordingly
    with open(fn_info, 'r') as f:
        for cnt, line in enumerate(f):
            # get the angle, center, size and base name
            elems = line.split()
            a = [int(x) for x in elems[0:3]]
            cen = [int(x) for x in elems[3:6]]
            sz = int(elems[6])
            # elems[7] is the label, not used here
            fnbase_out = elems[8]

            # do the job: get the 3 slices
            ss = gen_3s(img, a, cen, sz)

            # write the 3 slices
            for i, the_slice in enumerate(ss):
                fn_slice = "%s_%d_%d.mha" % (fnbase_out, cnt+1, i+1)
                write_slice(the_slice, os.path.join(dir_out, fn_slice))
Пример #6
0
def CreateFrogActor(fileName, tissue):
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(fileName)
    reader.Update()

    selectTissue = vtk.vtkImageThreshold()
    selectTissue.ThresholdBetween(tissue, tissue)
    selectTissue.SetInValue(255)
    selectTissue.SetOutValue(0)
    selectTissue.SetInputConnection(reader.GetOutputPort())

    isoValue = 63.5
    mcubes = vtk.vtkMarchingCubes()
    mcubes.SetInputConnection(selectTissue.GetOutputPort())
    mcubes.ComputeScalarsOff()
    mcubes.ComputeGradientsOff()
    mcubes.ComputeNormalsOn()
    mcubes.SetValue(0, isoValue)

    stripper = vtk.vtkStripper()
    stripper.SetInputConnection(mcubes.GetOutputPort())

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

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor
Пример #7
0
def writeAllImageSlices(imgfn,pathfn,ext,output_dir):
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(imgfn)
    reader.Update()
    img = reader.GetOutput()

    parsed_path = parsePathFile(pathfn)
    slices = getAllImageSlices(img,parsed_path,ext)

    writer = vtk.vtkJPEGWriter()

    table = vtk.vtkLookupTable()
    scalar_range = img.GetScalarRange()
    table.SetRange(scalar_range[0], scalar_range[1]) # image intensity range
    table.SetValueRange(0.0, 1.0) # from black to white
    table.SetSaturationRange(0.0, 0.0) # no color saturation
    table.SetRampToLinear()
    table.Build()

    # Map the image through the lookup table
    color = vtk.vtkImageMapToColors()
    color.SetLookupTable(table)

    mkdir(output_dir)
    for i in range(len(slices)):
        color.SetInputData(slices[i])
        writer.SetInputConnection(color.GetOutputPort())
        writer.SetFileName(output_dir+'{}.jpg'.format(i))
        writer.Update()
        writer.Write()
        def CreateVolumeSource(self):
            imageReader = vtk.vtkMetaImageReader()
            imageReader.SetFileName(self.ImageFileName)

            compSrc = vtk.vtkImageExtractComponents()
            compSrc.SetInputConnection(imageReader.GetOutputPort())
            compSrc.SetComponents(self.ComponentIndex)
            compSrc.Update()

            valueMin, valueMax = compSrc.GetOutput().GetPointData().GetArray(
                'MetaImage').GetValueRange()
            valueMin = 0.0

            toUnsignedShort = vtk.vtkImageShiftScale()
            toUnsignedShort.ClampOverflowOn()
            toUnsignedShort.SetShift(-valueMin)
            if valueMax - valueMin != 0:
                toUnsignedShort.SetScale(
                    512.0 /
                    (valueMax -
                     valueMin))  #randomly cause error that "zerodivision"
            toUnsignedShort.SetInputConnection(compSrc.GetOutputPort())
            toUnsignedShort.SetOutputScalarTypeToUnsignedShort()

            return toUnsignedShort
Пример #9
0
def loadImageData(filename, spacing=()):
    """Read and return a ``vtkImageData`` object from file.
    Use ``load`` instead.
    E.g. `img = load('myfile.tif').imagedata()`
    """
    if ".tif" in filename.lower():
        reader = vtk.vtkTIFFReader()
    elif ".slc" in filename.lower():
        reader = vtk.vtkSLCReader()
        if not reader.CanReadFile(filename):
            colors.printc("~prohibited Sorry bad slc file " + filename, c=1)
            return None
    elif ".vti" in filename.lower():
        reader = vtk.vtkXMLImageDataReader()
    elif ".mhd" in filename.lower():
        reader = vtk.vtkMetaImageReader()
    elif ".dem" in filename.lower():
        reader = vtk.vtkDEMReader()
    elif ".nii" in filename.lower():
        reader = vtk.vtkNIFTIImageReader()
    elif ".nrrd" in filename.lower():
        reader = vtk.vtkNrrdReader()
        if not reader.CanReadFile(filename):
            colors.printc("~prohibited Sorry bad nrrd file " + filename, c=1)
            return None
    reader.SetFileName(filename)
    reader.Update()
    image = reader.GetOutput()
    if len(spacing) == 3:
        image.SetSpacing(spacing[0], spacing[1], spacing[2])
    return image
Пример #10
0
def trim_mha(fn = "dataset.mha", fnout = "t.mha"):
    if not os.path.exists(fn):
        print "%s does not exists, skip" % (fn,)
        return
    
    # read mha image
    rd = vtk.vtkMetaImageReader()
    rd.SetFileName(fn)
    rd.Update()

    # the image data
    img = vtk.vtkImageData()
    img = rd.GetOutput()

    # set spacing to (1.0, 1.0, 1.0)
    spacing = img.GetSpacing()
    new_spacing = (1.0, 1.0, 1.0)
    img.SetSpacing(new_spacing)

    # set the origin to (0.0, 0.0, 0.0)
    new_orig = (0.0, 0.0, 0.0)
    img.SetOrigin(new_orig)
    
    # write mha
    wt = vtk.vtkMetaImageWriter()
    wt.SetInputData(img)
    wt.SetFileName(fnout)
    wt.Write()

    return spacing
Пример #11
0
    def read_metaimage(self, fname_meta, cast_type=5):

        reader = vtk.vtkMetaImageReader()
        reader.SetFileName(fname_meta)

        # VTK image cast
        img_cast = vtk.vtkImageCast()
        if cast_type == 0:
            # return a vtkImageData with wrong dims and bounds value
            self.reader = reader.GetOutput()
            # return reader.GetOutput()

        elif cast_type in [i for i in range(2, 12)]:
            img_cast.SetInputConnection(reader.GetOutputPort())
            img_cast.SetOutputScalarType(cast_type)
            img_cast.Update()
            self.reader = img_cast.GetOutput()
            # return img_cast.GetOutput()  # a vtkImageData

        else:
            sys.stderr.write(
                ('Wrong Cast Type! It should be 2, 3, ..., 11\n')
                ('No Image Cast Applied')
            )
            self.reader = img_cast.GetOutput()
            # return reader.GetOutput()

        self.flag_read = True

        return self.reader
Пример #12
0
def mhd_getRatios(fname):
  """
  Get relative axis ratios from MHD file defined by fname
  """
  if not os.path.exists(fname):
    print "imageStackLoader.mhd_getRatios can not find %s" % fname
    return
    
  try:
    #Attempt to use the vtk module to read the element spacing
    imp.find_module('vtk')
    import vtk
    imr = vtk.vtkMetaImageReader()
    imr.SetFileName(fname)
    imr.Update()
 
    im = imr.GetOutput()
    spacing = im.GetSpacing()    
  except ImportError:
    #If the vtk module fails, we try to read the spacing using the built-in reader
    info = mhd_read_header_file(fname)
    if info.has_key('elementspacing'):
      spacing = info['elementspacing']
    else:
      print "Failed to find spacing info in MHA file. Using default axis length values"      
      return lasHelp.readPreference('defaultAxisRatios') #defaults


  if len(spacing)==0: 
    print "Failed to find spacing valid spacing info in MHA file. Using default axis length values"      
    return lasHelp.readPreference('defaultAxisRatios') #defaults
  
  return spacingToRatio(spacing)  
Пример #13
0
def mhdRead(fname,fallBackMode = False):
  """
  Read an MHD file using either VTK (if available) or the slower-built in reader
  if fallBackMode is true we force use of the built-in reader
  """
  if fallBackMode == False: 
    #Attempt to load vtk
    try:
      imp.find_module('vtk')
      import vtk
      from vtk.util.numpy_support import vtk_to_numpy
    except ImportError:
      print "Failed to find VTK. Falling back to built in (but slower) MHD reader"
      fallBackMode = True

  if fallBackMode:
    return mhdRead_fallback(fname)
  else:
    #use VTK
    imr = vtk.vtkMetaImageReader()
    imr.SetFileName(fname)
    imr.Update()

    im = imr.GetOutput()

    rows, cols, z = im.GetDimensions()
    sc = im.GetPointData().GetScalars()
    a = vtk_to_numpy(sc)
    a = a.reshape(z, cols, rows) 
    a = a.swapaxes(1,2)
    print "Using VTK to read MHD image of size: cols: %d, rows: %d, layers: %d" % (rows,cols,z)
    return a    
Пример #14
0
    def load_data_from_file(self, file_path):
        """Loads scanvolume data from file. Also sets the volume as input for the sliceviewers
        """
        self._view_frame.SetStatusText("Opening file: %s..." % (file_path))
        filename = os.path.split(file_path)[1]
        fileBaseName = os.path.splitext(filename)[0]

        reader = vtk.vtkMetaImageReader()
        reader.SetFileName(file_path)
        reader.Update()
        self.image_data = reader.GetOutput()
        self.slice_viewer1.set_input(self.image_data)
        self.slice_viewer1.reset_camera()
        self.slice_viewer1.render()

        self.slice_viewer2.set_input(self.image_data)
        self.slice_viewer2.reset_camera()
        self.slice_viewer2.render()

        self.slice_viewer3.set_input(self.image_data)
        self.slice_viewer3.render()
        self.slice_viewer3.set_opacity(0.1)
        cam = self.ren.GetActiveCamera()
        cam.SetPosition(0, -100, 0)
        cam.SetFocalPoint(0, 0, 0)
        cam.SetViewUp(0, 0, 1)
        self.ren.ResetCamera()

        if (self.mask_data
            ) is not None:  # We can start calculating the volumerender
            self.create_volumerender(0, 0)
        else:
            self._view_frame.SetStatusText("Opened file")
Пример #15
0
def create_frog_actor(file_name, tissue, use_flying_edges):
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(str(file_name))
    reader.Update()

    select_tissue = vtk.vtkImageThreshold()
    select_tissue.ThresholdBetween(tissue, tissue)
    select_tissue.SetInValue(255)
    select_tissue.SetOutValue(0)
    select_tissue.SetInputConnection(reader.GetOutputPort())

    iso_value = 63.5
    if use_flying_edges:
        try:
            iso_surface = vtk.vtkFlyingEdges3D()
        except AttributeError:
            iso_surface = vtk.vtkMarchingCubes()
    else:
        iso_surface = vtk.vtkMarchingCubes()
    iso_surface.SetInputConnection(select_tissue.GetOutputPort())
    iso_surface.ComputeScalarsOff()
    iso_surface.ComputeGradientsOff()
    iso_surface.ComputeNormalsOn()
    iso_surface.SetValue(0, iso_value)

    stripper = vtk.vtkStripper()
    stripper.SetInputConnection(iso_surface.GetOutputPort())

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

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor
Пример #16
0
    def read_metaimage(self, fname_meta, cast_type=5):

        reader = vtk.vtkMetaImageReader()
        reader.SetFileName(fname_meta)

        # VTK image cast
        img_cast = vtk.vtkImageCast()
        if cast_type == 0:
            # return a vtkImageData with wrong dims and bounds value
            self.reader = reader.GetOutput()
            # return reader.GetOutput()

        elif cast_type in [i for i in range(2, 12)]:
            img_cast.SetInputConnection(reader.GetOutputPort())
            img_cast.SetOutputScalarType(cast_type)
            img_cast.Update()
            self.reader = img_cast.GetOutput()
            # return img_cast.GetOutput()  # a vtkImageData

        else:
            sys.stderr.write(('Wrong Cast Type! It should be 2, 3, ..., 11\n'
                              )('No Image Cast Applied'))
            self.reader = img_cast.GetOutput()
            # return reader.GetOutput()

        self.flag_read = True

        return self.reader
Пример #17
0
def read_meta_image(meta_name, cast_type=5):
    """
    Usually Meta Image is `unsigned short`
    No casting leads to wrong reslut!
    """
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(meta_name)

    # No cast
    if cast_type == 0:
        # vtkImageData with wrong dims and bounds value.
        return reader.GetOutput()

    # Cast the image to another data type
    elif cast_type in [i for i in range(2, 12)]:
        cast = vtk.vtkImageCast()
        # cast.SetInputData(img_vtk)
        cast.SetInputConnection(reader.GetOutputPort())
        cast.SetOutputScalarType(cast_type)
        cast.Update()
        return cast.GetOutput()  # The output of `cast` is a vtkImageData

    # Wrong cast type. Return the no-cast vtkImageData
    else:
        sys.stderr.write('Wrong Cast Type! It should be 2, 3, ..., or 11')
        return reader.GetOutput()
Пример #18
0
    def loadUSFile(self, fileName):
        # Load VTK Meta Image
        reader = vtk.vtkMetaImageReader()
        reader.SetFileName(fileName)
        reader.Update()
        imageDims = reader.GetOutput().GetDimensions()

        # Disable renderers
        for i in range(len(self.viewUS)):
            self.viewUS[i].viewer.GetInteractor().EnableRenderOff()

        # Share one cursor object
        for i in range(len(self.viewUS)):
            self.viewUS[i].viewer.SetResliceCursor(
                self.viewUS[0].viewer.GetResliceCursor())

        # Assign data to 2D viewers sharing one cursorobject
        for i in range(len(self.viewUS)):
            self.viewUS[i].SetInputData(reader.GetOutput())

        # Enable 2D viewers
        for i in range(len(self.viewUS)):
            self.viewUS[i].viewer.GetRenderer().ResetCamera()
            self.viewUS[i].viewer.GetInteractor().EnableRenderOn()

        # Enable interactors
        for i in range(len(self.viewUS)):
            self.viewUS[i].viewer.GetInteractor().Enable()

        self.ResetUSViews()
        self.SetUSResliceMode(1)  # Oblique
        self.Render()
Пример #19
0
    def load_data_from_file(self, file_path):
        """Loads scanvolume data from file. Also sets the volume as input for the sliceviewers
        """
        self._view_frame.SetStatusText("Opening file: %s..." % (file_path))        
        filename = os.path.split(file_path)[1]
        fileBaseName =os.path.splitext(filename)[0]

        reader = vtk.vtkMetaImageReader()
        reader.SetFileName(file_path)
        reader.Update()
        self.image_data = reader.GetOutput()
        self.slice_viewer1.set_input(self.image_data)
        self.slice_viewer1.reset_camera()
        self.slice_viewer1.render()

        self.slice_viewer2.set_input(self.image_data)
        self.slice_viewer2.reset_camera()
        self.slice_viewer2.render()
        
        self.slice_viewer3.set_input(self.image_data)
        self.slice_viewer3.render()
        self.slice_viewer3.set_opacity(0.1)
        cam = self.ren.GetActiveCamera()
        cam.SetPosition(0,-100,0)
        cam.SetFocalPoint(0,0,0)
        cam.SetViewUp(0,0,1)
        self.ren.ResetCamera()
       
        if (self.mask_data) is not None: # We can start calculating the volumerender
	        self.create_volumerender(0,0)
        else:
	        self._view_frame.SetStatusText("Opened file")
Пример #20
0
    def __init__(self, module_manager):
        ModuleBase.__init__(self, module_manager)

        self._reader = vtk.vtkMetaImageReader()

        module_utils.setup_vtk_object_progress(self, self._reader,
                                               'Reading MetaImage data.')

        self._config.filename = ''

        configList = [(
            'File name:', 'filename', 'base:str', 'filebrowser',
            'The name of the MetaImage file you want to load.', {
                'fileMode':
                wx.OPEN,
                'fileMask':
                'MetaImage single file (*.mha)|*.mha|MetaImage separate header '
                '(*.mhd)|*.mhd|All files (*.*)|*.*'
            })]

        ScriptedConfigModuleMixin.__init__(self, configList, {
            'Module (self)': self,
            'vtkMetaImageReader': self._reader
        })

        self.sync_module_logic_with_config()
Пример #21
0
    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        #self.resize(800,600)

        self.frame1 = QCILViewerWidget(
            viewer=viewer2D,
            shape=(600, 600),
            interactorStyle=vlink.Linked2DInteractorStyle)
        self.frame2 = QCILViewerWidget(
            viewer=viewer3D,
            shape=(600, 600),
            interactorStyle=vlink.Linked3DInteractorStyle)

        reader = vtk.vtkMetaImageReader()
        reader.SetFileName('head.mha')
        reader.Update()

        self.frame1.viewer.setInputData(reader.GetOutput())
        self.frame2.viewer.setInputData(reader.GetOutput())

        # Initially link viewers
        self.linkedViewersSetup()
        self.link2D3D.enable()

        layout = QtWidgets.QBoxLayout(QtWidgets.QBoxLayout.LeftToRight)
        layout.addWidget(self.frame1)
        layout.addWidget(self.frame2)

        cw = QtWidgets.QWidget()
        cw.setLayout(layout)
        self.setCentralWidget(cw)
        self.central_widget = cw
        self.show()
Пример #22
0
def vtkImageReader(file, segmentation=False):
    """
    using vtkMetaImageReader to read mhd file
    :param file: the path of the mhd file (note: using '/' instead of '\' in absolute path)
    :param segmentation: assign true when file is partial volume segmentation
    :return: updated reader
    """
    image = vtk.vtkMetaImageReader()
    image.SetFileName(file)
    image.Update()
    print(image.GetOutput())
    if segmentation:
        # turn datatype to ushort
        # and increase the voxel value by multiply a constant if it is a partial volume segmentation file
        cast = vtk.vtkImageCast()
        cast.SetInputConnection(image.GetOutputPort())
        cast.SetOutputScalarTypeToUnsignedShort()
        cast.Update()

        math = vtk.vtkImageMathematics()
        math.SetOperationToMultiplyByK()
        math.SetConstantK(1150.0)
        math.SetInputConnection(cast.GetOutputPort())
        math.Update()
        return math
    else:
        return image
Пример #23
0
def main():
    filename = get_program_parameters()

    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(filename)
    reader.Update()

    # Visualize
    actor = vtk.vtkImageActor()
    actor.GetMapper().SetInputConnection(reader.GetOutputPort())

    renderer = vtk.vtkRenderer()
    renderer.AddActor(actor)
    renderer.ResetCamera()

    render_window = vtk.vtkRenderWindow()
    render_window.AddRenderer(renderer)

    render_window_interactor = vtk.vtkRenderWindowInteractor()
    style = vtk.vtkInteractorStyleImage()

    render_window_interactor.SetInteractorStyle(style)

    render_window_interactor.SetRenderWindow(render_window)
    render_window.Render()
    render_window_interactor.Initialize()

    render_window_interactor.Start()
Пример #24
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(
         self, module_manager,
         vtk.vtkMetaImageReader(), 'Reading vtkMetaImage.',
         (), ('vtkMetaImage',),
         replaceDoc=True,
         inputFunctions=None, outputFunctions=None)
Пример #25
0
def createSTL(mha, stl):

    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(mha)
    reader.Update()

    threshold = vtk.vtkImageThreshold()
    threshold.SetInputConnection(reader.GetOutputPort())
    threshold.ThresholdByLower(0.1)
    threshold.ReplaceInOn()
    threshold.SetInValue(0)  # set all values below 0.1 to 0
    threshold.ReplaceOutOn()
    threshold.SetOutValue(1)  # set all values above 0.1 to 1
    threshold.Update()

    dmc = vtk.vtkFlyingEdges3D()
    dmc.SetInputConnection(threshold.GetOutputPort())
    dmc.ComputeNormalsOn()
    dmc.GenerateValues(1, 1, 1)
    dmc.Update()

    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputConnection(dmc.GetOutputPort())
    smoother.SetNumberOfIterations(15)
    smoother.BoundarySmoothingOff()
    smoother.Update()

    writer = vtk.vtkSTLWriter()
    writer.SetInputConnection(smoother.GetOutputPort())
    writer.SetFileTypeToBinary()
    writer.SetFileName(stl)
    writer.Write()

    return 0
Пример #26
0
    def loadFile(self, fileName):
        # Load VTK Meta Image
        reader = vtk.vtkMetaImageReader()
        reader.SetFileName(fileName)
        reader.Update()

        # TEST
        self.imageData = reader.GetOutput()

        imageDims = reader.GetOutput().GetDimensions()

        # Disable renderers and widgets
        self.stack.EnableRenderOff()
        self.viewer3D.interactor.EnableRenderOff()

        # Turn-off plane widgets
        for i in range(3):
            self.viewer3D.planeWidgets[i].Off()

        # Assign data to 2D viewers sharing one cursorobject
        self.stack.SetInputData(reader.GetOutput())

        # Enable plane widgets
        for i in range(3):
            self.viewer3D.planeWidgets[i].SetInputConnection(
                reader.GetOutputPort())
            self.viewer3D.planeWidgets[i].SetPlaneOrientation(i)
            self.viewer3D.planeWidgets[i].SetSliceIndex(imageDims[i] // 2)
            self.viewer3D.planeWidgets[i].GetInteractor().Enable()
            self.viewer3D.planeWidgets[i].On()
            self.viewer3D.planeWidgets[i].InteractionOn()

        # Enable 2D viewers
        for i in range(self.stack.count()):
            self.stack.widget(i).viewer.GetRenderer().ResetCamera()
            self.stack.widget(i).viewer.GetInteractor().EnableRenderOn()

        # Enable interactors
        for i in range(self.stack.count()):
            self.stack.widget(i).interactor.Enable()
            self.stack.widget(i).viewer.GetInteractor().Enable()

        # Enable 3D rendering
        self.viewer3D.interactor.EnableRenderOn()
        # Reset camera for the renderer - otherwise it is set using dummy data
        self.viewer3D.planeWidgets[0].GetDefaultRenderer().ResetCamera()

        actor = self.stack.widget(0).viewer.GetImageActor()
        self.stack.widget(0).viewer.GetImageActor().InterpolateOff()
        #self.PropPicker.PickFromListOn()
        self.PropPicker.AddPickList(actor)

        # AddObserver(event, callback, priority)
        self.stack.widget(0).viewer.GetInteractor().AddObserver(
            'LeftButtonPressEvent', self.pickCallback, 100)

        # Update 3D
        self.ResetViews()
        self.SetResliceMode(1)
def MetaReader(ff):
    '''
    http://www.vtk.org/Wiki/VTK/Examples/Cxx/IO/MetaImageReader
    '''
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(ff)
    reader.Update()
    return reader.GetOutput()
Пример #28
0
 def ReadMetaImageFile(self):
     if (self.InputFileName == ''):
         self.PrintError('Error: no InputFileName.')
     self.PrintLog('Reading meta image file.')
     reader = vtk.vtkMetaImageReader()
     reader.SetFileName(self.InputFileName)
     reader.Update()
     self.Image = reader.GetOutput()
Пример #29
0
 def ReadMetaImageFile(self):
     if (self.InputFileName == ''):
         self.PrintError('Error: no InputFileName.')
     self.PrintLog('Reading meta image file.')
     reader = vtk.vtkMetaImageReader()
     reader.SetFileName(self.InputFileName)
     reader.Update()
     self.Image = reader.GetOutput()
Пример #30
0
    def GetImageDataForBaseAndExtension(self, fileName, extension):
        """
		:type fileName: basestring
		:type extension: basestring
		:rtype: vtkImageData
		"""
        if extension == DataReader.TypeMHA or extension == DataReader.TypeMHD:
            # Use a vktMetaImageReader
            imageReader = vtkMetaImageReader()
            imageReader.SetFileName(fileName)
            imageReader.Update()
            return imageReader.GetOutput()
        elif extension == DataReader.TypeDICOM:
            # Use a dicom reader
            dirName = os.path.dirname(fileName)
            return self.GetImageDataFromDirectory(dirName)
        elif extension == DataReader.TypeDAT:
            raise Exception("Support for .dat files is not implemented.")
            # Read in the .dat file byte by byte
            imageData = None

            import numpy as np
            with open(fileName, "rb") as f:
                dimensions = np.fromfile(f, np.int16, count=3)
                imageData = vtkImageData()
                imageData.SetDimensions(int(dimensions[0]), int(dimensions[1]),
                                        int(dimensions[2]))
                imageData.SetScalarTypeToFloat()
                imageData.SetNumberOfScalarComponents(1)
                imageData.AllocateScalars()
                imageData.Update()
                imageData.PrepareForNewData()

                fileData = np.fromfile(f, np.int16)

                dataIndex = 0
                for z in range(int(dimensions[2])):
                    for y in range(int(dimensions[1])):
                        for x in range(int(dimensions[0])):
                            imageData.SetScalarComponentFromFloat(
                                x, y, z, 0, float(fileData[dataIndex]))
                            dataIndex += 1

            return imageData
        elif extension == DataReader.TypeVTI:
            # Use a XMLImageReader
            imageReader = vtkXMLImageDataReader()
            imageReader.SetFileName(fileName)
            imageReader.Update()
            return imageReader.GetOutput()
        elif extension == DataReader.TypeNRRD:
            # Use a NrrdReader
            imageReader = vtkNrrdReader()
            imageReader.SetFileName(fileName)
            imageReader.Update()
            return imageReader.GetOutput()
        else:
            assert False
Пример #31
0
def setVtkWidget(vtkWidget):

    colors = vtk.vtkNamedColors()

    # Create the RenderWindow, Renderer and Interactor.
    #

    ren1 = vtk.vtkRenderer()
    vtkWidget.GetRenderWindow().AddRenderer(ren1)

    iren = vtkWidget.GetRenderWindow().GetInteractor()

    reader = vtk.vtkMetaImageReader()
    reader.SetFileName('FullHead.mha')
    reader.Update()

    locator = vtk.vtkMergePoints()
    locator.SetDivisions(396, 396, 24)
    locator.SetNumberOfPointsPerBucket(1)
    locator.AutomaticOff()

    iso = vtk.vtkMarchingCubes()
    iso.SetInputConnection(reader.GetOutputPort())
    iso.ComputeGradientsOn()
    iso.ComputeScalarsOff()
    iso.SetValue(0, 1)
    iso.SetLocator(locator)

    isoMapper = vtk.vtkPolyDataMapper()
    isoMapper.SetInputConnection(iso.GetOutputPort())
    isoMapper.ScalarVisibilityOff()

    isoActor = vtk.vtkActor()
    isoActor.SetMapper(isoMapper)
    isoActor.GetProperty().SetColor(colors.GetColor3d("Wheat"))

    outline = vtk.vtkOutlineFilter()
    outline.SetInputConnection(reader.GetOutputPort())

    outlineMapper = vtk.vtkPolyDataMapper()
    outlineMapper.SetInputConnection(outline.GetOutputPort())

    outlineActor = vtk.vtkActor()
    outlineActor.SetMapper(outlineMapper)

    # Add the actors to the renderer, set the background and size.
    #
    ren1.AddActor(outlineActor)
    ren1.AddActor(isoActor)
    ren1.SetBackground(colors.GetColor3d("Black"))
    ren1.GetActiveCamera().SetFocalPoint(0, 0, 0)
    ren1.GetActiveCamera().SetPosition(0, -1, 0)
    ren1.GetActiveCamera().SetViewUp(0, 0, -1)
    ren1.ResetCamera()
    ren1.GetActiveCamera().Dolly(1.5)
    ren1.ResetCameraClippingRange()

    iren.Initialize()
Пример #32
0
def load_volume(path):

    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(path)
    reader.Update()

    volume = reader.GetOutput()

    return volume
Пример #33
0
 def __init__(self, module_manager):
     SimpleVTKClassModuleBase.__init__(self,
                                       module_manager,
                                       vtk.vtkMetaImageReader(),
                                       'Reading vtkMetaImage.', (),
                                       ('vtkMetaImage', ),
                                       replaceDoc=True,
                                       inputFunctions=None,
                                       outputFunctions=None)
Пример #34
0
def showImage(inputFileName):
    imgData = None
    dataType = None

    renderer = vtk.vtkRenderer()

    if type(inputFileName) == str:
        fileName, fileExtension = os.path.splitext(inputFileName)
        fileExtension = fileExtension.lower()
        if fileExtension in ['.mha', '.mhd']:
            reader = vtk.vtkMetaImageReader()
            reader.SetFileName(inputFileName)
            reader.Update()
        elif fileExtension in ['.png']:
            reader = vtk.vtkPNGReader()
            reader.SetFileName(inputFileName)
            reader.Update()
        else:
            raise Exception("Unknown extension - update this program")
        imgData = reader.GetOutput()
        dataType = vtk.vtkImageData
    elif type(inputFileName) == vtk.vtkImageData:
        imgData = inputFileName
        dataType = vtk.vtkImageData
    elif type(inputFileName) == vtk.vtkPolyData:
        imgData = inputFileName
        dataType = vtk.vtkPolyData

    if dataType == vtk.vtkImageData:
        low, high = imgData.GetPointData().GetScalars().GetRange()
        print("low: %f, high: %f" % (low, high))
        print(imgData.GetDimensions())
        image = vtk.vtkImageActor()
        image.GetMapper().SetInputData(imgData)

        image.GetProperty().SetColorWindow(high - low)
        image.GetProperty().SetColorLevel(0.5 * (low + high))
        renderer.AddActor(image)
        style = vtk.vtkInteractorStyleImage()
    else:
        style = vtk.vtkInteractorStyleSwitch()
        surfActor = vtk.vtkActor()
        surfMapper = vtk.vtkPolyDataMapper()
        surfMapper.SetInputData(imgData)
        surfActor.SetMapper(surfMapper)
        renderer.AddActor(surfActor)

    window = vtk.vtkRenderWindow()
    window.AddRenderer(renderer)

    interactor = vtk.vtkRenderWindowInteractor()
    interactor.SetRenderWindow(window)

    interactor.SetInteractorStyle(style)

    #print(image.GetMapper().GetInput())
    interactor.Start()
Пример #35
0
def CreateSmoothFrogActor(fileName, tissue):
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(fileName)
    reader.Update()

    selectTissue = vtk.vtkImageThreshold()
    selectTissue.ThresholdBetween(tissue, tissue)
    selectTissue.SetInValue(255)
    selectTissue.SetOutValue(0)
    selectTissue.SetInputConnection(reader.GetOutputPort())

    gaussianRadius = 1
    gaussianStandardDeviation = 2.0
    gaussian = vtk.vtkImageGaussianSmooth()
    gaussian.SetStandardDeviations(gaussianStandardDeviation,
                                   gaussianStandardDeviation,
                                   gaussianStandardDeviation)
    gaussian.SetRadiusFactors(gaussianRadius, gaussianRadius, gaussianRadius)
    gaussian.SetInputConnection(selectTissue.GetOutputPort())

    isoValue = 127.5
    mcubes = vtk.vtkMarchingCubes()
    mcubes.SetInputConnection(gaussian.GetOutputPort())
    mcubes.ComputeScalarsOff()
    mcubes.ComputeGradientsOff()
    mcubes.ComputeNormalsOff()
    mcubes.SetValue(0, isoValue)

    smoothingIterations = 0
    passBand = 0.001
    featureAngle = 60.0
    smoother = vtk.vtkWindowedSincPolyDataFilter()
    smoother.SetInputConnection(mcubes.GetOutputPort())
    smoother.SetNumberOfIterations(smoothingIterations)
    smoother.BoundarySmoothingOff()
    smoother.FeatureEdgeSmoothingOff()
    smoother.SetFeatureAngle(featureAngle)
    smoother.SetPassBand(passBand)
    smoother.NonManifoldSmoothingOn()
    smoother.NormalizeCoordinatesOn()
    smoother.Update()

    normals = vtk.vtkPolyDataNormals()
    normals.SetInputConnection(smoother.GetOutputPort())
    normals.SetFeatureAngle(featureAngle)

    stripper = vtk.vtkStripper()
    stripper.SetInputConnection(normals.GetOutputPort())

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

    actor = vtk.vtkActor()
    actor.SetMapper(mapper)

    return actor
Пример #36
0
def read_and_transform_image(
        file_path: str) -> (vtk.vtkImageData, vtk.vtkTransform):
    """Reads an image as VTK image.

    VTK images have no direction matrix, therefore we apply a transformation to the image after loading to have in the
    correct space. Note that only meta and NIfTI images are supported.

    Args:
        file_path (str): The file path.

    Returns:
        (vtk.vtkImageData): The image.

    Raises:
        ValueError:
    """
    # check file extension to use correct reader
    extension = ''.join(pathlib.Path(file_path).suffixes)

    if extension == '.mha' or extension == '.mdh':
        reader = vtk.vtkMetaImageReader()
    elif extension == '.nii' or extension == '.nii.gz':
        reader = vtk.vtkNIFTIImageReader()
    else:
        raise ValueError('Unknown image format {}'.format(extension))

    reader.SetFileName(file_path)
    reader.Update()
    image = reader.GetOutput()

    # VTK images have no direction matrix, therefore load the same image with itk and apply a transformation
    image_sitk = sitk.ReadImage(file_path)
    direction = image_sitk.GetDirection()
    origin = image_sitk.GetOrigin()

    matrix = vtk.vtkMatrix4x4()
    matrix.Identity()
    matrix.SetElement(0, 0, direction[0])
    matrix.SetElement(0, 1, direction[3])
    matrix.SetElement(0, 2, direction[6])
    matrix.SetElement(1, 0, direction[1])
    matrix.SetElement(1, 1, direction[4])
    matrix.SetElement(1, 2, direction[7])
    matrix.SetElement(2, 0, direction[2])
    matrix.SetElement(2, 1, direction[5])
    matrix.SetElement(2, 2, direction[8])

    transform = vtk.vtkTransform()
    transform.Identity()
    # transform.Update()
    # transform.PostMultiply()
    # transform.Translate(-origin[0], -origin[1], -origin[2])
    transform.Translate(-origin[0], -origin[1], -origin[2])
    transform.Concatenate(matrix)

    return image, transform
	def GetImageDataForBaseAndExtension(self, fileName, extension):
		"""
		:type fileName: basestring
		:type extension: basestring
		:rtype: vtkImageData
		"""
		if extension == DataReader.TypeMHA or extension == DataReader.TypeMHD:
			# Use a vktMetaImageReader
			imageReader = vtkMetaImageReader()
			imageReader.SetFileName(fileName)
			imageReader.Update()
			return imageReader.GetOutput()
		elif extension == DataReader.TypeDICOM:
			# Use a dicom reader
			dirName = os.path.dirname(fileName)
			return self.GetImageDataFromDirectory(dirName)
		elif extension == DataReader.TypeDAT:
			raise Exception("Support for .dat files is not implemented.")
			# Read in the .dat file byte by byte
			imageData = None

			import numpy as np
			with open(fileName, "rb") as f:
				dimensions = np.fromfile(f, np.int16, count=3)
				imageData = vtkImageData()
				imageData.SetDimensions(int(dimensions[0]), int(dimensions[1]), int(dimensions[2]))
				imageData.SetScalarTypeToFloat()
				imageData.SetNumberOfScalarComponents(1)
				imageData.AllocateScalars()
				imageData.Update()
				imageData.PrepareForNewData()

				fileData = np.fromfile(f, np.int16)

				dataIndex = 0
				for z in range(int(dimensions[2])):
					for y in range(int(dimensions[1])):
						for x in range(int(dimensions[0])):
							imageData.SetScalarComponentFromFloat(x, y, z, 0, float(fileData[dataIndex]))
							dataIndex += 1

			return imageData
		elif extension == DataReader.TypeVTI:
			# Use a XMLImageReader
			imageReader = vtkXMLImageDataReader()
			imageReader.SetFileName(fileName)
			imageReader.Update()
			return imageReader.GetOutput()
		elif extension == DataReader.TypeNRRD:
			# Use a NrrdReader
			imageReader = vtkNrrdReader()
			imageReader.SetFileName(fileName)
			imageReader.Update()
			return imageReader.GetOutput()
		else:
			assert False
Пример #38
0
def return_matrix_image(image_name):
    imr = vtk.vtkMetaImageReader()
    imr.SetFileName(image_name)
    imr.Update()

    im = imr.GetOutput()
    sc = im.GetPointData().GetScalars()
    a = vtk_to_numpy(sc)
    print(a.shape)
    return a
Пример #39
0
  def loadFile(self, fileName):
    # Load VTK Meta Image
    reader = vtk.vtkMetaImageReader()
    reader.SetFileName(fileName)
    reader.Update()
    imageDims = reader.GetOutput().GetDimensions()

    # Disable renderers and widgets
    for i in range(3):
      self.vtk_widgets[i].viewer.GetInteractor().EnableRenderOff()
    if use3D:
      self.vtk_widgets[3].EnableRenderOff()
      # Turn-off plane widgets
      for i in range(3):
        self.planeWidget[i].Off()

    # Assign data to 2D viewers sharing one cursorobject
    for i in range(3):
      self.vtk_widgets[i].viewer.SetInputData(reader.GetOutput())

    if use3D:
      # Enable plane widgets
      for i in range(3):
        # Something missing when compared to c++ (no interactor is set)
        self.planeWidget[i].SetInteractor(self.vtk_widgets[3]) # was missing
        
        self.planeWidget[i].SetInputConnection(reader.GetOutputPort())
        self.planeWidget[i].SetPlaneOrientation(i)
        self.planeWidget[i].SetSliceIndex(imageDims[i] // 2)
        self.planeWidget[i].UpdatePlacement() # was missing
        self.planeWidget[i].GetInteractor().Enable()
        self.planeWidget[i].On()
        self.planeWidget[i].InteractionOn()

    # Enable 2D viewers
    for i in range(3):
      self.vtk_widgets[i].viewer.GetRenderer().ResetCamera()
      self.vtk_widgets[i].viewer.GetInteractor().EnableRenderOn()

    # Enable interactors
    for i in range(3):
      self.vtk_widgets[i].interactor.Enable()

    if use3D:
      # Enable 3D rendering
      self.vtk_widgets[3].EnableRenderOn()
      # Reset camera for the renderer - otherwise it is set using dummy data
      self.planeWidget[0].GetDefaultRenderer().ResetCamera()

      # Could we requist interactor for 3D image??

    # Update 3D
    self.ResetViews()
    self.SetResliceMode(1)
Пример #40
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()
Пример #41
0
def mhd2npy(fn):
    # back the other way:
    r = vtk.vtkMetaImageReader()
    r.SetFileName(fn)
    r.Update()
    image = r.GetOutput()
    vtk_data = image.GetPointData().GetScalars()
    numpy_data = ns.vtk_to_numpy(vtk_data)
    dims = image.GetDimensions()
    numpy_data = numpy_data.reshape(dims[2], dims[1], dims[0])
    numpy_data = numpy_data.transpose(2, 1, 0)
    return numpy_data
Пример #42
0
def write_3slices(fn_mha="t.mha", pnt=(159, 233, 90), wxyz=(0.0, 0.0, 0.0, 1.0), sz=16, fnbase_out="out"):
    """ write the 3 perpendicular slices with half of the size sz at point pnt"""
    rd = vtk.vtkMetaImageReader()
    rd.SetFileName(fn_mha)
    rd.Update()
    img = rd.GetOutput()

    xy, yz, xz = gen_3slices(img, pnt, wxyz, sz)

    write_slice(xy, fnbase_out+"_xy.mha")
    write_slice(yz, fnbase_out+"_yz.mha")
    write_slice(xz, fnbase_out+"_xz.mha")
Пример #43
0
def mhd2npy(fn):
    # back the other way:
    r = vtk.vtkMetaImageReader()
    r.SetFileName(fn)
    r.Update()
    image = r.GetOutput()
    vtk_data = image.GetPointData().GetScalars()
    numpy_data = ns.vtk_to_numpy(vtk_data)
    dims = image.GetDimensions()
    numpy_data = numpy_data.reshape(dims[2], dims[1], dims[0])
    numpy_data = numpy_data.transpose(2, 1, 0)
    return numpy_data
Пример #44
0
def extract_contour(segmentation_path, contour_path, rgb_data=False):
    # build pipeline
    sys.stdout.write('Updating segmentation...'); sys.stdout.flush()
    segmentation = vtk.vtkMetaImageReader()
    segmentation.SetFileName(segmentation_path)
    segmentation.Update()
    print 'done.'
    
    if rgb_data:
        calculator_function = "mag(MetaImage)"
    else:
        calculator_function = "MetaImage * 255"
    
    sys.stdout.write('Updating calculator...'); sys.stdout.flush()
    calculator = vtk.vtkArrayCalculator()
    calculator.SetInputConnection(segmentation.GetOutputPort())
    # Working on point data
    calculator.SetAttributeModeToUsePointData()
    calculator.AddScalarArrayName("MetaImage")
    # magnitude of input
    calculator.SetFunction("mag(MetaImage)")
    # The output array will be called resArray
    calculator.SetResultArrayName("magnitude")
    
    # Use AssignAttribute to make resArray the active scalar field
    aa = vtk.vtkAssignAttribute()
    aa.SetInputConnection(calculator.GetOutputPort())
    aa.Assign("magnitude", "SCALARS", "POINT_DATA")
    aa.Update()
    print 'done.'
    
    # intensity is either (3 * 255^2)^0.5, or 1
    if rgb_data:
        magnitude = 420.0
    else:
        magnitude = 127
    
    sys.stdout.write('Updating contour...'); sys.stdout.flush()
    contour = vtk.vtkContourFilter()
    contour.SetInputConnection(calculator.GetOutputPort())
    contour.SetValue(0, magnitude)
    contour.Update()
    print 'done.'
    
    # write out data file in given format
    sys.stdout.write('Updating writer...'); sys.stdout.flush()
    writer = vtk.vtkXMLPolyDataWriter()
    writer.SetFileName(contour_path)
    writer.SetCompressorTypeToZLib()
    writer.SetInputConnection(contour.GetOutputPort())
    writer.Write()
    print 'done.'
Пример #45
0
    def load_mask_from_file(self, file_path):
        """Loads mask file
        """
        self._view_frame.SetStatusText( "Opening mask: %s..." % (file_path))        
        filename = os.path.split(file_path)[1]
        fileBaseName =os.path.splitext(filename)[0]

        reader = vtk.vtkMetaImageReader()
        reader.SetFileName(file_path)
        reader.Update()
        self.mask_data = reader.GetOutput()
        if (self.image_data) is not None:
	        self.create_volumerender(0,0)
        else:
	        self._view_frame.SetStatusText("Opened mask file")
def generate_mesh(imgbinitk):
    sitk.WriteImage( imgbinitk,'label_cleaned_tmp.mha')
    
    reader=vtk.vtkMetaImageReader()
    reader.SetFileName('label_cleaned_tmp.mha')
    reader.Update()
    
    imgbin=reader.GetOutput()
    dmc = vtk.vtkDiscreteMarchingCubes()
    dmc.SetInputData(imgbin)
    dmc.ComputeNormalsOn()
    dmc.GenerateValues(1, 1, 1)
    dmc.Update()
    meshout=dmc.GetOutput()
    #DisplayVTKMesh(meshout,"mesh from marchin cubes")
    return meshout
Пример #47
0
def write_3slices(fn_mha="t.mha",
                  a=(-30, 25, 45), cen=(82, 93, 104), sz=10,
                  fnbase_out="out"):
    """ write the 3 slices using angle, center, half-size  """
    rd = vtk.vtkMetaImageReader()
    rd.SetFileName(fn_mha)
    rd.Update()
    img = rd.GetOutput()

    if a is None:
        xy, yz, xz = gen_3ps(img, cen, sz)
    else:
        xy, yz, xz = gen_3s(img, a, cen, sz)

    write_slice(xy, fnbase_out + "_1.mha")
    write_slice(yz, fnbase_out + "_2.mha")
    write_slice(xz, fnbase_out + "_3.mha")
Пример #48
0
def dataSize(filename, **args):
    """Read data size from raw/mhd image
    
    Arguments:
        filename (str):  imaris file name
        x,y,z (tuple or all): range specifications
    
    Returns:
        int: raw image data size
    """  
    
    imr = vtk.vtkMetaImageReader()
    imr.SetFileName(filename);
    imr.Update()

    im = imr.GetOutput()
    dims = im.GetDimensions();
    #dims = list(dims);
    #dims[0:2] = [dims[1], dims[0]];
    #dims = tuple(dims);
    return io.dataSizeFromDataRange(dims, **args);
Пример #49
0
def dataZSize(filename, z = all, **args):
    """Read z data size from raw/mhd image
        
    Arguments:
        filename (str):  imaris file name
        z (tuple or all): range specification
    
    Returns:
        int: raw image z data size
    """  
    
    imr = vtk.vtkMetaImageReader()
    imr.SetFileName(filename);
    imr.Update()

    im = imr.GetOutput()
    dims = im.GetDimensions()
    
    if len(dims) > 2:
        return io.toDataSize(dims[2], r = z);
    else:
        return None;
Пример #50
0
def readData(filename, x = all, y = all, z = all):
    """Read data from raw/mhd image
    
    Arguments:
        filename (str): file name as regular expression
        x,y,z (tuple): data range specifications
    
    Returns:
        array: image data
    """   
    
    imr = vtk.vtkMetaImageReader()
    imr.SetFileName(filename);
    imr.Update()
    
    im = imr.GetOutput()
    dims = im.GetDimensions()
    
    print dims    
    
    sc = im.GetPointData().GetScalars()
    img = vtk_to_numpy(sc)
    #print img.shape
    
    dims = list(dims);
    dims[0:3] = [dims[2], dims[1], dims[0]];
    
    imgs = list(img.shape);
    if len(imgs) > 1:
        imgs.pop(0);
        dims = dims + imgs;
    
    img = img.reshape(dims)
    #img = img.transpose([1,2,0]);
    tp = [2,1,0];
    tp = tp + [i for i in range(3, len(dims))];
    img = img.transpose(tp);
    
    return io.dataToRange(img, x = x, y = y, z = z);
Пример #51
0
import vtk

meta_image_filename = 'labels.mhd'

# Prepare to read the file

reader_volume = vtk.vtkMetaImageReader()
reader_volume.SetFileName(meta_image_filename)
reader_volume.Update()


# Extract the region of interest
voi = vtk.vtkExtractVOI()
if vtk.VTK_MAJOR_VERSION <= 5:
    voi.SetInput(reader_volume.GetOutput())
else:
    voi.SetInputConnection(reader_volume.GetOutputPort())

#voi.SetVOI(0,517, 0,228, 0,392)
voi.SetSampleRate(1, 1, 1)
#voi.SetSampleRate(3, 3, 3)
voi.Update() # necessary for GetScalarRange()
srange = voi.GetOutput().GetScalarRange() # needs Update() before!
print("Range", srange)


##Prepare surface generation
#contour = vtk.vtkContourFilter()
#contour = vtk.vtkMarchingCubes()
contour = vtk.vtkDiscreteMarchingCubes() #for label images
if vtk.VTK_MAJOR_VERSION <= 5:
Пример #52
0
def main(argv):
	if len(argv) < 3:
		sys.stderr.write("Usage: %s <volume.mhd> <trace.vtk>\n" % argv[0])
		return 1

	segmented_volume_filename, trace_filename = argv[1:3]

	for filename in [ segmented_volume_filename, trace_filename ]:
		if not os.path.exists(filename):
			sys.stderr.write("file '%s' not found\n" % filename)
			return 1

	ren = vtk.vtkRenderer()
	renWin = vtk.vtkRenderWindow()
	renWin.AddRenderer(ren)
	renWin.SetSize(WIDTH, HEIGHT)

	# create a renderwindowinteractor
	iren = vtk.vtkRenderWindowInteractor()
	iren.SetRenderWindow(renWin)

	antique_white = [ 0.9804, 0.9216, 0.8431 ]
	line_width = 5

	centerline = vtk.vtkPolyDataReader()
	for centerline in [centerline]:
		for r in [centerline]:
			r.SetFileName( trace_filename )
			r.ReadAllVectorsOn()
			r.ReadAllScalarsOn()
			r.Update()
			centerline_mapper = vtk.vtkPolyDataMapper()
			for m in [centerline_mapper]:
				m.SetInput( centerline.GetOutput() )
			centreline_actor = vtk.vtkActor()
			for a in [centreline_actor]:
				a.SetMapper( centerline_mapper )
				a.GetProperty().SetColor( *antique_white )
				a.GetProperty().SetLineWidth( line_width );

	# Create transfer mapping scalar value to opacity
	opacity_transfer_function = vtk.vtkPiecewiseFunction()
	for tf in [opacity_transfer_function]:
		tf.AddPoint( 20 , 0.0)
		tf.AddPoint( 255 , 0.2)
	# Create transfer mapping scalar value to color
	color_transfer_function = vtk.vtkColorTransferFunction()
	for tf in [color_transfer_function]:
		tf.AddRGBPoint(0.0, 0.0, 0.0, 0.0)
		tf.AddRGBPoint(64.0, 0.2, 0.0, 0.0)
		tf.AddRGBPoint(128.0, 0.0, 0.0, 1.0)
		tf.AddRGBPoint( 192.0, 0.0, 1.0, 0.0)
		tf.AddRGBPoint( 255.0, 0.0, 0.2, 0.0)
		tf.SetColorSpaceToDiverging()
	# The property describes how the data will look
	volume_property = vtk.vtkVolumeProperty()
	for vp in [volume_property]:
		vp.SetColor(color_transfer_function)
		vp.SetScalarOpacity(opacity_transfer_function)

	segmentation = vtk.vtkMetaImageReader()
	for segmentation in [segmentation]:
		for r in [segmentation]:
			r.SetFileName( segmented_volume_filename )
			r.Update()

		segmentation_outline_filter = vtk.vtkOutlineFilter()
		for f in [segmentation_outline_filter]:
			f.SetInput( segmentation.GetOutput() )
		segmentation_outline_mapper = vtk.vtkPolyDataMapper()
		for m in [segmentation_outline_mapper]:
			m.SetInputConnection( segmentation_outline_filter.GetOutputPort() )
		segmentation_outline_actor = vtk.vtkActor()
		for a in [segmentation_outline_actor]:
			a.SetMapper( segmentation_outline_mapper )

		segmentation_mapper = vtk.vtkSmartVolumeMapper()
		for m in [segmentation_mapper]:
			m.SetInput( segmentation.GetOutput() )
		segmentation_actor = vtk.vtkVolume()
		for a in [segmentation_actor]:
			a.SetMapper( segmentation_mapper )
			a.SetProperty( volume_property )




		for actor in [ centreline_actor, segmentation_actor, segmentation_outline_actor]:
			ren.AddActor( actor )

	iren.Initialize()
	renWin.Render()

	iren.Start()
Пример #53
0
#!/Users/seb/Work/code/ParaView/build/bin/pvpython

import sys
from vtk import vtkMetaImageReader, vtkProgrammableFilter, vtkUnsignedCharArray, vtkJPEGWriter, vtkPNGWriter

basePath = '/Users/seb/Work/projects/NE-Phase2/'

reader = vtkMetaImageReader()
reader.SetFileName("/Users/seb/Work/projects/NE-Phase2/Patient05.mha")
reader.Update()

writer = vtkJPEGWriter() # vtkJPEGWriter()

filter = vtkProgrammableFilter()

def unfoldData():
   inputDS = filter.GetInputDataObject(0, 0)
   outputDS = filter.GetImageDataOutput()

   dims = inputDS.GetDimensions()

   # dims[1] * dims[2]
   nbSlices = (dims[1] * dims[2]) / 2048
   outputDS.SetDimensions(dims[0], dims[1] * dims[2] / nbSlices, nbSlices)
   outputDS.SetOrigin(0,0,0)
   outputDS.SetSpacing(1,1,1)

   for arrayIdx in range(inputDS.GetPointData().GetNumberOfArrays()):
      array = inputDS.GetPointData().GetArray(arrayIdx)

      size = dims[0] * dims[1] * dims[2]
Пример #54
0
import numpy as np
import vtk
from vtk.util.numpy_support import vtk_to_numpy

imr = vtk.vtkMetaImageReader()
imr.SetFileName('t10-Subvolume-resample_scale-1.mhd')
imr.Update()

im = imr.GetOutput()
rows, cols, _ = im.GetDimensions()
sc = im.GetPointData().GetScalars()
a = vtk_to_numpy(sc)
a = a.reshape(rows, cols, -1)

assert a.shape==im.GetDimensions()
Пример #55
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()
      
      # 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.vtkMetaImageReader()
      self.reader.SetFileName('')
      self.reader2.SetFileName('')
      
      # 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.fileLoadDefaults = QAction("&Load Defaults",self)
      self.fileLoadDefaults.setToolTip("Loads default values for range/threshold/etc")
      self.fileLoadDefaults.setStatusTip("Loads default values for range/threshold/etc")
  
      self.connect(self.fileOpenAction, SIGNAL("triggered()"),self.fileOpen)
      self.connect(self.fileOpenAction2, SIGNAL("triggered()"),self.fileOpen2)
      self.connect(self.fileLoadDefaults, SIGNAL("triggered()"),self.fileLoad)
      
      self.fileMenu = self.menuBar().addMenu("&File")
      self.fileMenu.addAction(self.fileOpenAction)   
      self.fileMenu.addAction(self.fileOpenAction2)
      self.fileMenu.addAction(self.fileLoadDefaults)
      
      # property label
      self.label_property = QLabel("Property: ")
      
      # property dropdown
      self.dropdown_property = QComboBox()
      
      # toolbar
      self.viewToolbar = self.addToolBar("View")
      self.viewToolbar.setObjectName("ViewToolbar")
      self.viewToolbar.addWidget(self.label_property)
      self.viewToolbar.addWidget(self.dropdown_property)
      
      self.connect(self.dropdown_property, SIGNAL("currentIndexChanged(int)"), self.SetProperty)
Пример #56
0
renWin.AddRenderer(Ren1)
renWin.SetSize(300,300)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
reader = vtk.vtkImageReader()
reader.SetDataByteOrderToLittleEndian()
reader.SetDataExtent(0,63,0,63,1,93)
reader.SetDataSpacing(3.2,3.2,1.5)
reader.SetFilePrefix("" + str(VTK_DATA_ROOT) + "/Data/headsq/quarter")
reader.SetDataMask(0x7fff)
reader.Update()
pvTemp200 = vtk.vtkMetaImageWriter()
pvTemp200.SetFileName("mhdWriter.mhd")
pvTemp200.SetInputData(reader.GetOutput())
pvTemp200.Write()
pvTemp90 = vtk.vtkMetaImageReader()
pvTemp90.SetFileName("mhdWriter.mhd")
pvTemp90.Update()
pvTemp109 = vtk.vtkLookupTable()
pvTemp109.SetNumberOfTableValues(256)
pvTemp109.SetHueRange(0.6667,0)
pvTemp109.SetSaturationRange(1,1)
pvTemp109.SetValueRange(1,1)
pvTemp109.SetTableRange(37.3531,260)
pvTemp109.SetVectorComponent(0)
pvTemp109.Build()
pvTemp110 = vtk.vtkContourFilter()
pvTemp110.SetInputData(pvTemp90.GetOutput(0))
pvTemp110.SetValue(0,1150)
pvTemp110.SetComputeNormals(1)
pvTemp110.SetComputeGradients(0)
import sys

import vtk

usage = sys.argv[0] + '  <original_image> <gradient_magnitude_image> <output_image>.png'

if len( sys.argv ) < 4:
    print( usage )
    sys.exit( 1 )

camera = vtk.vtkCamera()
camera.SetViewUp     (0.0, 1.0, 0.0)
camera.SetFocalPoint (127.5, 127.5, 0.0)
camera.SetPosition   (127.5, 127.5, 494.77095648274013)

original_reader = vtk.vtkMetaImageReader()
original_reader.SetFileName( sys.argv[1] )
original_reader.Update()

original_actor = vtk.vtkImageActor()
original_actor.SetInput( original_reader.GetOutput() )

original_ren = vtk.vtkRenderer()
original_ren.AddActor( original_actor )
original_ren.SetViewport( 0.0, 0.0, 0.5, 1.0 )
original_ren.SetActiveCamera( camera )
original_ren.SetBackground( 1.0, 1.0, 1.0 )

gradient_reader = vtk.vtkMetaImageReader()
gradient_reader.SetFileName( sys.argv[2] )
gradient_reader.Update()
Пример #58
0
dirs['train'] = output_dir+'train/'
dirs['val'] = output_dir+'val/'
dirs['test'] = output_dir+'test/'

split_models = {}
split_models['train'] = open('./data/jameson_train.txt').readlines()
split_models['val'] = open('./data/jameson_val.txt').readlines()
split_models['test'] = open('./data/jameson_test.txt').readlines()
for k in split_models.keys():
    split_models[k] = [s.replace('\n','') for s in split_models[k]]
models = split_models['train'] + split_models['val'] + split_models['test']

#############################
# Start processing data
#############################
reader = vtk.vtkMetaImageReader()
reader2 = vtk.vtkMetaImageReader()

mhas = open(output_dir+'images.txt').readlines()
mhas = [i.replace('\n','') for i in mhas]

truths = open(output_dir+'truths.txt').readlines()
truths = [i.replace('\n','') for i in truths]

paths = open(output_dir+'paths.txt').readlines()
paths = [i.replace('\n','') for i in paths]

#for i in range(len(mahs)):
images = []
contours3D = []
names = []