Python Image.Image() Examples

The following are 30 code examples of Image.Image(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module Image , or try the search function .
Example #1
Source File: blob_image_test.py    From browserscope with Apache License 2.0 6 votes vote down vote up
def expect_crop(self, left_x=None, right_x=None, top_y=None, bottom_y=None):
    """Setup a mox expectation to images_stub._Crop."""
    crop_xform = images_service_pb.Transform()
    if left_x is not None:
      if not isinstance(left_x, float):
        raise self.failureException('Crop argument must be a float.')
      crop_xform.set_crop_left_x(left_x)
    if right_x is not None:
      if not isinstance(right_x, float):
        raise self.failureException('Crop argument must be a float.')
      crop_xform.set_crop_right_x(right_x)
    if top_y is not None:
      if not isinstance(top_y, float):
        raise self.failureException('Crop argument must be a float.')
      crop_xform.set_crop_top_y(top_y)
    if bottom_y is not None:
      if not isinstance(bottom_y, float):
        raise self.failureException('Crop argument must be a float.')
      crop_xform.set_crop_bottom_y(bottom_y)
    self._images_stub._Crop(mox.IsA(Image.Image), crop_xform).AndReturn(
        self._image) 
Example #2
Source File: ImageFile.py    From keras-lambda with MIT License 6 votes vote down vote up
def __init__(self, fp=None, filename=None):
        Image.Image.__init__(self)

        self.tile = None
        self.readonly = 1 # until we know better

        self.decoderconfig = ()
        self.decodermaxblock = MAXBLOCK

        if Image.isStringType(fp):
            # filename
            self.fp = open(fp, "rb")
            self.filename = fp
        else:
            # stream
            self.fp = fp
            self.filename = filename

        try:
            self._open()
        except IndexError, v: # end of data
            if Image.DEBUG > 1:
                traceback.print_exc()
            raise SyntaxError, v 
Example #3
Source File: ImageFile.py    From mxnet-lambda with Apache License 2.0 6 votes vote down vote up
def __init__(self, fp=None, filename=None):
        Image.Image.__init__(self)

        self.tile = None
        self.readonly = 1 # until we know better

        self.decoderconfig = ()
        self.decodermaxblock = MAXBLOCK

        if Image.isStringType(fp):
            # filename
            self.fp = open(fp, "rb")
            self.filename = fp
        else:
            # stream
            self.fp = fp
            self.filename = filename

        try:
            self._open()
        except IndexError, v: # end of data
            if Image.DEBUG > 1:
                traceback.print_exc()
            raise SyntaxError, v 
Example #4
Source File: ImageFile.py    From CNCGToolKit with MIT License 6 votes vote down vote up
def __init__(self, fp=None, filename=None):
        Image.Image.__init__(self)

        self.tile = None
        self.readonly = 1 # until we know better

        self.decoderconfig = ()
        self.decodermaxblock = MAXBLOCK

        if Image.isStringType(fp):
            # filename
            self.fp = open(fp, "rb")
            self.filename = fp
        else:
            # stream
            self.fp = fp
            self.filename = filename

        try:
            self._open()
        except IndexError, v: # end of data
            if Image.DEBUG > 1:
                traceback.print_exc()
            raise SyntaxError, v 
Example #5
Source File: blob_image_test.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def setUp(self):
    self.mox = mox.Mox()
    self._environ = {'PATH_INFO': 'http://test.com/_ah/img/SomeBlobKey',
                     'REQUEST_METHOD': 'GET'}
    self._images_stub = self.mox.CreateMock(images_stub.ImagesServiceStub)
    self._image = Image.Image()
    self.app = blob_image.Application()
    os.environ['APPLICATION_ID'] = 'testapp'
    self._get_images_stub = blob_image._get_images_stub
    blob_image._get_images_stub = lambda: self._images_stub 
Example #6
Source File: ImageFile.py    From keras-lambda with MIT License 5 votes vote down vote up
def seek(self, offset, whence=0):
        if whence == 0:
            self.offset = offset
        elif whence == 1:
            self.offset = self.offset + offset
        else:
            # force error in Image.open
            raise IOError("illegal argument to seek") 
Example #7
Source File: utils.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _show_extensions(self):
        for mn in ('_rl_accel','_renderPM','sgmlop','pyRXP','pyRXPU','_imaging','Image'):
            try:
                A = [mn].append
                __import__(mn)
                m = sys.modules[mn]
                A(m.__file__)
                for vn in ('__version__','VERSION','_version','version'):
                    if hasattr(m,vn):
                        A('%s=%r' % (vn,getattr(m,vn)))
            except:
                A('not found')
            self._writeln(' '+' '.join(A.__self__)) 
Example #8
Source File: ImageFile.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def load_prepare(self):
        # create image memory if necessary
        if not self.im or\
           self.im.mode != self.mode or self.im.size != self.size:
            self.im = Image.core.new(self.mode, self.size)
        # create palette (optional)
        if self.mode == "P":
            Image.Image.load(self) 
Example #9
Source File: ImageFile.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def seek(self, offset, whence=0):
        if whence == 0:
            self.offset = offset
        elif whence == 1:
            self.offset = self.offset + offset
        else:
            # force error in Image.open
            raise IOError("illegal argument to seek") 
Example #10
Source File: ImageFile.py    From mxnet-lambda with Apache License 2.0 5 votes vote down vote up
def close(self):
        # finish decoding
        if self.decoder:
            # get rid of what's left in the buffers
            self.feed("")
            self.data = self.decoder = None
            if not self.finished:
                raise IOError("image was incomplete")
        if not self.image:
            raise IOError("cannot parse this image")
        if self.data:
            # incremental parsing not possible; reopen the file
            # not that we have all data
            try:
                fp = _ParserFile(self.data)
                self.image = Image.open(fp)
            finally:
                fp.close() # explicitly close the virtual file
        return self.image

# --------------------------------------------------------------------

##
# (Helper) Save image body to file.
#
# @param im Image object.
# @param fp File object.
# @param tile Tile list. 
Example #11
Source File: ImageFile.py    From keras-lambda with MIT License 5 votes vote down vote up
def close(self):
        # finish decoding
        if self.decoder:
            # get rid of what's left in the buffers
            self.feed("")
            self.data = self.decoder = None
            if not self.finished:
                raise IOError("image was incomplete")
        if not self.image:
            raise IOError("cannot parse this image")
        if self.data:
            # incremental parsing not possible; reopen the file
            # not that we have all data
            try:
                fp = _ParserFile(self.data)
                self.image = Image.open(fp)
            finally:
                fp.close() # explicitly close the virtual file
        return self.image

# --------------------------------------------------------------------

##
# (Helper) Save image body to file.
#
# @param im Image object.
# @param fp File object.
# @param tile Tile list. 
Example #12
Source File: utils.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def import_zlib():
    try:
        import zlib
    except ImportError:
        zlib = None
        from reportlab.rl_config import ZLIB_WARNINGS
        if ZLIB_WARNINGS: warnOnce('zlib not available')
    return zlib

# Image Capability Detection.  Set a flag haveImages
# to tell us if either PIL or Java imaging libraries present.
# define PIL_Image as either None, or an alias for the PIL.Image
# module, as there are 2 ways to import it 
Example #13
Source File: utils.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def _isPILImage(im):
    try:
        return isinstance(im,Image.Image)
    except AttributeError:
        return 0 
Example #14
Source File: utils.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def _read_image(self,fp):
        if sys.platform[0:4] == 'java':
            from javax.imageio import ImageIO
            return ImageIO.read(fp)
        else:
            return Image.open(fp) 
Example #15
Source File: utils.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def getRGBData(self):
        "Return byte array of RGB data as string"
        try:
            if self._data is None:
                self._dataA = None
                if sys.platform[0:4] == 'java':
                    import jarray
                    from java.awt.image import PixelGrabber
                    width, height = self.getSize()
                    buffer = jarray.zeros(width*height, 'i')
                    pg = PixelGrabber(self._image, 0,0,width,height,buffer,0,width)
                    pg.grabPixels()
                    # there must be a way to do this with a cast not a byte-level loop,
                    # I just haven't found it yet...
                    pixels = []
                    a = pixels.append
                    for i in range(len(buffer)):
                        rgb = buffer[i]
                        a(chr((rgb>>16)&0xff))
                        a(chr((rgb>>8)&0xff))
                        a(chr(rgb&0xff))
                    self._data = ''.join(pixels)
                    self.mode = 'RGB'
                else:
                    im = self._image
                    mode = self.mode = im.mode
                    if mode=='RGBA':
                        if Image.VERSION.startswith('1.1.7'): im.load()
                        self._dataA = ImageReader(im.split()[3])
                        im = im.convert('RGB')
                        self.mode = 'RGB'
                    elif mode not in ('L','RGB','CMYK'):
                        im = im.convert('RGB')
                        self.mode = 'RGB'
                    self._data = im.tostring()
            return self._data
        except:
            annotateException('\nidentity=%s'%self.identity()) 
Example #16
Source File: utils.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def _show_extensions(self):
        for mn in ('_rl_accel','_renderPM','sgmlop','pyRXP','pyRXPU','_imaging','Image'):
            try:
                A = [mn].append
                m = recursiveImport(mn,sys.path[:],1)
                A(m.__file__)
                for vn in ('__version__','VERSION','_version','version'):
                    if hasattr(m,vn):
                        A('%s=%r' % (vn,getattr(m,vn)))
            except:
                A('not found')
            self._writeln(' '+' '.join(A.__self__)) 
Example #17
Source File: ImageFile.py    From CNCGToolKit with MIT License 5 votes vote down vote up
def raise_ioerror(error):
    try:
        message = Image.core.getcodecstatus(error)
    except AttributeError:
        message = ERRORS.get(error)
    if not message:
        message = "decoder error %d" % error
    raise IOError(message + " when reading image file")

#
# --------------------------------------------------------------------
# Helpers 
Example #18
Source File: ImageFile.py    From CNCGToolKit with MIT License 5 votes vote down vote up
def load_prepare(self):
        # create image memory if necessary
        if not self.im or\
           self.im.mode != self.mode or self.im.size != self.size:
            self.im = Image.core.new(self.mode, self.size)
        # create palette (optional)
        if self.mode == "P":
            Image.Image.load(self) 
Example #19
Source File: ImageFile.py    From CNCGToolKit with MIT License 5 votes vote down vote up
def seek(self, offset, whence=0):
        if whence == 0:
            self.offset = offset
        elif whence == 1:
            self.offset = self.offset + offset
        else:
            # force error in Image.open
            raise IOError("illegal argument to seek") 
Example #20
Source File: ImageFile.py    From CNCGToolKit with MIT License 5 votes vote down vote up
def close(self):
        # finish decoding
        if self.decoder:
            # get rid of what's left in the buffers
            self.feed("")
            self.data = self.decoder = None
            if not self.finished:
                raise IOError("image was incomplete")
        if not self.image:
            raise IOError("cannot parse this image")
        if self.data:
            # incremental parsing not possible; reopen the file
            # not that we have all data
            try:
                fp = _ParserFile(self.data)
                self.image = Image.open(fp)
            finally:
                self.image.load()
                fp.close() # explicitly close the virtual file
        return self.image

# --------------------------------------------------------------------

##
# (Helper) Save image body to file.
#
# @param im Image object.
# @param fp File object.
# @param tile Tile list. 
Example #21
Source File: transforms.py    From deep-learning-from-scratch-3 with MIT License 5 votes vote down vote up
def __call__(self, img):
        if not self.transforms:
            return img
        for t in self.transforms:
            img = t(img)
        return img


# =============================================================================
# Transforms for PIL Image
# ============================================================================= 
Example #22
Source File: transforms.py    From deep-learning-from-scratch-3 with MIT License 5 votes vote down vote up
def __call__(self, img):
        if self.mode == 'BGR':
            img = img.convert('RGB')
            r, g, b = img.split()
            img = Image.merge('RGB', (b, g, r))
            return img
        else:
            return img.convert(self.mode) 
Example #23
Source File: transforms.py    From deep-learning-from-scratch-3 with MIT License 5 votes vote down vote up
def __init__(self, size, mode=Image.BILINEAR):
        self.size = pair(size)
        self.mode = mode 
Example #24
Source File: transforms.py    From deep-learning-from-scratch-3 with MIT License 5 votes vote down vote up
def __call__(self, img):
        if isinstance(img, np.ndarray):
            return img
        if isinstance(img, Image.Image):
            img = np.asarray(img)
            img = img.transpose(2, 0, 1)
            img = img.astype(self.dtype)
            return img
        else:
            raise TypeError 
Example #25
Source File: transforms.py    From deep-learning-from-scratch-3 with MIT License 5 votes vote down vote up
def __call__(self, array):
        data = array.transpose(1, 2, 0)
        return Image.fromarray(data) 
Example #26
Source File: ImageFile.py    From keras-lambda with MIT License 5 votes vote down vote up
def load_prepare(self):
        # create image memory if necessary
        if not self.im or\
           self.im.mode != self.mode or self.im.size != self.size:
            self.im = Image.core.new(self.mode, self.size)
        # create palette (optional)
        if self.mode == "P":
            Image.Image.load(self) 
Example #27
Source File: utils.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def _isPILImage(im):
    try:
        return isinstance(im,Image.Image)
    except AttributeError:
        return 0 
Example #28
Source File: blob_image_test.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def expect_resize(self, resize):
    """Setup a mox expectation to images_stub._Resize."""
    resize_xform = images_service_pb.Transform()
    resize_xform.set_width(resize)
    resize_xform.set_height(resize)
    self._images_stub._Resize(mox.IsA(Image.Image),
                              resize_xform).AndReturn(self._image) 
Example #29
Source File: blob_image_test.py    From browserscope with Apache License 2.0 5 votes vote down vote up
def expect_encode_image(self, data,
                          mime_type=images_service_pb.OutputSettings.JPEG):
    """Setup a mox expectation to images_stub._EncodeImage."""
    output_settings = images_service_pb.OutputSettings()
    output_settings.set_mime_type(mime_type)
    self._images_stub._EncodeImage(mox.IsA(Image.Image),
                                   output_settings).AndReturn(data) 
Example #30
Source File: transforms.py    From Qualia2.0 with MIT License 5 votes vote down vote up
def __init__(self, size, interpolation=Image.BILINEAR):
        self.size = size
        self.interpolation = interpolation