Exemplo n.º 1
0
def GetArrayFromImage(imageOrFilter):
    """Get an Array with the content of the image buffer
    """
    # Check for numpy
    if not HAVE_NUMPY:
        raise ImportError('Numpy not available.')
    # Finds the image type
    import itk
    keys = [k for k in itk.PyBuffer.keys() if k[0] == output(imageOrFilter).__class__]
    if len(keys ) == 0:
        raise RuntimeError("No suitable template parameter can be found.")
    ImageType = keys[0]
    # Create a numpy array of the type of the input image
    return itk.PyBuffer[keys[0]].GetArrayFromImage(output(imageOrFilter))
Exemplo n.º 2
0
def _GetArrayFromImage(image_or_filter, function, keep_axes, update):
    """Get an Array with the content of the image buffer
    """
    # Check for numpy
    if not HAVE_NUMPY:
        raise ImportError('Numpy not available.')
    # Finds the image type
    import itk
    keys = [k for k in itk.PyBuffer.keys() if k[0] == output(image_or_filter).__class__]
    if len(keys ) == 0:
        raise RuntimeError("No suitable template parameter can be found.")
    ImageType = keys[0]
    # Create a numpy array of the type of the input image
    templatedFunction = getattr(itk.PyBuffer[keys[0]], function)
    return templatedFunction(output(image_or_filter), keep_axes, update)
Exemplo n.º 3
0
 def __init__(self, imageOrFilter, Label=False) :
   import tempfile, itk, os
   # get some data from the environment
   command = os.environ.get("WRAPITK_SHOW2D_COMMAND", "imview %s -fork")
   label_command = os.environ.get("WRAPITK_SHOW2D_LABEL_COMMAND", "imview %s -c regions.lut -fork")
   compress = os.environ.get("WRAPITK_SHOW2D_COMPRESS", "true").lower() in ["on", "true", "yes", "1"]
   extension = os.environ.get("WRAPITK_SHOW2D_EXTENSION", ".tif")
   # use the tempfile module to get a non used file name and to put
   # the file at the rignt place
   self.__tmpFile__ = tempfile.NamedTemporaryFile(suffix=extension)
   # get an updated image
   img = output(imageOrFilter)
   img.UpdateOutputInformation()
   img.Update()
   # change the LabelMaps to an Image, so we can look at them easily
   if 'LabelMap' in dir(itk) and img.GetNameOfClass() == 'LabelMap':
     # retreive the biggest label in the label map
     maxLabel = img.GetNthLabelObject( img.GetNumberOfLabelObjects() - 1 ).GetLabel()
     # search for a filter to convert the label map
     label_image_type = sorted( [params[1] for params in itk.LabelMapToLabelImageFilter.keys() if params[0] == class_(img) and itk.NumericTraits[itk.template(params[1])[1][0]].max() >= maxLabel ] )[0]
     convert = itk.LabelMapToLabelImageFilter[ img, label_image_type ].New( img )
     convert.Update()
     img = convert.GetOutput()
     # this is a label image - force the parameter
     Label = True
   write(img, self.__tmpFile__.name, compress)
   # now run imview
   import os
   if Label:
     os.system( label_command % self.__tmpFile__.name)
   else:
     os.system( command % self.__tmpFile__.name)
Exemplo n.º 4
0
def spacing(imageOrFilter):
    """Return the spacing of an image, or of the output image of a filter

    This method take care of updating the needed informations
    """
    # we don't need the entire output, only its size
    imageOrFilter.UpdateOutputInformation()
    img = output(imageOrFilter)
    return img.GetSpacing()
Exemplo n.º 5
0
def region(imageOrFilter):
    """Return the region of an image, or of the output image of a filter

    This method take care of updating the needed informations
    """
    # we don't need the entire output, only its size
    imageOrFilter.UpdateOutputInformation()
    img = output(imageOrFilter)
    return img.GetLargestPossibleRegion()
Exemplo n.º 6
0
def origin(image_or_filter):
    """Return the origin of an image, or of the output image of a filter

    This method take care of updating the needed informations
    """
    # we don't need the entire output, only its size
    image_or_filter.UpdateOutputInformation()
    img = output(image_or_filter)
    return img.GetOrigin()
Exemplo n.º 7
0
def show(input, **kargs):
    """display an image
    """
    import itk
    img = output(input)
    if img.GetImageDimension() == 3 and "show3D" in dir(itk):
        return itk.show3D(input, **kargs)
    else:
        # print("2D not supported yet, use the 3D viewer.")
        return show2D(input, **kargs)
Exemplo n.º 8
0
def set_inputs( newItkObject, args=[], kargs={} ):
  """Set the inputs of the given objects, according to the non named or the named parameters in args and kargs

  This function tries to assign all the non named parameters in the input of the newItkObject
  - the first non named parameter in the first input, etc.

  The named parameters are used by calling the method with the same name prefixed by 'Set'.
  set_inputs( obj, kargs={'Threshold': 10} ) calls obj.SetThreshold(10)

  This is the function use in the enhanced New() method to manage the inputs.
  It can be used to produce a similar behavior:

  def SetInputs(self, *args, **kargs):
    import itk
    itk.set_inputs(self, *args, **kargs)
  """
  # try to get the images from the filters in args
  args = [output(arg) for arg in args]

  # args without name are filter used to set input image
  #
  # count SetInput calls to call SetInput, SetInput2, SetInput3, ...
  # usefull with filter which take 2 input (or more) like SubstractImageFiler
  # Ex: substract image2.png to image1.png and save the result in result.png
  # r1 = itk.ImageFileReader.US2.New(FileName='image1.png')
  # r2 = itk.ImageFileReader.US2.New(FileName='image2.png')
  # s = itk.SubtractImageFilter.US2US2US2.New(r1, r2)
  # itk.ImageFileWriter.US2.New(s, FileName='result.png').Update()
  try :
    for setInputNb, arg  in enumerate(args) :
      methodName = 'SetInput%i' % (setInputNb+1)
      if methodName in dir(newItkObject) :
        # first try to use methods called SetInput1, SetInput2, ...
        # those method should have more chances to work in case of multiple
        # input types
        getattr(newItkObject, methodName)(arg)
      else :
        # no method called SetInput?
        # try with the standard SetInput(nb, input)
        newItkObject.SetInput(setInputNb, arg)
  except TypeError, e :
    # the exception have (at least) to possible reasons:
    # + the filter don't take the input number as first argument
    # + arg is an object of wrong type
    #
    # if it's not the first input, re-raise the exception
    if setInputNb != 0 :
      raise e
    # it's the first input, try to use the SetInput() method without input number
    newItkObject.SetInput(args[0])
    # but raise an exception if there is more than 1 argument
    if len(args) > 1 :
      raise TypeError('Object accept only 1 input.')
Exemplo n.º 9
0
def write(imageOrFilter, fileName, compression=False):
  """Write a image or the output image of a filter to filename

  The writer is instantiated with the image type of the image in
  parameter (or, again, with the output image of the filter in parameter)
  """
  import itk
  img = output(imageOrFilter)
  img.UpdateOutputInformation()
  # don't put that writer in the automatic pipeline
  tmp_auto_pipeline = auto_pipeline.current
  auto_pipeline.current = None
  writer = itk.ImageFileWriter[img].New(Input=img, FileName=fileName, UseCompression=compression)
  auto_pipeline.current = tmp_auto_pipeline
  writer.Update()
Exemplo n.º 10
0
def range(imageOrFilter) :
  """Return the range of values in a image of in the output image of a filter

  The minimum and maximum values are returned in a tuple: (min, max)
  range() take care of updating the pipeline
  """
  import itk
  img = output(imageOrFilter)
  img.UpdateOutputInformation()
  img.Update()
  # don't put that calculator in the automatic pipeline
  tmp_auto_pipeline = auto_pipeline.current
  auto_pipeline.current = None
  comp = itk.MinimumMaximumImageCalculator[img].New(Image=img)
  auto_pipeline.current = tmp_auto_pipeline
  comp.Compute()
  return (comp.GetMinimum(), comp.GetMaximum())
Exemplo n.º 11
0
def imwrite(imageOrFilter, fileName, compression=False):
    """Write a image or the output image of a filter to a file.

    The writer is instantiated with the image type of the image in
    parameter (or, again, with the output image of the filter in parameter).
    """
    import itk
    img = output(imageOrFilter)
    img.UpdateOutputInformation()
    # don't put that writer in the automatic pipeline
    tmp_auto_pipeline = auto_pipeline.current
    auto_pipeline.current = None
    writer = itk.ImageFileWriter[img].New(Input=img,
                                          FileName=fileName,
                                          UseCompression=compression)
    auto_pipeline.current = tmp_auto_pipeline
    writer.Update()
Exemplo n.º 12
0
def range(imageOrFilter):
    """Return the range of values in a image of in the output image of a filter

    The minimum and maximum values are returned in a tuple: (min, max)
    range() take care of updating the pipeline
    """
    import itk
    img = output(imageOrFilter)
    img.UpdateOutputInformation()
    img.Update()
    # don't put that calculator in the automatic pipeline
    tmp_auto_pipeline = auto_pipeline.current
    auto_pipeline.current = None
    comp = itk.MinimumMaximumImageCalculator[img].New(Image=img)
    auto_pipeline.current = tmp_auto_pipeline
    comp.Compute()
    return (comp.GetMinimum(), comp.GetMaximum())
Exemplo n.º 13
0
def index_to_physical_point( imageOrFilter, idx ):
  """Get the pysical point in an image from an index

  imageOrFilter is the image where the physical point must be computed
  idx is the index used to compute the physical point. It can be a continuous index.
  """
  import sys
  print >> sys.stderr, "WrapITK warning: itk.index_to_physical_point() is deprecated. The coresponding templated method is now available in itk::ImageBase."
  from __builtin__ import range # required because range is overladed in this module
  # get the image if needed
  img = output( imageOrFilter )
  dim = img.GetImageDimension()
  o = origin( img )
  s = spacing( img )

  # use the typemaps to really get a continuous index
  import itk
  idx = itk.ContinuousIndex[ itk.D, dim ]( idx )

  # create the output object
  p = itk.Point[ itk.D, dim ]()
  for i in range( 0, dim ):
    p[i] = s[i] * idx[i] + o[i]
  return p
Exemplo n.º 14
0
def physical_point_to_index( imageOrFilter, p ):
  """Get the index in an image from the physical point

  image is the image where the physical point must be computed
  p is the point used to compute the index
  """
  import sys
  print >> sys.stderr, "WrapITK warning: itk.physical_point_to_index() is deprecated. The coresponding templated method is now available in itk::ImageBase."
  from __builtin__ import range # required because range is overladed in this module
  # get the image if needed
  img = output( imageOrFilter )
  dim = img.GetImageDimension()
  o = origin( img )
  s = spacing( img )

  # use the typemaps to really get a point
  import itk
  p = itk.Point[ itk.D, dim ]( p )

  # create the output object
  idx = itk.Index[ dim ]()
  for i in range( 0, dim ):
    idx.SetElement( i, int( round( ( p[i] - o[i] ) / s[i] ) ) )
  return idx
Exemplo n.º 15
0
    def __init__(self, imageOrFilter, Label=False, Title=None):
        import tempfile
        import itk
        import os
        import platform
        # get some data from the environment
        command = os.environ.get("WRAPITK_SHOW2D_COMMAND")
        if command is None:
            if platform.system() == "Darwin":
                command = (
                    "open -a ImageJ -n --args -eval 'open(\"%(image)s\"); "
                    "run (\"View 100%%\"); rename(\"%(title)s\");'")
            else:
                command = (
                    "imagej %(image)s -run 'View 100%%' -eval "
                    "'rename(\"%(title)s\")' &")

        label_command = os.environ.get("WRAPITK_SHOW2D_LABEL_COMMAND")
        if label_command is None:
            if platform.system() == "Darwin":
                label_command = (
                    "open -a ImageJ -n --args -eval 'open(\"%(image)s\"); "
                    "run (\"View 100%%\"); rename(\"%(title)s\"); "
                    "run(\"3-3-2 RGB\");'")
            else:
                label_command = (
                    "imagej %(image)s -run 'View 100%%' -eval "
                    "'rename(\"%(title)s\")' -run '3-3-2 RGB' &")

        compress = os.environ.get(
            "WRAPITK_SHOW2D_COMPRESS",
            "true").lower() in ["on", "true", "yes", "1"]
        extension = os.environ.get("WRAPITK_SHOW2D_EXTENSION", ".tif")

        # use the tempfile module to get a non used file name and to put
        # the file at the rignt place
        self.__tmpFile__ = tempfile.NamedTemporaryFile(suffix=extension)
        # get an updated image
        img = output(imageOrFilter)
        img.UpdateOutputInformation()
        img.Update()
        if Title is None:
            # try to generate a title
            s = img.GetSource()
            if s:
                s = itk.down_cast(s)
                if hasattr(img, "GetSourceOutputIndex"):
                    o = '[%s]' % img.GetSourceOutputIndex()
                elif hasattr(img, "GetSourceOutputName"):
                    o = '[%s]' % img.GetSourceOutputName()
                else:
                    o = ""
                Title = "%s%s" % (s.__class__.__name__, o)
            else:
                Title = img.__class__.__name__
            try:
                import IPython
                ip = IPython.get_ipython()
                if ip is not None:
                    names = []
                    ref = imageOrFilter
                    if s:
                        ref = s
                    for n, v in ip.user_ns.iteritems():
                        if isinstance(v, itk.LightObject) and v == ref:
                            names.append(n)
                    if names != []:
                        Title = ", ".join(names) + " - " + Title
            except ImportError:
                # just do nothing
                pass
        # change the LabelMaps to an Image, so we can look at them easily
        if 'LabelMap' in dir(itk) and img.GetNameOfClass() == 'LabelMap':
            # retreive the biggest label in the label map
            maxLabel = img.GetNthLabelObject(
                img.GetNumberOfLabelObjects() - 1).GetLabel()
            # search for a filter to convert the label map
            lab = itk.LabelMapToLabelImageFilter.keys()
            maxVal = itk.NumericTraits[itk.template(params[1])[1][0]].max()
            cond = params[0] == class_(img) and maxVal >= maxLabel
            label_image_type = sorted([params[1] for params in lab if cond])[0]
            convert = itk.LabelMapToLabelImageFilter[
                img, label_image_type].New(img)
            convert.Update()
            img = convert.GetOutput()
            # this is a label image - force the parameter
            Label = True
        write(img, self.__tmpFile__.name, compress)
        # now run imview
        import os
        if Label:
            os.system(
                label_command %
                {"image": self.__tmpFile__.name, "title": Title})
        else:
            os.system(
                command %
                {"image": self.__tmpFile__.name, "title": Title})
Exemplo n.º 16
0
def set_inputs(newItkObject, args=[], kargs={}):
    """Set the inputs of the given objects, according to the non named or the
    named parameters in args and kargs

    This function tries to assign all the non named parameters in the input of
    the newItkObject
    - the first non named parameter in the first input, etc.

    The named parameters are used by calling the method with the same name
    prefixed by 'Set'.
    set_inputs( obj, kargs={'Threshold': 10} ) calls obj.SetThreshold(10)

    This is the function use in the enhanced New() method to manage the inputs.
    It can be used to produce a similar behavior:

    def SetInputs(self, *args, **kargs):
        import itk
        itk.set_inputs(self, *args, **kargs)
    """
    # try to get the images from the filters in args
    args = [output(arg) for arg in args]

    # args without name are filter used to set input image
    #
    # count SetInput calls to call SetInput, SetInput2, SetInput3, ...
    # usefull with filter which take 2 input (or more) like SubstractImageFiler
    # Ex: substract image2.png to image1.png and save the result in result.png
    # r1 = itk.ImageFileReader.US2.New(FileName='image1.png')
    # r2 = itk.ImageFileReader.US2.New(FileName='image2.png')
    # s = itk.SubtractImageFilter.US2US2US2.New(r1, r2)
    # itk.ImageFileWriter.US2.New(s, FileName='result.png').Update()
    try:
        for setInputNb, arg in enumerate(args):
            methodName = 'SetInput%i' % (setInputNb + 1)
            if methodName in dir(newItkObject):
                # first try to use methods called SetInput1, SetInput2, ...
                # those method should have more chances to work in case of
                # multiple input types
                getattr(newItkObject, methodName)(arg)
            else:
                # no method called SetInput?
                # try with the standard SetInput(nb, input)
                newItkObject.SetInput(setInputNb, arg)
    except TypeError as e:
        # the exception have (at least) to possible reasons:
        # + the filter don't take the input number as first argument
        # + arg is an object of wrong type
        #
        # if it's not the first input, re-raise the exception
        if setInputNb != 0:
            raise e
        # it's the first input, try to use the SetInput() method without input
        # number
        newItkObject.SetInput(args[0])
        # but raise an exception if there is more than 1 argument
        if len(args) > 1:
            raise TypeError('Object accept only 1 input.')
    except AttributeError:
        # There is no SetInput() method, try SetImage
        # but before, check the number of inputs
        if len(args) > 1:
            raise TypeError('Object accept only 1 input.')
        methodList = ['SetImage', 'SetInputImage']
        methodName = None
        for m in methodList:
            if m in dir(newItkObject):
                methodName = m
        if methodName:
            getattr(newItkObject, methodName)(args[0])
        else:
            raise AttributeError('No method found to set the input.')

    # named args : name is the function name, value is argument(s)
    for attribName, value in kargs.iteritems():
        # use Set as prefix. It allow to use a shorter and more intuitive
        # call (Ex: itk.ImageFileReader.UC2.New(FileName='image.png')) than
        # with the full name
        # (Ex: itk.ImageFileReader.UC2.New(SetFileName='image.png'))
        if attribName not in ["auto_progress", "template_parameters"]:
            attrib = getattr(newItkObject, 'Set' + attribName)
            attrib(value)
Exemplo n.º 17
0
def set_inputs(newItkObject, args=[], kargs={}):
    """Set the inputs of the given objects, according to the non named or the
    named parameters in args and kargs

    This function tries to assign all the non named parameters in the input of
    the newItkObject
    - the first non named parameter in the first input, etc.

    The named parameters are used by calling the method with the same name
    prefixed by 'Set'.
    set_inputs( obj, kargs={'Threshold': 10} ) calls obj.SetThreshold(10)

    This is the function use in the enhanced New() method to manage the inputs.
    It can be used to produce a similar behavior:

    def SetInputs(self, *args, **kargs):
        import itk
        itk.set_inputs(self, *args, **kargs)
    """
    # try to get the images from the filters in args
    args = [output(arg) for arg in args]

    # args without name are filter used to set input image
    #
    # count SetInput calls to call SetInput, SetInput2, SetInput3, ...
    # usefull with filter which take 2 input (or more) like SubstractImageFiler
    # Ex: substract image2.png to image1.png and save the result in result.png
    # r1 = itk.ImageFileReader.US2.New(FileName='image1.png')
    # r2 = itk.ImageFileReader.US2.New(FileName='image2.png')
    # s = itk.SubtractImageFilter.US2US2US2.New(r1, r2)
    # itk.ImageFileWriter.US2.New(s, FileName='result.png').Update()
    try:
        for setInputNb, arg in enumerate(args):
            methodName = 'SetInput%i' % (setInputNb + 1)
            if methodName in dir(newItkObject):
                # first try to use methods called SetInput1, SetInput2, ...
                # those method should have more chances to work in case of
                # multiple input types
                getattr(newItkObject, methodName)(arg)
            else:
                # no method called SetInput?
                # try with the standard SetInput(nb, input)
                newItkObject.SetInput(setInputNb, arg)
    except TypeError as e:
        # the exception have (at least) to possible reasons:
        # + the filter don't take the input number as first argument
        # + arg is an object of wrong type
        #
        # if it's not the first input, re-raise the exception
        if setInputNb != 0:
            raise e
        # it's the first input, try to use the SetInput() method without input
        # number
        newItkObject.SetInput(args[0])
        # but raise an exception if there is more than 1 argument
        if len(args) > 1:
            raise TypeError('Object accept only 1 input.')
    except AttributeError:
        # There is no SetInput() method, try SetImage
        # but before, check the number of inputs
        if len(args) > 1:
            raise TypeError('Object accept only 1 input.')
        methodList = ['SetImage', 'SetInputImage']
        methodName = None
        for m in methodList:
            if m in dir(newItkObject):
                methodName = m
        if methodName:
            getattr(newItkObject, methodName)(args[0])
        else:
            raise AttributeError('No method found to set the input.')

    # named args : name is the function name, value is argument(s)
    for attribName, value in kargs.items():
        # use Set as prefix. It allow to use a shorter and more intuitive
        # call (Ex: itk.ImageFileReader.UC2.New(FileName='image.png')) than
        # with the full name
        # (Ex: itk.ImageFileReader.UC2.New(SetFileName='image.png'))
        if attribName not in ["auto_progress", "template_parameters"]:
            attrib = getattr(newItkObject, 'Set' + attribName)
            attrib(output(value))
Exemplo n.º 18
0
def set_inputs(new_itk_object, args=None, kargs=None):
    """Set the inputs of the given objects, according to the non named or the
    named parameters in args and kargs

    This function tries to assign all the non named parameters in the input of
    the new_itk_object
    - the first non named parameter in the first input, etc.

    The named parameters are used by calling the method with the same name
    prefixed by 'Set'.
    set_inputs( obj, kargs={'Threshold': 10} ) calls obj.SetThreshold(10)

    This is the function use in the enhanced New() method to manage the inputs.
    It can be used to produce a similar behavior:

    def SetInputs(self, *args, **kargs):
        import itk
        itk.set_inputs(self, *args, **kargs)
    """

    # Fix bug with Mutable Default Arguments
    # https://docs.python-guide.org/writing/gotchas/
    args: list = args if args else []
    kargs: Dict[str, Any] = kargs if kargs else {}

    # try to get the images from the filters in args
    args = [output(arg) for arg in args]

    # args without name are filter used to set input image
    #
    # count SetInput calls to call SetInput, SetInput2, SetInput3, ...
    # useful with filter which take 2 input (or more) like SubtractImageFiler
    # Ex: subtract image2.png to image1.png and save the result in result.png
    # r1 = itk.ImageFileReader.US2.New(FileName='image1.png')
    # r2 = itk.ImageFileReader.US2.New(FileName='image2.png')
    # s = itk.SubtractImageFilter.US2US2US2.New(r1, r2)
    # itk.ImageFileWriter.US2.New(s, FileName='result.png').Update()
    setInputNb = -1
    try:
        for setInputNb, arg in enumerate(args):
            methodName = "SetInput%i" % (setInputNb + 1)
            if methodName in dir(new_itk_object):
                # first try to use methods called SetInput1, SetInput2, ...
                # those method should have more chances to work in case of
                # multiple input types
                getattr(new_itk_object, methodName)(arg)
            else:
                # no method called SetInput?
                # try with the standard SetInput(nb, input)
                new_itk_object.SetInput(setInputNb, arg)
    except TypeError as e:
        # the exception have (at least) to possible reasons:
        # + the filter don't take the input number as first argument
        # + arg is an object of wrong type
        #
        # if it's not the first input, re-raise the exception
        if setInputNb != 0:
            raise e
        # it's the first input, try to use the SetInput() method without input
        # number
        new_itk_object.SetInput(args[0])
        # but raise an exception if there is more than 1 argument
        if len(args) > 1:
            raise TypeError("Object accepts only 1 input.")
    except AttributeError:
        # There is no SetInput() method, try SetImage
        # but before, check the number of inputs
        if len(args) > 1:
            raise TypeError("Object accepts only 1 input.")
        methodList = ["SetImage", "SetInputImage"]
        methodName = None
        for m in methodList:
            if m in dir(new_itk_object):
                methodName = m
        if methodName:
            getattr(new_itk_object, methodName)(args[0])
        else:
            raise AttributeError("No method found to set the input.")

    # named args : name is the function name, value is argument(s)
    for attribName, value in kargs.items():
        # use Set as prefix. It allow to use a shorter and more intuitive
        # call (Ex: itk.ImageFileReader.UC2.New(FileName='image.png')) than
        # with the full name
        # (Ex: itk.ImageFileReader.UC2.New(SetFileName='image.png'))
        if attribName not in ["auto_progress", "template_parameters"]:
            if attribName.islower():
                attribName = _snake_to_camel(attribName)
            attrib = getattr(new_itk_object, "Set" + attribName)

            # Do not use try-except mechanism as this leads to
            # segfaults. Instead limit the number of types that are
            # tested. The list of tested type could maybe be replaced by
            # a test that would check for iterables.
            if type(value) in [list, tuple]:
                try:
                    output_value = [output(x) for x in value]
                    attrib(*output_value)
                except Exception:
                    attrib(output(value))
            else:
                attrib(output(value))