Esempio n. 1
0
def attribute_dict(i, name):
    """Returns a dict with the attribute values in keys and a list of the
    corresponding objects in value

    i: the input LabelImage
    name: the name of the attribute
    """
    import itk

    i = itk.output(i)
    relabel = itk.StatisticsRelabelLabelMapFilter[i].New(i,
                                                         Attribute=name,
                                                         ReverseOrdering=True,
                                                         InPlace=False)
    relabel.UpdateLargestPossibleRegion()
    r = relabel.GetOutput()
    d = {}
    # required because range is overloaded in this module
    from builtins import range

    for i in range(1, r.GetNumberOfLabelObjects() + 1):
        lo = r.GetLabelObject(i)
        v = lo.__getattribute__("Get" + name)()
        l_list = d.get(v, [])
        l_list.append(lo)
        d[v] = l_list
    return d
Esempio n. 2
0
 def Show(self, itkIm, title="noname") :
     """ Display an image, with optional title
     If different titles are used then multiple images will be available in imview.
     Flip between them with the menu or space bar
     """
     import itk
     #itkIm = itk.image(itkIm)
     itkIm = itk.output(itkIm)
     if not self.connected :
         # do the login now that we have an image type
         self.imviewObj = itk.Imview[itkIm]
         self.Connection = self.imviewObj.ImviewLogin(self.portNum)
         self.connected = True
         print "Connected"
         print self.Connection
         self.ImageTemp = itk.template(itkIm)[1]
     else:
         if itk.template(itkIm)[1] != self.ImageTemp:
             self.ImageTemp = itk.template(itkIm)[1] 
             self.imviewObj = itk.Imview[itkIm]
     # transmit the image
     status = self.imviewObj.ImviewPutImage(itkIm, self.Connection, title)
     if (status != 0):
         # Failed to send image. Assume that imview has died
         self.__StartImview__()
         status = self.imviewObj.ImviewPutImage(itkIm, self.Connection, title)
         if (status != 0):
             print "Something seriously wrong - give up on this Imview instance"
Esempio n. 3
0
def attributes_list(i, names):
    """Returns a list of the specified attributes for the objects in the image.

    i: the input LabelImage
    name: the attribute name
    """
    import itk

    i = itk.output(i)
    relabel = itk.StatisticsRelabelLabelMapFilter[i].New(i,
                                                         Attribute=names[0],
                                                         ReverseOrdering=True,
                                                         InPlace=False)
    relabel.UpdateLargestPossibleRegion()
    r = relabel.GetOutput()
    l_list = []
    # required because range is overloaded in this module
    from builtins import range

    for i in range(1, r.GetNumberOfLabelObjects() + 1):
        attrs = []
        for name in names:
            attrs.append(r.GetLabelObject(i).__getattribute__("Get" + name)())
        l_list.append(tuple(attrs))
    return l_list
Esempio n. 4
0
def view(image):
    have_imglyb = False
    try:
        import imglyb
        have_imglyb = True
    except ImportError:
        pass
    have_vtk = False
    try:
        import vtk
        have_vtk = True
    except ImportError:
        pass
    viewer = Viewer()
    if is_arraylike(image):
        arr = np.asarray(image)
        image_from_array = itk.GetImageViewFromArray(arr)
        viewer.image = image_from_array
    elif have_vtk and isinstance(image, vtk.vtkImageData):
        from vtk.util import numpy_support as vtk_numpy_support
        array = vtk_numpy_support.vtk_to_numpy(image.GetPointData().GetScalars())
        array.shape = tuple(image.GetDimensions())[::-1]
        image_from_array = itk.GetImageViewFromArray(array)
        image_from_array.SetSpacing(image.GetSpacing())
        image_from_array.SetOrigin(image.GetOrigin())
        viewer.image = image_from_array
    elif have_imglyb and isinstance(image,
            imglyb.util.ReferenceGuardingRandomAccessibleInterval):
        image_array = imglyb.to_numpy(image)
        image_from_array = itk.GetImageViewFromArray(image_array)

    else:
        # an itk.Image
        viewer.image = itk.output(image)
    return viewer
Esempio n. 5
0
def number_of_objects(i):
    """Returns the number of objets in the image.

    i: the input LabelImage
    """
    import itk
    i.UpdateLargestPossibleRegion()
    i = itk.output(i)
    return i.GetNumberOfLabelObjects()
Esempio n. 6
0
 def Overlay(self, itkIm, title="noname") :
     """Send an overlay to image with specified title"""
     import itk
     #itkIm = itk.image(itkIm)
     itkIm = itk.output(itkIm)
     if not self.connected :
         print "No image being viewed - send one first"
     else:
         if itk.template(itkIm)[1] != self.ImageTemp:
             self.ImageTemp = itk.template(itkIm)[1] 
             self.imviewObj = itk.Imview[itkIm]
         status = self.imviewObj.ImviewPutOverlay(itkIm, self.Connection, title)
def to_itk_image(image_like):

    if isinstance(image_like, itk.Image):
        return image_like

    if is_arraylike(image_like):
        array = np.asarray(image_like)
        can_use_view = array.flags['OWNDATA']
        if have_dask and isinstance(image_like, dask.array.core.Array):
            can_use_view = False
        array = np.ascontiguousarray(array)
        # JavaScript does not support 64-bit integers
        if array.dtype == np.int64:
            array = array.astype(np.float32)
        elif array.dtype == np.uint64:
            array = array.astype(np.float32)
        if can_use_view:
            image_from_array = itk.image_view_from_array(array)
        else:
            image_from_array = itk.image_from_array(array)
        return image_from_array
    elif have_vtk and isinstance(image_like, vtk.vtkImageData):
        from vtk.util import numpy_support as vtk_numpy_support
        array = vtk_numpy_support.vtk_to_numpy(
            image_like.GetPointData().GetScalars())
        array.shape = tuple(image_like.GetDimensions())[::-1]
        image_from_array = itk.image_view_from_array(array)
        image_from_array.SetSpacing(image_like.GetSpacing())
        image_from_array.SetOrigin(image_like.GetOrigin())
        return image_from_array
    elif have_simpleitk and isinstance(image_like, sitk.Image):
        array = sitk.GetArrayViewFromImage(image_like)
        image_from_array = itk.image_view_from_array(array)
        image_from_array.SetSpacing(image_like.GetSpacing())
        image_from_array.SetOrigin(image_like.GetOrigin())
        direction = image_like.GetDirection()
        npdirection = np.asarray(direction)
        npdirection = np.reshape(npdirection, (-1, 3))
        itkdirection = itk.matrix_from_array(npdirection)
        image_from_array.SetDirection(itkdirection)
        return image_from_array
    elif have_imagej:
        import imglyb
        if isinstance(image_like,
                      imglyb.util.ReferenceGuardingRandomAccessibleInterval):
            array = imglyb.to_numpy(image_like)
            image_from_array = itk.image_view_from_array(array)
            return image_from_array
    elif isinstance(image_like, itk.ProcessObject):
        return itk.output(image_like)

    return None
Esempio n. 8
0
    def SetInput(self, input):
        import itk
        img = itk.output(input)
        self.__input__ = img
        if img:
            # Update to try to avoid to exit if a c++ exception is throwed
            # sadely, it will not prevent the program to exit later...
            # a real fix would be to wrap c++ exception in vtk
            img.UpdateOutputInformation()
            img.Update()

            # flip the image to get the same representation than the vtk one
            self.__flipper__ = itk.FlipImageFilter[img].New(Input=img)
            axes = self.__flipper__.GetFlipAxes()
            axes.SetElement(1, True)
            self.__flipper__.SetFlipAxes(axes)

            # change the spacing while still keeping the ratio to workaround vtk bug
            # when spacing is very small
            spacing_ = itk.spacing(img)
            normSpacing = []
            for i in range(0, spacing_.Size()):
                normSpacing.append(
                    spacing_.GetElement(i) / spacing_.GetElement(0))
            self.__changeInfo__ = itk.ChangeInformationImageFilter[img].New(
                self.__flipper__,
                OutputSpacing=normSpacing,
                ChangeSpacing=True)

            # now really convert the data
            self.__itkvtkConverter__ = itk.ImageToVTKImageFilter[img].New(
                self.__changeInfo__)
            self.__volumeMapper__.SetInput(
                self.__itkvtkConverter__.GetOutput())
            # needed to avoid warnings
            # self.__itkvtkConverter__.GetOutput() must be callable

            import vtk
            if not self.__outline__:
                self.__outline__ = vtk.vtkOutlineFilter()
                self.__outline__.SetInput(self.__itkvtkConverter__.GetOutput())
                self.__outlineMapper__ = vtk.vtkPolyDataMapper()
                self.__outlineMapper__.SetInput(self.__outline__.GetOutput())
                self.__outlineActor__ = vtk.vtkActor()
                self.__outlineActor__.SetMapper(self.__outlineMapper__)
                self.__ren__.AddActor(self.__outlineActor__)
            else:
                self.__outline__.SetInput(self.__itkvtkConverter__.GetOutput())

        self.Render()
Esempio n. 9
0
def attribute_list( i, name ):
  """Returns a list of the specified attributes for the objects in the image.

  i: the input LabelImage
  name: the attribute name
  """
  import itk
  i = itk.output(i)
  relabel = itk.StatisticsRelabelLabelMapFilter[i].New(i, Attribute=name, ReverseOrdering=True, InPlace=False)
  relabel.UpdateLargestPossibleRegion()
  r = relabel.GetOutput()
  l = []
  for i in range(1, r.GetNumberOfLabelObjects()+1):
    l.append( r.GetLabelObject(i).__getattribute__("Get"+name)() )
  return l
Esempio n. 10
0
  def SetInput(self, input) :
    import itk
    img = itk.output(input)
    self.__input__ = img
    if img :
      # Update to try to avoid to exit if a c++ exception is throwed
      # sadely, it will not prevent the program to exit later...
      # a real fix would be to wrap c++ exception in vtk
      img.UpdateOutputInformation()
      img.Update()
      
      # flip the image to get the same representation than the vtk one
      self.__flipper__ = itk.FlipImageFilter[img].New(Input=img)
      axes = self.__flipper__.GetFlipAxes()
      axes.SetElement(1, True)
      self.__flipper__.SetFlipAxes(axes)
      
      # change the spacing while still keeping the ratio to workaround vtk bug
      # when spacing is very small
      spacing_ = itk.spacing(img)
      normSpacing = []
      for i in range(0, spacing_.Size()):
        normSpacing.append( spacing_.GetElement(i) / spacing_.GetElement(0) )
      self.__changeInfo__ = itk.ChangeInformationImageFilter[img].New(self.__flipper__, OutputSpacing=normSpacing, ChangeSpacing=True)
      
      # now really convert the data
      self.__itkvtkConverter__ = itk.ImageToVTKImageFilter[img].New(self.__changeInfo__)
      self.__volumeMapper__.SetInput(self.__itkvtkConverter__.GetOutput())
      # needed to avoid warnings
      # self.__itkvtkConverter__.GetOutput() must be callable
      
      import vtk
      if not self.__outline__ :
	  self.__outline__ = vtk.vtkOutlineFilter()
	  self.__outline__.SetInput(self.__itkvtkConverter__.GetOutput())
	  self.__outlineMapper__ = vtk.vtkPolyDataMapper()
	  self.__outlineMapper__.SetInput(self.__outline__.GetOutput())
	  self.__outlineActor__ = vtk.vtkActor()
	  self.__outlineActor__.SetMapper(self.__outlineMapper__)
	  self.__ren__.AddActor(self.__outlineActor__)
      else :
	  self.__outline__.SetInput(self.__itkvtkConverter__.GetOutput())

    self.Render()
Esempio n. 11
0
def attribute_dict( i, name ):
  """Returns a dict with the attribute values in keys and a list of the corresponding objects in value

  i: the input LabelImage
  name: the name of the attribute
  """
  import itk
  i = itk.output(i)
  relabel = itk.StatisticsRelabelLabelMapFilter[i].New(i, Attribute=name, ReverseOrdering=True, InPlace=False)
  relabel.UpdateLargestPossibleRegion()
  r = relabel.GetOutput()
  d = {}
  for i in range(1, r.GetNumberOfLabelObjects()+1):
    lo = r.GetLabelObject(i)
    v = lo.__getattribute__("Get"+name)()
    l = d.get( v, [] )
    l.append( lo )
    d[v] = l
  return d
Esempio n. 12
0
    def validate(self, obj, value):
        self._source_object = value

        image_from_array = to_itk_image(value)
        if image_from_array:
            return image_from_array

        try:
            # an itk.Image or a filter that produces an Image
            # return itk.output(value)
            # Working around traitlets / ipywidgets update mechanism to
            # force an update. While the result of __eq__ can indicate it is
            # the same object, the actual contents may have changed, as
            # indicated by image.GetMTime()
            value = itk.output(value)
            grafted = value.__New_orig__()
            grafted.Graft(value)
            return grafted
        except:
            self.error(obj, value)
Esempio n. 13
0
    def validate(self, obj, value):
        if is_arraylike(value):
            array = np.asarray(value)
            self._source_object = array
            if array.flags['OWNDATA']:
                image_from_array = itk.GetImageViewFromArray(array)
            else:
                image_from_array = itk.GetImageFromArray(array)
            return image_from_array
        elif have_vtk and isinstance(value, vtk.vtkImageData):
            from vtk.util import numpy_support as vtk_numpy_support
            array = vtk_numpy_support.vtk_to_numpy(
                value.GetPointData().GetScalars())
            array.shape = tuple(value.GetDimensions())[::-1]
            self._source_object = array
            image_from_array = itk.GetImageViewFromArray(array)
            image_from_array.SetSpacing(value.GetSpacing())
            image_from_array.SetOrigin(value.GetOrigin())
            return image_from_array
        elif have_imglyb and isinstance(
                value, imglyb.util.ReferenceGuardingRandomAccessibleInterval):
            array = imglyb.to_numpy(value)
            self._source_object = array
            image_from_array = itk.GetImageViewFromArray(array)
            return image_from_array

        try:
            # an itk.Image or a filter that produces an Image
            # return itk.output(value)
            # Working around traitlets / ipywidgets update mechanism to
            # force an update. While the result of __eq__ can indicate it is
            # the same object, the actual contents may have changed, as
            # indicated by image.GetMTime()
            value = itk.output(value)
            self._source_object = value
            grafted = value.__New_orig__()
            grafted.Graft(value)
            return grafted
        except:
            self.error(obj, value)
Esempio n. 14
0
def computeRegion(lo, img):
   img = itk.output(img)
   import math
   transform = lo.GetBinaryPrincipalAxesToPhysicalAxesTransform()
   invTransform = itk.AffineTransform.D3.New()
   transform.GetInverse( invTransform )
   region = lo.GetRegion()
   outputSpacing = [min(itk.spacing(img))]*3
   dummyImg = itk.Image.UC3.New()
   dummyImg.SetSpacing( outputSpacing )
   idx = region.GetIndex()
   size = region.GetSize()
   minPoint = [4294967295L]*3
   maxPoint = [-4294967295L]*3
   for x in [idx[0], idx[0]+size[0]]:
       for y in [idx[1], idx[1]+size[1]]:
           for z in [idx[2], idx[2]+size[2]]:
               inputPoint = img.TransformIndexToPhysicalPoint( [x,y,z] )
               outputPoint = invTransform.TransformPoint( inputPoint )
               for i in range(0,3):
                   if minPoint[i] > outputPoint[i]:
                       minPoint[i] = outputPoint[i]
                   if maxPoint[i] < outputPoint[i]:
                       maxPoint[i] = outputPoint[i]
   minIdx = dummyImg.TransformPhysicalPointToIndex(minPoint)
   maxIdx = dummyImg.TransformPhysicalPointToIndex(maxPoint)
   outputIdx = []
   outputSize = []
   for i in range(0,3):
       outputIdx.append(int(minIdx[i]))
       outputSize.append( int(maxIdx[i] - minIdx[i]) )
   uabc3 = 1.0
   for v in itk.spacing(img):
     uabc3 *= v
   for v in lo.GetEquivalentEllipsoidSize():
     uabc3 *= v
   uabc3 = math.pow(uabc3, 1/3.0)
   spacing2 = [uabc3 / v for v in lo.GetEquivalentEllipsoidSize()]
   return (outputIdx, outputSize, outputSpacing, spacing2)
import numpy as np
import matplotlib.pyplot as plt
# import numpy.fft as fft
np.core.arrayprint._line_width = 200

Dimension = 2
RealPixelType = itk.F
RealImageType = itk.Image[RealPixelType, Dimension]

# Read input Image
inputImage = "/home/phc/Software/ITK/build-dev-cpp98/ExternalData/Modules/Remote/IsotropicWavelets/test/Input/checkershadow_Lch_512x512.tiff"
reader = itk.ImageFileReader.New(FileName=inputImage)
spacing = reader.GetOutput().GetSpacing()
origin = reader.GetOutput().GetOrigin()
direction = reader.GetOutput().GetDirection()

# Perform FFT on input image
castFilter = itk.CastImageFilter[itk.output(reader), RealImageType].New(reader)
fftFilter = itk.ForwardFFTImageFilter.New(castFilter)
fftFilter.Update()
ComplexType=itk.output(fftFilter.GetOutput())
npInput = itk.GetArrayFromImage(castFilter)
npFFT = itk.GetArrayFromImage(fftFilter)
plt.imshow(npInput)
itk.show(reader)
# plt.show()

inputImage3D = "/home/phc/Software/ITK/build-dev-cpp98/ExternalData/Modules/Remote/IsotropicWavelets/test/Input/collagen_21x21x9.tiff"
reader3D = itk.ImageFileReader.New(FileName=inputImage)
npInput3D = itk.GetArrayFromImage(reader3D)
Esempio n. 16
0
except KeyError:
    pass

# test ctype
assert itk.ctype("unsigned short") == itk.US
assert itk.ctype("        unsigned      \n   short \t  ") == itk.US
assert itk.ctype("signed short") == itk.SS
assert itk.ctype("short") == itk.SS
try:
    itk.ctype("dummy")
    raise Exception("unknown C type should send an exception")
except KeyError:
    pass

# test output
assert itk.output(reader) == reader.GetOutput()
assert itk.output(1) == 1
# test the deprecated image
assert itk.image(reader) == reader.GetOutput()
assert itk.image(1) == 1

# test size
s = itk.size(reader)
assert s[0] == s[1] == 256
s = itk.size(reader.GetOutput())
assert s[0] == s[1] == 256

# test physical size
s = itk.physical_size(reader)
assert s[0] == s[1] == 256.0
s = itk.physical_size(reader.GetOutput())
Esempio n. 17
0
    pass

# test ctype
assert itk.ctype("unsigned short") == itk.US
assert itk.ctype("        unsigned      \n   short \t  ") == itk.US
assert itk.ctype("signed short") == itk.SS
assert itk.ctype("short") == itk.SS
try:
    itk.ctype("dummy")
    raise Exception("unknown C type should send an exception")
except KeyError:
    pass


# test output
assert itk.output(reader) == reader.GetOutput()
assert itk.output(1) == 1
# test the deprecated image
assert itk.image(reader) == reader.GetOutput()
assert itk.image(1) == 1

# test size
s = itk.size(reader)
assert s[0] == s[1] == 256
s = itk.size(reader.GetOutput())
assert s[0] == s[1] == 256

# test physical size
s = itk.physical_size(reader)
assert s[0] == s[1] == 256.0
s = itk.physical_size(reader.GetOutput())
Esempio n. 18
0
import itk

input = '../../Testing/Data/Input/foot.mha'

valt = itk.F
imgt = itk.Image[valt, 2]

reader = itk.ImageFileReader[imgt].New( FileName=input )

grad_io = itk.VTKImageIO.New()
grad_io.SetPixelType( grad_io.VECTOR )

gradient_filter = itk.GradientImageFilter[ imgt, valt, valt ].New()
gradient_filter.SetInput( reader.GetOutput() )
gradt = itk.output(gradient_filter)
itk.write( gradient_filter, 'foot_GradientImageFilter.mha' )

gradient_mag_filter = itk.GradientToMagnitudeImageFilter[ gradt, imgt ].New()
gradient_mag_filter.SetInput( gradient_filter.GetOutput() )
itk.write( gradient_mag_filter, 'foot_GradientImageFilter_magnitude.mha' )


dog_filter = itk.DifferenceOfGaussiansGradientImageFilter[ imgt, valt ].New()
dog_filter.SetInput( reader.GetOutput() )
dog_filter.SetWidth( 1 )
itk.write( dog_filter, 'foot_DifferenceOfGaussiansGradientImageFilter.mha' )

dog_mag_filter = itk.GradientToMagnitudeImageFilter[ gradt, imgt ].New()
dog_mag_filter.SetInput( dog_filter.GetOutput() )
itk.write( dog_mag_filter, 'foot_DifferenceOfGaussiansGradientImageFilter_magnitude.mha' )
def checkerboard(image1, image2, pattern=3, invert=False, **viewer_kwargs):
    """Compare two images with a checkerboard pattern.

    This is particularly useful for examining registration results.

    Parameters
    ----------
    image1 : array_like, itk.Image, or vtk.vtkImageData
        First image to use in the checkerboard.

    image2 : array_like, itk.Image, or vtk.vtkImageData
        Second image to use in the checkerboard.

    pattern : int, optional, default: 3
        Size of the checkerboard pattern.

    invert : bool, optional, default: False
        Swap inputs.

    viewer_kwargs : optional
        Keyword arguments for the viewer. See help(itkwidgets.view).

    """

    itk_image1 = to_itk_image(image1)
    if not itk_image1:
        itk_image1 = itk.output(image1)
    itk_image2 = to_itk_image(image2)
    if not itk_image2:
        itk_image2 = itk.output(image2)
    input1 = itk_image1
    input2 = itk_image2

    region_image1 = itk_image1.GetLargestPossibleRegion()
    region_image2 = itk_image2.GetLargestPossibleRegion()
    same_physical_space = \
        np.allclose(np.array(itk_image1.GetOrigin()), np.array(itk_image2.GetOrigin())) and \
        np.allclose(np.array(itk_image1.GetSpacing()), np.array(itk_image2.GetSpacing())) and \
        itk_image1.GetDirection() == itk_image2.GetDirection() and \
        np.allclose(np.array(region_image1.GetIndex()), np.array(region_image2.GetIndex())) and \
        np.allclose(np.array(region_image1.GetSize()), np.array(region_image2.GetSize()))
    if not same_physical_space:
        upsample_image2 = True
        if itk_image1.GetSpacing() != itk_image2.GetSpacing():
            min1 = min(itk_image1.GetSpacing())
            min2 = min(itk_image2.GetSpacing())
            if min2 < min1:
                upsample_image2 = False
        else:
            size1 = max(itk.size(itk_image1))
            size2 = max(itk.size(itk_image1))
            if size2 > size1:
                upsample_image2 = False

        if upsample_image2:
            resampler = itk.ResampleImageFilter.New(itk_image2)
            resampler.UseReferenceImageOn()
            resampler.SetReferenceImage(itk_image1)
            resampler.Update()
            input2 = resampler.GetOutput()
        else:
            resampler = itk.ResampleImageFilter.New(itk_image1)
            resampler.UseReferenceImageOn()
            resampler.SetReferenceImage(itk_image2)
            resampler.Update()
            input1 = resampler.GetOutput()

    checkerboard_filter = itk.CheckerBoardImageFilter.New(input1, input2)

    dimension = itk_image1.GetImageDimension()
    checker_pattern = [pattern]*dimension
    checkerboard_filter.SetCheckerPattern(checker_pattern)
    checkerboard_filter_inverse = itk.CheckerBoardImageFilter.New(input2, input1)

    if invert:
        checkerboard_filter_inverse.Update()
        checkerboard = checkerboard_filter_inverse.GetOutput()
    else:
        checkerboard_filter.Update()
        checkerboard = checkerboard_filter.GetOutput()

    if 'annotations' not in viewer_kwargs:
        viewer_kwargs['annotations'] = False
    if 'interpolation' not in viewer_kwargs:
        viewer_kwargs['interpolation'] = False
    if 'ui_collapsed' not in viewer_kwargs:
        viewer_kwargs['ui_collapsed'] = True
    viewer = Viewer(image=checkerboard, **viewer_kwargs)

    # Heuristic to specify the max pattern size
    max_size1 = int(min(itk.size(itk_image1)) / 8)
    max_size1 = max(max_size1, pattern*2)
    max_size2 = int(min(itk.size(itk_image2)) / 8)
    max_size2 = max(max_size2, pattern*2)
    max_size = max(max_size1, max_size2)

    pattern_slider = widgets.IntSlider(value=pattern, min=2, max=max_size,
            step=1, description='Pattern size:')
    invert_checkbox = widgets.Checkbox(value=invert, description = 'Invert')
    def update_checkerboard(change):
        checker_pattern = [pattern_slider.value]*dimension
        checkerboard_filter.SetCheckerPattern(checker_pattern)
        checkerboard_filter_inverse.SetCheckerPattern(checker_pattern)
        if invert_checkbox.value:
            checkerboard_filter_inverse.Update()
            viewer.image = checkerboard_filter_inverse.GetOutput()
        else:
            checkerboard_filter.Update()
            viewer.image = checkerboard_filter.GetOutput()
    pattern_slider.observe(update_checkerboard, ['value'])
    invert_checkbox.observe(update_checkerboard, ['value'])

    widget = widgets.VBox([viewer,
        widgets.HBox([pattern_slider, invert_checkbox])])

    return widget
Esempio n. 20
0
def to_itk_image(image_like):

    if isinstance(image_like, (itk.Image, itk.VectorImage)):
        return image_like

    if is_arraylike(image_like):
        array = np.asarray(image_like)
        can_use_view = array.flags['OWNDATA']
        if have_dask and isinstance(image_like, dask.array.core.Array):
            can_use_view = False
        array = np.ascontiguousarray(array)
        # JavaScript does not support 64-bit integers
        if array.dtype == np.int64:
            array = array.astype(np.float32)
        elif array.dtype == np.uint64:
            array = array.astype(np.float32)
        if can_use_view:
            image_from_array = itk.image_view_from_array(array)
        else:
            image_from_array = itk.image_from_array(array)
        return image_from_array

    elif have_vtk and isinstance(image_like, vtk.vtkImageData):
        from vtk.util import numpy_support as vtk_numpy_support
        array = vtk_numpy_support.vtk_to_numpy(
            image_like.GetPointData().GetScalars())
        dims = list(image_like.GetDimensions())
        spacing = list(image_like.GetSpacing())
        origin = list(image_like.GetOrigin())

        # Check for zdim==1
        zdim = dims.pop()
        if zdim > 1:
            # zdim>1, put it back in the dims array
            dims.append(zdim)
        else:
            #zdim==1, remove z-spacing and z-origin
            spacing.pop()
            origin.pop()

        array.shape = dims[::-1]
        image_from_array = itk.image_view_from_array(array)
        image_from_array.SetSpacing(spacing)
        image_from_array.SetOrigin(origin)
        return image_from_array

    elif have_simpleitk and isinstance(image_like, sitk.Image):
        array = sitk.GetArrayViewFromImage(image_like)
        image_from_array = itk.image_view_from_array(array)
        image_from_array.SetSpacing(image_like.GetSpacing())
        image_from_array.SetOrigin(image_like.GetOrigin())
        direction = image_like.GetDirection()
        npdirection = np.asarray(direction)
        npdirection = np.reshape(npdirection, (-1, image_like.GetDimension()))
        itkdirection = itk.matrix_from_array(npdirection)
        image_from_array.SetDirection(itkdirection)
        return image_from_array

    elif have_imagej:
        import imglyb
        if isinstance(image_like,
                      imglyb.util.ReferenceGuardingRandomAccessibleInterval):
            array = imglyb.to_numpy(image_like)
            image_from_array = itk.image_view_from_array(array)
            return image_from_array

    elif isinstance(image_like, itk.ProcessObject):
        return itk.output(image_like)

    return None
Esempio n. 21
0
if len(sys.argv) != 5:
    print "Usage: " + sys.argv[0] + " inputImage outputImage High_sub_bands levels"
    sys.exit(1)
print ("Generating Wavelet Space for input image %s" % sys.argv[1])
inputImage = sys.argv[1]
outputImage = sys.argv[2]
high_sub_bands = int(sys.argv[3])
levels = int(sys.argv[4])

print "Reading image"
reader = itk.ImageFileReader.New(FileName=inputImage)
reader.Update()
spacing = reader.GetOutput().GetSpacing()
origin = reader.GetOutput().GetOrigin()
direction = reader.GetOutput().GetDirection()
castFilter = itk.CastImageFilter[itk.output(reader),itk.Image[itk.F,3]].New(reader)

print "Perform FFT on input image"
fftFilter = itk.ForwardFFTImageFilter.New(castFilter)
fftFilter.Update()
ComplexType=itk.output(fftFilter.GetOutput())
RealImageType = itk.Image[itk.F,3]
inverseFFT = itk.InverseFFTImageFilter[ ComplexType, RealImageType].New()
print "Create Forward Filter Bank"
PointType=itk.Point[itk.D,3]
SimoncelliType = itk.SimoncelliIsotropicWavelet[itk.F,3,PointType]
forwardFilterBankType = itk.WaveletFrequencyFilterBankGenerator[ComplexType,SimoncelliType]
forwardFilterBank = forwardFilterBankType.New()
forwardFilterBank.SetHighPassSubBands( high_sub_bands )
forwardFilterBank.SetSize( fftFilter.GetOutput().GetLargestPossibleRegion().GetSize() )
forwardFilterBank.Update()
Esempio n. 22
0
castImageFilter.Update()

filter2 = itk.ConnectedThresholdImageFilter.New(castImageFilter.GetOutput())
filter2.SetReplaceValue(255)
filter2.SetLower(900)
filter2.SetUpper(1600)

index = itk.Index[dimension]()
index[0] = 83
index[1] = 80
index[2] = 109

filter2.SetSeed(index)
filter2.Update()

in_type = itk.output(filter2)
output_type = itk.Image[PixelType, dimension]
rescaler = itk.RescaleIntensityImageFilter[in_type, output_type].New(filter2)
rescaler.SetOutputMinimum(0)
rescaler.SetOutputMaximum(255)
rescaler.Update()

itk.imwrite(filter2, os.path.join(filepath, itk_output_filename))

ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)

reader = vtk.vtkMetaImageReader()