Example #1
0
def read_lsm(filename,channel=0):
    """Read an lsm image

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

    # LSM reader
    imageFile = lsmreader.Lsmimage(filename)
    imageFile.open()

    _info = {}
    #LSM header
    _VX = imageFile.header['CZ LSM info']['Voxel Size X']
    _VY = imageFile.header['CZ LSM info']['Voxel Size Y']
    _VZ = imageFile.header['CZ LSM info']['Voxel Size Z']
    _vx = _VX * 10**6
    _vy = _VY * 10**6
    _vz = _VZ * 10**6

    _PIXSIZE = imageFile.header['Image'][0]['Bit / Sample']

    _info["TYPE"] = 'unsigned fixed'
    _info["PIXSIZE"] = str(_PIXSIZE)
    _info["SCALE"] = 2
    _info["CPU"] = 'decm'
    _info["#GEOMETRY"] = 'CARTESIAN'

    #LSM datas
    _data = imageFile.image['data'][channel]
    im = SpatialImage(_data)
    im.resolution = _vx,_vy,_vz
    im.info = _info
    return im
Example #2
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