Ejemplo n.º 1
0
def imread(filename, dimension=3):
    """Reads an image file completely into memory.

    It uses the file extension to determine how to read the file. It first tries
    some specific readers for volume images (Inrimages, TIFFs, LSMs, NPY) or falls
    back on PIL readers for common formats if installed.

    In all cases the returned image is 3D (2D is upgraded to single slice 3D).
    If it has colour or is a vector field it is even 4D.

    :Parameters:
     - `filename` (str)

    :Returns Type:
        |SpatialImage|
    """
    filename = expusr(filename)
    if not exists(filename):
        raise IOError("The requested file do not exist: %s" % filename)

    root, ext = splitext(filename)
    ext = ext.lower()
    if ext == ".gz":
        root, ext = splitext(root)
        ext = ext.lower()
    if ext == ".inr":
        return read_inrimage(filename)
    elif ext in [".tif", ".tiff"]:
        return read_tif(filename)
    elif ext in [".npz", ".npy"]:
        return load(filename)
    elif ext in [".h5", ".hdf5"]:
        return read_h5(filename)
Ejemplo n.º 2
0
def color_by_sequence_blosum62_score(query_object, reference_object):
    """
    USAGE

    color_by_sequence_blosum62_score QUERY_OBJ, REFERENCE_OBJ

    Colors both the query and reference objects based on the aminoacid sequence
    BLOSUM62 score between the two objects. Residues are colored from a gradient
    between red and green where red residues have the lower BLOSUM62 and green
    residues the best. Prints and returns the BLOSUM62 score.
    """

    import sys
    from os.path import expanduser as expusr
    sys.path.insert(1, expusr("~/Desktop/scripts/"))
    from ze_utils.common import read_matrix_from_txt_file, blosum62

    # Get the sequences of the query and reference object
    query_seq = get_sequence(query_object, False)
    reference_seq = get_sequence(reference_object, False)

    # Sequences of query and reference objects must be of the same length.
    # No sequence alignment is performed.
    assert len(query_seq) == len(reference_seq), \
        "Objects do not have the same number of aminoacids."

    # Iterate over the two objects and retrieve the residue list. This makes
    # possible the comparison of two sequences where the residues are in the
    # same order but with different numbering.
    resi_list = {"query": [], "reference": []}
    cmd.iterate("%s and name CA" % (query_object), \
        "query.append(resi)", space = resi_list)
    cmd.iterate("%s and name CA" % (reference_object), \
        "reference.append(resi)", space = resi_list)

    # Read the BLOSUM62 matrix from the default location
    matrix, entries = read_matrix_from_txt_file()

    # Calculate the BLOSUM62 score between the given query and reference
    # sequences
    b62_scr, b62_res_scr = blosum62(matrix, entries, query_seq, reference_seq)

    # Create a Red-Green Gradient with 16 steps. This corresponds to each value
    # possible in the BLOSUM62 matrix (from -4 to 11).
    colors = set_colors_from_RG_gradient(16)

    # Iterate over each residue score in the objects and color them on the
    # corresponding color from the generated Reg-Green Gradient
    for index, res_scr in enumerate(b62_res_scr):
        cmd.color("RG%d" % (res_scr + 4), "resi %d and %s" % \
            (int(resi_list["query"][index]), query_object))
        cmd.color("RG%d" % (res_scr + 4), "resi %d and %s" % \
            (int(resi_list["reference"][index]), reference_object))

    # Print and return the BLOSUM62 score
    print("BLOSUM62 score: %5d" % (b62_scr))
    return b62_scr
Ejemplo n.º 3
0
def imsave(filename, img):
    """Save a |SpatialImage| to filename.

    .. note: `img` **must** be a |SpatialImage|.

    The filewriter is choosen according to the file extension. However all file extensions
    will not match the data held by img, in dimensionnality or encoding, and might raise `IOError`s.

    For real volume data, Inrimage and NPY are currently supported.
    For |SpatialImage|s that are actually 2D, PNG, BMP, JPG among others are supported if PIL is installed.

    :Parameters:
     - `filename` (str)
     - `img` (|SpatialImage|)
    """

    assert isinstance(img, SpatialImage)
    # -- images are always at least 3D! If the size of dimension 3 (indexed 2) is 1, then it is actually
    # a 2D image. If it is 4D it has vectorial or RGB[A] data. --
    filename = expusr(filename)
    head, tail = psplit(filename)
    head = head or "."
    if not exists(head):
        raise IOError("The directory do not exist: %s" % head)

    root, ext = splitext(filename)

    is2D = img.shape[2] == 1
    ext = ext.lower()
    if ext == ".gz":
        root, ext = splitext(root)
        ext = ext.lower()
    if ext == ".inr":
        write_inrimage(filename, img)
    elif ext in [".npz", ".npy"]:
        save(filename, img)
    elif ext in [".tiff", ".tif"]:
        write_tif(filename, img)
    else:
        if not is2D:
            raise IOError("No writer found for format of 3D image %s"%filename)
        else:
            # -- fallback on Pylab.
            # WARNING: Careful, this can fail in many ways still!
            # For example, many formats wont support writing scalar floats, or
            # vector floats, or encodings different from uchar8 --

            #WARNING 2: Still this damn transposition thing that may appear.
            #the problem is that what we write doesn't look like what is shown
            #with "display()". display() is broken, not the write functions.
            if len(img.shape) == 4: # RGB[A] images
                _imsave(filename,img[:,:,0,:])
            elif len(img.shape) == 3: #scalar images
                _imsave(filename, img[:,:,0])
            else:
                raise IOError("Unhandled image shape %s"%str(img.shape))
Ejemplo n.º 4
0
def imread (filename, dimension=3) :
    """Reads an image file completely into memory.

    It uses the file extension to determine how to read the file. It first tries
    some specific readers for volume images (Inrimages, TIFFs, LSMs, NPY) or falls
    back on PIL readers for common formats if installed.

    In all cases the returned image is 3D (2D is upgraded to single slice 3D).
    If it has colour or is a vector field it is even 4D.

    :Parameters:
     - `filename` (str)

    :Returns Type:
        |SpatialImage|
    """
    filename = expusr(filename)
    if not exists(filename) :
        raise IOError("The requested file do not exist: %s" % filename)

    root, ext = splitext(filename)
    ext = ext.lower()
    if ext == ".gz":
        root, ext = splitext(root)
        ext = ext.lower()
    if ext == ".inr":
        return read_inrimage(filename)
    elif ext == ".lsm":
        return read_lsm(filename)
    elif ext in [".tif", ".tiff"]:
        return read_tif(filename)
    elif ext in [".npz", ".npy"]:
        return load(filename)
    else:
        # -- We use the normal numpy reader. It returns 2D images.
        # If len(shape) == 2 : scalar image.
        # If len(shape) == 3 and shape[2] == 3 : rgb image
        # If len(shape) == 3 and shape[3] == 4 : rgba image.
        # Return a SpatialImage please! --

        # Use the array protocol to convert a PIL image to an array.
        # Don't use pylab'es PIL_to_array conversion as it flips images vertically.
        im_array = np.array(Image.open(filename))
        shape    = im_array.shape
        if len(shape)==2:
            newShape = (shape[0], shape[1], 1, 1)
        elif len(shape) == 3:
            newShape = (shape[0], shape[1], 1, shape[2])
        else:
            raise IOError("unhandled image shape : %s, %s"%(filename, str(shape)))
        #newarr   = np.zeros(newShape, dtype=im_array.dtype, order="C")
        #newarr[:,:,0] = im_array[:,:]
        vdim     = 1 if( len(shape) < 3 ) else shape[2]
        return SpatialImage(im_array.reshape(newShape), None, vdim)
Ejemplo n.º 5
0
def read_matrix_from_txt_file(f=expusr("~/Desktop/scripts/static/b62.txt")):
    """
    Read a BLOSUM62 matrix from a TXT file. Since this file requires a specific
    format, the usage of the matrix on the default location is encourgaed. 
    Returns both the loaded matrix and the list of its entries.

    See also: blosum62
    """

    matrix = []
    with open(f, "r") as b62:
        entries = b62.readline().split()
        for line in b62:
            matrix.append([int(value) for value in line.split()[1:]])
    return matrix, entries
Ejemplo n.º 6
0
Archivo: IO.py Proyecto: leoguignard/IO
def imsave(filename, img):
    """Save a |SpatialImage| to filename.

    .. note: `img` **must** be a |SpatialImage|.

    The filewriter is choosen according to the file extension. However all file extensions
    will not match the data held by img, in dimensionnality or encoding, and might raise `IOError`s.

    For real volume data, Inrimage and NPY are currently supported.
    For |SpatialImage|s that are actually 2D, PNG, BMP, JPG among others are supported if PIL is installed.

    :Parameters:
     - `filename` (str)
     - `img` (|SpatialImage|)
    """

    filename = expusr(filename)
    root, ext = splitext(filename)

    # assert isinstance(img, SpatialImage) or ext == '.klb'
    # -- images are always at least 3D! If the size of dimension 3 (indexed 2) is 1, then it is actually
    # a 2D image. If it is 4D it has vectorial or RGB[A] data. --
    head, tail = psplit(filename)
    head = head or "."
    if not exists(head):
        raise IOError("The directory do not exist: %s" % head)

    # is2D = img.shape[2] == 1
    ext = ext.lower()
    if ext == ".gz":
        root, ext = splitext(root)
        ext = ext.lower()
    if ext == ".inr":
        write_inrimage(filename, img)
    elif ext in [".npz", ".npy"]:
        save(filename, img)
    elif ext in [".tiff", ".tif"]:
        write_tif(filename, img)
    elif ext == '.klb':
        write_klb(filename, img)
    elif ext in ['.h5', '.hdf5']:
        write_h5(filename, img)