Esempio n. 1
0
    def __init__(self, im):

        data = None
        colortable = None

        # handle filename, if given instead of image name
        if hasattr(im, "toUtf8"):
            # FIXME - is this really the best way to do this?
            im = unicode(im.toUtf8(), "utf-8")
        if Image.isStringType(im):
            im = Image.open(im)

        if im.mode == "1":
            format = QImage.Format_Mono
        elif im.mode == "L":
            format = QImage.Format_Indexed8
            colortable = []
            for i in range(256):
                colortable.append(rgb(i, i, i))
        elif im.mode == "P":
            format = QImage.Format_Indexed8
            colortable = []
            palette = im.getpalette()
            for i in range(0, len(palette), 3):
                colortable.append(rgb(*palette[i:i+3]))
        elif im.mode == "RGB":
            data = im.tostring("raw", "BGRX")
            format = QImage.Format_RGB32
        elif im.mode == "RGBA":
            try:
                data = im.tostring("raw", "BGRA")
            except SystemError:
                # workaround for earlier versions
                r, g, b, a = im.split()
                im = Image.merge("RGBA", (b, g, r, a))
            format = QImage.Format_ARGB32
        else:
            raise ValueError("unsupported image mode %r" % im.mode)

        # must keep a reference, or Qt will crash!
        self.__data = data or im.tostring()

        QImage.__init__(self, self.__data, im.size[0], im.size[1], format)

        if colortable:
            self.setColorTable(colortable)
Esempio n. 2
0
    def __init__(self, im):

        data = None
        colortable = None

        # handle filename, if given instead of image name
        if hasattr(im, "toUtf8"):
            # FIXME - is this really the best way to do this?
            im = unicode(im.toUtf8(), "utf-8")
        if Image.isStringType(im):
            im = Image.open(im)

        if im.mode == "1":
            format = QImage.Format_Mono
        elif im.mode == "L":
            format = QImage.Format_Indexed8
            colortable = []
            for i in range(256):
                colortable.append(rgb(i, i, i))
        elif im.mode == "P":
            format = QImage.Format_Indexed8
            colortable = []
            palette = im.getpalette()
            for i in range(0, len(palette), 3):
                colortable.append(rgb(*palette[i:i + 3]))
        elif im.mode == "RGB":
            data = im.tostring("raw", "BGRX")
            format = QImage.Format_RGB32
        elif im.mode == "RGBA":
            try:
                data = im.tostring("raw", "BGRA")
            except SystemError:
                # workaround for earlier versions
                r, g, b, a = im.split()
                im = Image.merge("RGBA", (b, g, r, a))
            format = QImage.Format_ARGB32
        else:
            raise ValueError("unsupported image mode %r" % im.mode)

        # must keep a reference, or Qt will crash!
        self.__data = data or im.tostring()

        QImage.__init__(self, self.__data, im.size[0], im.size[1], format)

        if colortable:
            self.setColorTable(colortable)
def to_img(img, scalar_type=None, lut=None, forceNativeLut=None):
    """Transform an image array into a QImage

    :Parameters:
     -`img` (NxMx3 or 4 array of int) - 2D matrix of RGB(A) image pixels
                       i will correspond to y and j to x with origin
                       in the top left corner

    :Returns Type: QImage
    """
    # -- personnal opinion (DB) : there shouldn't be ANY transposition
    # applied automatically in viewing code, except for transpositions
    # explicitly asked by the user view GUI or what. If the image is not
    # properly oriented it is up to the reading code to fix the orientation! --
    if isinstance(img, SpatialImage):
        nb_dim = len(img.shape)
        if nb_dim == 3:
            img = img.transpose(1, 0, 2)
        elif nb_dim == 4:
            img = img.transpose(1, 0, 2, 3)
        elif nb_dim == 2:
            img = img.transpose(1, 0)
        else:
            raise Exception("Unknown image shape, cannot deduce pixel format")
    _img = Image.fromarray(img)
    pseudo_QImage = ImageQt.ImageQt(_img)
    return pseudo_QImage

    try:
        imgconvarray = {
            1: QImage.Format_Indexed8,
            3: QImage.Format_RGB888,
            4: QImage.Format_ARGB32
        }
    except:
        imgconvarray = {1: QImage.Format_Indexed8, 4: QImage.Format_ARGB32}

    nb_dim = len(img.shape)
    if nb_dim == 3:
        vdim = img.shape[-1]
        img = img.transpose(1, 0, 2).copy("C")
    elif nb_dim == 4:
        vdim = img.shape[-1]
        img = img.transpose(1, 0, 2, 3).copy("C")
    elif nb_dim == 2:
        vdim = 1
        img = img.transpose(1, 0).copy("C")
    else:
        raise Exception("Unknown image shape, cannot deduce pixel format")

    if not img.flags['C_CONTIGUOUS']:
        img = img.copy("C")

    qimg = QImage(img.data, img.shape[1], img.shape[0], imgconvarray[vdim])

    return qimg.copy()
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)
def read_sequence ( directory, grayscale=True, number_images=None, start=0, increment=1, filename_contains="", voxels_size=None, verbose=True) :
    """
    Convert a sequence of images in a folder as a numpy array.
    The images must all be the same size and type.
    They can be in TIFF, .... format.

    :Parameters:
        - `grayscale` (bool) - convert the image to grayscale
        - `number_images` (int) - specify how many images to open
        - `start` (int) - used to start with the nth image in the folder (default = 0 for the first image)
        - `increment` (int) - set to "n" to open every "n" image (default = 1 for opening all images)
        - `filename_contains` (str) - only files whose name contains that string are opened
        - `voxels_size (tuple) - specify voxels size
        - `verbose` (bool) - verbose mode
    """

    _images = []
    _files = []

    if verbose : print "Loading : "
    for f in os.listdir(directory):
        if fnmatch.fnmatch(f, '*%s*' %filename_contains):
            try :
                im = Image.open(os.path.join(directory, f))
                _files.append(f)
                if grayscale is True :
                    _images.append(ImageOps.grayscale(im))
                else:
                    _images.append(im)
            except :
                if verbose : print "\t warning : cannot open %s" %f

    if len(_images) == 0 :
        if verbose : print "\t no images loaded"
        return -1

    xdim, ydim = _images[0].size

    if number_images is None :
        zdim = round(float(len(_images) - start)/ increment)
        _nmax = len(_images) - start
    else :
        zdim = number_images
        _nmax = number_images * increment

    if _images[0].mode == 'RGB':
        nd_image = np.zeros((xdim,ydim,zdim, 3), dtype=np.uint8)

    nd_image = np.zeros((xdim,ydim,zdim))

    j = 0
    for i in _images[start:_nmax+start:increment] :
        if i.size == _images[start].size :
            nd_image[:,:,j] = i
            if verbose : print "\t ./%s" %_files[_images.index(i)]
            j += 1
        else :
            if verbose : print "%s : wrong size - %s expected, %s found" %(_files[_images.index(i)], _images[start].size, i.size)
    result = nd_image.transpose(1,0,2)

    if voxels_size is None :
        return SpatialImage(result)
    else :
        return SpatialImage(result, voxels_size)
Esempio n. 6
0
def to_img (img, scalar_type=None, lut=None, forceNativeLut=None) :
    """Transform an image array into a QImage

    :Parameters:
     -`img` (NxMx3 or 4 array of int) - 2D matrix of RGB(A) image pixels
                       i will correspond to y and j to x with origin
                       in the top left corner

    :Returns Type: QImage
    """
    # -- personnal opinion (DB) : there shouldn't be ANY transposition
    # applied automatically in viewing code, except for transpositions
    # explicitly asked by the user view GUI or what. If the image is not
    # properly oriented it is up to the reading code to fix the orientation! --
    if isinstance(img, SpatialImage):
        nb_dim = len(img.shape)
        if nb_dim == 3:
            img = img.transpose(1,0,2)
        elif nb_dim == 4:
            img = img.transpose(1,0,2,3)
        elif nb_dim == 2:
            img = img.transpose(1,0)
        else:
            raise Exception("Unknown image shape, cannot deduce pixel format")
    _img = Image.fromarray(img)
    pseudo_QImage = ImageQt.ImageQt(_img)
    return pseudo_QImage

    try:
        imgconvarray={
            1:QImage.Format_Indexed8,
            3:QImage.Format_RGB888,
            4:QImage.Format_ARGB32
            }
    except:
        imgconvarray={
            1:QImage.Format_Indexed8,
            4:QImage.Format_ARGB32
            }

    nb_dim = len(img.shape)
    if nb_dim == 3:
        vdim = img.shape[-1]
        img = img.transpose(1,0,2).copy("C")
    elif nb_dim == 4:
        vdim = img.shape[-1]
        img = img.transpose(1,0,2,3).copy("C")
    elif nb_dim == 2:
        vdim = 1
        img = img.transpose(1,0).copy("C")
    else:
        raise Exception("Unknown image shape, cannot deduce pixel format")

    if not img.flags['C_CONTIGUOUS']:
        img = img.copy("C")

    qimg = QImage(img.data,
                  img.shape[1],
                  img.shape[0],
                  imgconvarray[vdim])

    
    return qimg.copy()