Example #1
0
def loadTiffStack(fname,useLibTiff=False):
  """
  Read a TIFF stack.
  We're using tifflib by default as, right now, only this works when the application is compile on Windows. [17/08/15]
  Bugs: known to fail with tiffs produced by Icy [23/07/15]

  """
  if not os.path.exists(fname):
    print "imageStackLoader.loadTiffStack can not find %s" % fname
    return

  purePython = True
  if useLibTiff:
    from libtiff import TIFFfile
    import numpy as np
    tiff = TIFFfile(fname)
    samples, sample_names = tiff.get_samples() #we should have just one
    print "Loading:\n" + tiff.get_info() + " with libtiff\n"
    im = np.asarray(samples[0])
  else:
    print "Loading:\n" + fname + " with tifffile\n"
    from tifffile import imread 
    im = imread(fname)

  im=im.swapaxes(1,2) 
  print "read image of size: cols: %d, rows: %d, layers: %d" % (im.shape[1],im.shape[2],im.shape[0])
  return im
Example #2
0
def load_tiff_stack(fname, use_lib_tiff=False):
    """
    Read a TIFF stack.
    We're using tifflib by default as, right now, only this works when the application is compile on Windows. [17/08/15]
    Bugs: known to fail with tiffs produced by Icy [23/07/15]
    """
    if not check_file_exists(fname, "load_tiff_stack"):
        return

    if use_lib_tiff:
        try:
            from libtiff import TIFFfile
        except ImportError:  # Suppresses error in IDE when libtiff not installed
            raise
        tiff = TIFFfile(fname)
        samples, sample_names = tiff.get_samples()  # we should have just one
        print("Loading: " + tiff.get_info() + " with libtiff\n")
        im = np.asarray(samples[0])
    else:
        print("Loading: " + fname + " with tifffile\n")
        from tifffile import imread

        im = imread(fname)

    im = im.swapaxes(1, 2)
    print("read image of size: cols: %d, rows: %d, layers: %d" %
          (im.shape[1], im.shape[2], im.shape[0]))
    return im
Example #3
0
def read_tif(filename,channel=0):
    """Read a tif image

    :Parameters:
    - `filename` (str) - name of the file to read
    """

    # TIF reader
    tif = libtiff.TIFF.open(filename)
    
    if tif.GetField('ImageDescription'):
        tif = TIFFfile(filename)
        arr = tif.get_tiff_array()
        _data = arr[:].T
        info_str = tif.get_info()
    else:
        i = 1
        while not tif.LastDirectory():
            i+=1
            tif.ReadDirectory()
        tif.SetDirectory(0)
        _data = np.zeros((i,)+tif.read_image().shape,dtype=tif.read_image().dtype)
        for ii,i in enumerate(tif.iter_images()):
            _data[ii] = i
        _data = _data.transpose(2, 1, 0)
        info_str = tif.info()

    nx, ny, nz = _data.shape

    # -- prepare metadata dictionnary --
    
    info_dict = dict( filter( lambda x: len(x)==2,
                              (inf.split(':') for inf in info_str.split("\n"))
                              ) )
    for k,v in info_dict.iteritems():
        info_dict[k] = v.strip()

    # -- getting the voxelsizes from the tiff image: sometimes
    # there is a BoundingBox attribute, sometimes there are
    # XResolution, YResolution, ZResolution or spacing.
    # the object returned by get_tiff_array has a "get_voxel_sizes()"
    # method but it fails, so here we go. --
    if "BoundingBox" in info_dict:
        bbox = info_dict["BoundingBox"]
        xm, xM, ym, yM, zm, zM = map(float,bbox.split())
        _vx = (xM-xm)/nx
        _vy = (yM-ym)/ny
        _vz = (zM-zm)/nz
    else:
        # -- When we have [XYZ]Resolution fields, it describes the
        # number of voxels per real unit. In SpatialImage we want the
        # voxelsizes, which is the number of real units per voxels.
        # So we must invert the result. --
        if "XResolution" in info_dict:
            # --resolution is stored in a [(values, precision)] list-of-one-tuple, or
            # sometimes as a single number --
            xres_str = eval(info_dict["XResolution"])
            if isinstance(xres_str, list) and isinstance(xres_str[0], tuple):
                xres_str = xres_str[0]
                _vx = float(xres_str[0])/xres_str[1]
            elif isinstance(xres_str, (int, float)):
                _vx = float(xres_str)
            else:
                _vx = 1.
            _vx = 1./_vx if _vx != 0 else 1.
        else:
            _vx = 1.0 # dumb fallback, maybe we will find something smarter later on
        if "YResolution" in info_dict:
            # --resolution is stored in a [(values, precision)] list-of-one-tuple, or
            # sometimes as a single number --
            yres_str = eval(info_dict["YResolution"])
            if isinstance(yres_str, list) and isinstance(yres_str[0], tuple):
                yres_str = yres_str[0]
                _vy = float(yres_str[0])/yres_str[1]
            elif isinstance(yres_str, (int, float)):
                _vy = float(yres_str)
            else:
                _vy = 1.
            _vy = 1./_vy if _vy != 0 else 1.
        else:
            _vy = 1.0 # dumb fallback, maybe we will find something smarter later on

        if "ZResolution" in info_dict:
            # --resolution is stored in a [(values, precision)] list-of-one-tuple, or
            # sometimes as a single number --
            zres_str = eval(info_dict["ZResolution"])
            if isinstance(zres_str, list) and isinstance(zres_str[0], tuple):
                zres_str = zres_str[0]
                _vz = float(zres_str[0])/zres_str[1]
            elif isinstance(zres_str, (int, float)):
                _vz = float(zres_str)
            else:
                _vz = 1.
            _vz = 1./_vz if _vz != 0 else 1.
        else:
            if "spacing" in info_dict:
                _vz = eval(info_dict["spacing"])
            else:
                _vz = 1.0 # dumb fallback, maybe we will find something smarter later on

    tif.close()
    # -- dtypes are not really stored in a compatible way (">u2" instead of uint16)
    # but we can convert those --
    dt = np.dtype(_data.dtype.name)
    # -- Return a SpatialImage please! --
    im = SpatialImage(_data, dtype=dt)
    im.resolution = _vx,_vy,_vz

    return im
Example #4
0
def read_tif(filename,channel=0):
    """Read a tif image

    :Parameters:
    - `filename` (str) - name of the file to read
    """

    # TIF reader
    tif = libtiff.TIFF.open(filename)

    if tif.GetField('ImageDescription'):
        tif = TIFFfile(filename)
        arr = tif.get_tiff_array()
        _data = arr[:].T
        info_str = tif.get_info()
    else:
        i = 1
        while not tif.LastDirectory():
            i+=1
            tif.ReadDirectory()
        tif.SetDirectory(0)
        _data = np.zeros((i,)+tif.read_image().shape,dtype=tif.read_image().dtype)
        for ii,i in enumerate(tif.iter_images()):
            _data[ii] = i
        _data = _data.transpose(2, 1, 0)
        info_str = tif.info()

    nx, ny, nz = _data.shape

    # -- prepare metadata dictionnary --
    info_dict = dict( filter( lambda x: len(x)==2,
                              (inf.split(':') for inf in info_str.split("\n"))
                              ) )
    info_dict.update(dict( filter( lambda x: len(x)==2,(inf.split('=') for inf in info_str.split("\n"))) ))
    for k,v in info_dict.iteritems():
        info_dict[k] = v.strip()

    info_dict.update({'Filename':filename.split('/')[-1]})
    print info_dict

    # -- getting the voxelsizes from the tiff image: sometimes
    # there is a BoundingBox attribute, sometimes there are
    # XResolution, YResolution, ZResolution or spacing.
    # the object returned by get_tiff_array has a "get_voxel_sizes()"
    # method but it fails, so here we go. --
    if "BoundingBox" in info_dict:
        bbox = info_dict["BoundingBox"]
        xm, xM, ym, yM, zm, zM = map(float,bbox.split())
        _vx = (xM-xm)/nx
        _vy = (yM-ym)/ny
        _vz = (zM-zm)/nz
    else:
        # -- When we have [XYZ]Resolution fields, it describes the
        # number of voxels per real unit. In SpatialImage we want the
        # voxelsizes, which is the number of real units per voxels.
        # So we must invert the result. --
        if "XResolution" in info_dict:
            # --resolution is stored in a [(values, precision)] list-of-one-tuple, or
            # sometimes as a single number --
            xres_str = eval(info_dict["XResolution"])
            if isinstance(xres_str, list) and isinstance(xres_str[0], tuple):
                xres_str = xres_str[0]
                _vx = float(xres_str[0])/xres_str[1]
            elif isinstance(xres_str, (int, float)):
                _vx = float(xres_str)
            else:
                _vx = 1.
            _vx = 1./_vx if _vx != 0 else 1.
        else:
            _vx = 1.0 # dumb fallback, maybe we will find something smarter later on
        if "YResolution" in info_dict:
            # --resolution is stored in a [(values, precision)] list-of-one-tuple, or
            # sometimes as a single number --
            yres_str = eval(info_dict["YResolution"])
            if isinstance(yres_str, list) and isinstance(yres_str[0], tuple):
                yres_str = yres_str[0]
                _vy = float(yres_str[0])/yres_str[1]
            elif isinstance(yres_str, (int, float)):
                _vy = float(yres_str)
            else:
                _vy = 1.
            _vy = 1./_vy if _vy != 0 else 1.
        else:
            _vy = 1.0 # dumb fallback, maybe we will find something smarter later on

        if "ZResolution" in info_dict:
            # --resolution is stored in a [(values, precision)] list-of-one-tuple, or
            # sometimes as a single number --
            zres_str = eval(info_dict["ZResolution"])
            if isinstance(zres_str, list) and isinstance(zres_str[0], tuple):
                zres_str = zres_str[0]
                _vz = float(zres_str[0])/zres_str[1]
            elif isinstance(zres_str, (int, float)):
                _vz = float(zres_str)
            else:
                _vz = 1.
            _vz = 1./_vz if _vz != 0 else 1.
        else:
            if "spacing" in info_dict:
                _vz = eval(info_dict["spacing"])
            else:
                _vz = 1.0 # dumb fallback, maybe we will find something smarter later on

    tif.close()
    # -- dtypes are not really stored in a compatible way (">u2" instead of uint16)
    # but we can convert those --
    dt = np.dtype(_data.dtype.name)
    # -- Return a SpatialImage please! --
    im = SpatialImage(_data, dtype=dt)
    im.resolution = _vx,_vy,_vz
    im.info = info_dict

    return im