Python PIL.Image.core() Examples

The following are 30 code examples of PIL.Image.core(). 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 PIL.Image , or try the search function .
Example #1
Source File: Image.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def blend(im1, im2, alpha):
    """
    Creates a new image by interpolating between two input images, using
    a constant alpha.::

        out = image1 * (1.0 - alpha) + image2 * alpha

    :param im1: The first image.
    :param im2: The second image.  Must have the same mode and size as
       the first image.
    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a
       copy of the first image is returned. If alpha is 1.0, a copy of
       the second image is returned. There are no restrictions on the
       alpha value. If necessary, the result is clipped to fit into
       the allowed output range.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    im1.load()
    im2.load()
    return im1._new(core.blend(im1.im, im2.im, alpha)) 
Example #2
Source File: Image.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _getdecoder(mode, decoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        decoder = DECODERS[decoder_name]
    except KeyError:
        pass
    else:
        return decoder(mode, *args + extra)

    try:
        # get decoder
        decoder = getattr(core, decoder_name + "_decoder")
    except AttributeError:
        raise OSError("decoder %s not available" % decoder_name)
    return decoder(mode, *args + extra) 
Example #3
Source File: Image.py    From teleport with Apache License 2.0 6 votes vote down vote up
def blend(im1, im2, alpha):
    """
    Creates a new image by interpolating between two input images, using
    a constant alpha.::

        out = image1 * (1.0 - alpha) + image2 * alpha

    :param im1: The first image.
    :param im2: The second image.  Must have the same mode and size as
       the first image.
    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a
       copy of the first image is returned. If alpha is 1.0, a copy of
       the second image is returned. There are no restrictions on the
       alpha value. If necessary, the result is clipped to fit into
       the allowed output range.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    im1.load()
    im2.load()
    return im1._new(core.blend(im1.im, im2.im, alpha)) 
Example #4
Source File: Image.py    From FODI with GNU General Public License v3.0 6 votes vote down vote up
def blend(im1, im2, alpha):
    """
    Creates a new image by interpolating between two input images, using
    a constant alpha.::

        out = image1 * (1.0 - alpha) + image2 * alpha

    :param im1: The first image.
    :param im2: The second image.  Must have the same mode and size as
       the first image.
    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a
       copy of the first image is returned. If alpha is 1.0, a copy of
       the second image is returned. There are no restrictions on the
       alpha value. If necessary, the result is clipped to fit into
       the allowed output range.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    im1.load()
    im2.load()
    return im1._new(core.blend(im1.im, im2.im, alpha)) 
Example #5
Source File: Image.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _crop(self, im, box):
        """
        Returns a rectangular region from the core image object im.

        This is equivalent to calling im.crop((x0, y0, x1, y1)), but
        includes additional sanity checks.

        :param im: a core image object
        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
        :returns: A core image object.
        """

        x0, y0, x1, y1 = map(int, map(round, box))

        absolute_values = (abs(x1 - x0), abs(y1 - y0))

        _decompression_bomb_check(absolute_values)

        return im.crop((x0, y0, x1, y1)) 
Example #6
Source File: Image.py    From FODI with GNU General Public License v3.0 6 votes vote down vote up
def _crop(self, im, box):
        """
        Returns a rectangular region from the core image object im.

        This is equivalent to calling im.crop((x0, y0, x1, y1)), but
        includes additional sanity checks.

        :param im: a core image object
        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
        :returns: A core image object.
        """

        x0, y0, x1, y1 = map(int, map(round, box))

        absolute_values = (abs(x1 - x0), abs(y1 - y0))

        _decompression_bomb_check(absolute_values)

        return im.crop((x0, y0, x1, y1)) 
Example #7
Source File: Image.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _getencoder(mode, encoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        encoder = ENCODERS[encoder_name]
    except KeyError:
        pass
    else:
        return encoder(mode, *args + extra)

    try:
        # get encoder
        encoder = getattr(core, encoder_name + "_encoder")
    except AttributeError:
        raise OSError("encoder %s not available" % encoder_name)
    return encoder(mode, *args + extra)


# --------------------------------------------------------------------
# Simple expression analyzer 
Example #8
Source File: Image.py    From FODI with GNU General Public License v3.0 6 votes vote down vote up
def _getencoder(mode, encoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        encoder = ENCODERS[encoder_name]
    except KeyError:
        pass
    else:
        return encoder(mode, *args + extra)

    try:
        # get encoder
        encoder = getattr(core, encoder_name + "_encoder")
    except AttributeError:
        raise OSError("encoder %s not available" % encoder_name)
    return encoder(mode, *args + extra)


# --------------------------------------------------------------------
# Simple expression analyzer 
Example #9
Source File: Image.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _crop(self, im, box):
        """
        Returns a rectangular region from the core image object im.

        This is equivalent to calling im.crop((x0, y0, x1, y1)), but
        includes additional sanity checks.

        :param im: a core image object
        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
        :returns: A core image object.
        """

        x0, y0, x1, y1 = map(int, map(round, box))

        absolute_values = (abs(x1 - x0), abs(y1 - y0))

        _decompression_bomb_check(absolute_values)

        return im.crop((x0, y0, x1, y1)) 
Example #10
Source File: Image.py    From FODI with GNU General Public License v3.0 6 votes vote down vote up
def _getdecoder(mode, decoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        decoder = DECODERS[decoder_name]
    except KeyError:
        pass
    else:
        return decoder(mode, *args + extra)

    try:
        # get decoder
        decoder = getattr(core, decoder_name + "_decoder")
    except AttributeError:
        raise OSError("decoder %s not available" % decoder_name)
    return decoder(mode, *args + extra) 
Example #11
Source File: test_file_png.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_leak_load(self):
        with open('Tests/images/hopper.png', 'rb') as f:
            DATA = BytesIO(f.read(16 * 1024))

        ImageFile.LOAD_TRUNCATED_IMAGES = True
        with Image.open(DATA) as im:
            im.load()

        def core():
            with Image.open(DATA) as im:
                im.load()

        try:
            self._test_leak(core)
        finally:
            ImageFile.LOAD_TRUNCATED_IMAGES = False 
Example #12
Source File: test_image_split.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_split_open(self):
        codecs = dir(Image.core)

        if 'zip_encoder' in codecs:
            test_file = self.tempfile("temp.png")
        else:
            test_file = self.tempfile("temp.pcx")

        def split_open(mode):
            hopper(mode).save(test_file)
            im = Image.open(test_file)
            return len(im.split())
        self.assertEqual(split_open("1"), 1)
        self.assertEqual(split_open("L"), 1)
        self.assertEqual(split_open("P"), 1)
        self.assertEqual(split_open("RGB"), 3)
        if 'zip_encoder' in codecs:
            self.assertEqual(split_open("RGBA"), 4) 
Example #13
Source File: test_file_libtiff.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_gimp_tiff(self):
        # Read TIFF JPEG images from GIMP [@PIL168]

        codecs = dir(Image.core)
        if "jpeg_decoder" not in codecs:
            self.skipTest("jpeg support not available")

        filename = "Tests/images/pil168.tif"
        im = Image.open(filename)

        self.assertEqual(im.mode, "RGB")
        self.assertEqual(im.size, (256, 256))
        self.assertEqual(
            im.tile, [('jpeg', (0, 0, 256, 256), 0, ('RGB', 'jpeg', False))]
        )
        im.load()

        self.assert_image_equal_tofile(im, "Tests/images/pil168.png") 
Example #14
Source File: Image.py    From teleport with Apache License 2.0 6 votes vote down vote up
def _getencoder(mode, encoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        encoder = ENCODERS[encoder_name]
    except KeyError:
        pass
    else:
        return encoder(mode, *args + extra)

    try:
        # get encoder
        encoder = getattr(core, encoder_name + "_encoder")
    except AttributeError:
        raise OSError("encoder %s not available" % encoder_name)
    return encoder(mode, *args + extra)


# --------------------------------------------------------------------
# Simple expression analyzer 
Example #15
Source File: test_file_eps.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_render_scale1(self):
        # We need png support for these render test
        codecs = dir(Image.core)
        if "zip_encoder" not in codecs or "zip_decoder" not in codecs:
            self.skipTest("zip/deflate support not available")

        # Zero bounding box
        image1_scale1 = Image.open(file1)
        image1_scale1.load()
        image1_scale1_compare = Image.open(file1_compare).convert("RGB")
        image1_scale1_compare.load()
        self.assert_image_similar(image1_scale1, image1_scale1_compare, 5)

        # Non-Zero bounding box
        image2_scale1 = Image.open(file2)
        image2_scale1.load()
        image2_scale1_compare = Image.open(file2_compare).convert("RGB")
        image2_scale1_compare.load()
        self.assert_image_similar(image2_scale1, image2_scale1_compare, 10) 
Example #16
Source File: Image.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _crop(self, im, box):
        """
        Returns a rectangular region from the core image object im.

        This is equivalent to calling im.crop((x0, y0, x1, y1)), but
        includes additional sanity checks.

        :param im: a core image object
        :param box: The crop rectangle, as a (left, upper, right, lower)-tuple.
        :returns: A core image object.
        """

        x0, y0, x1, y1 = map(int, map(round, box))

        absolute_values = (abs(x1 - x0), abs(y1 - y0))

        _decompression_bomb_check(absolute_values)

        return im.crop((x0, y0, x1, y1)) 
Example #17
Source File: test_file_eps.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_render_scale2(self):
        # We need png support for these render test
        codecs = dir(Image.core)
        if "zip_encoder" not in codecs or "zip_decoder" not in codecs:
            self.skipTest("zip/deflate support not available")

        # Zero bounding box
        image1_scale2 = Image.open(file1)
        image1_scale2.load(scale=2)
        image1_scale2_compare = Image.open(file1_compare_scale2).convert("RGB")
        image1_scale2_compare.load()
        self.assert_image_similar(image1_scale2, image1_scale2_compare, 5)

        # Non-Zero bounding box
        image2_scale2 = Image.open(file2)
        image2_scale2.load(scale=2)
        image2_scale2_compare = Image.open(file2_compare_scale2).convert("RGB")
        image2_scale2_compare.load()
        self.assert_image_similar(image2_scale2, image2_scale2_compare, 10) 
Example #18
Source File: Image.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _getencoder(mode, encoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        encoder = ENCODERS[encoder_name]
        return encoder(mode, *args + extra)
    except KeyError:
        pass
    try:
        # get encoder
        encoder = getattr(core, encoder_name + "_encoder")
        return encoder(mode, *args + extra)
    except AttributeError:
        raise IOError("encoder %s not available" % encoder_name)


# --------------------------------------------------------------------
# Simple expression analyzer 
Example #19
Source File: Image.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _getdecoder(mode, decoder_name, args, extra=()):

    # tweak arguments
    if args is None:
        args = ()
    elif not isinstance(args, tuple):
        args = (args,)

    try:
        decoder = DECODERS[decoder_name]
        return decoder(mode, *args + extra)
    except KeyError:
        pass
    try:
        # get decoder
        decoder = getattr(core, decoder_name + "_decoder")
        return decoder(mode, *args + extra)
    except AttributeError:
        raise IOError("decoder %s not available" % decoder_name) 
Example #20
Source File: inference.py    From sagemaker-tensorflow-serving-container with Apache License 2.0 6 votes vote down vote up
def handler(data, context):
    """Handle request.

    Args:
        data (obj): the request data
        context (Context): an object containing request and configuration details

    Returns:
        (bytes, string): data to return to client, (optional) response content type
    """

    # use the imported library
    print('pillow: {}\n{}'.format(PIL.__version__, dir(_imaging)))
    processed_input = _process_input(data, context)
    response = requests.post(context.rest_uri, data=processed_input)
    return _process_output(response, context) 
Example #21
Source File: test_tiff_ifdrational.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_ifd_rational_save(self):
        methods = (True, False)
        if 'libtiff_encoder' not in dir(Image.core):
            methods = (False,)

        for libtiff in methods:
            TiffImagePlugin.WRITE_LIBTIFF = libtiff

            im = hopper()
            out = self.tempfile('temp.tiff')
            res = IFDRational(301, 1)
            im.save(out, dpi=(res, res), compression='raw')

            reloaded = Image.open(out)
            self.assertEqual(float(IFDRational(301, 1)),
                             float(reloaded.tag_v2[282])) 
Example #22
Source File: test_file_wmf.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_load_raw(self):

        # Test basic EMF open and rendering
        im = Image.open('Tests/images/drawing.emf')
        if hasattr(Image.core, "drawwmf"):
            # Currently, support for WMF/EMF is Windows-only
            im.load()
            # Compare to reference rendering
            imref = Image.open('Tests/images/drawing_emf_ref.png')
            imref.load()
            self.assert_image_similar(im, imref, 0)

        # Test basic WMF open and rendering
        im = Image.open('Tests/images/drawing.wmf')
        if hasattr(Image.core, "drawwmf"):
            # Currently, support for WMF/EMF is Windows-only
            im.load()
            # Compare to reference rendering
            imref = Image.open('Tests/images/drawing_wmf_ref.png')
            imref.load()
            self.assert_image_similar(im, imref, 2.0) 
Example #23
Source File: Image.py    From teleport with Apache License 2.0 6 votes vote down vote up
def blend(im1, im2, alpha):
    """
    Creates a new image by interpolating between two input images, using
    a constant alpha.::

        out = image1 * (1.0 - alpha) + image2 * alpha

    :param im1: The first image.
    :param im2: The second image.  Must have the same mode and size as
       the first image.
    :param alpha: The interpolation alpha factor.  If alpha is 0.0, a
       copy of the first image is returned. If alpha is 1.0, a copy of
       the second image is returned. There are no restrictions on the
       alpha value. If necessary, the result is clipped to fit into
       the allowed output range.
    :returns: An :py:class:`~PIL.Image.Image` object.
    """

    im1.load()
    im2.load()
    return im1._new(core.blend(im1.im, im2.im, alpha)) 
Example #24
Source File: Image.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def effect_noise(size, sigma):
    """
    Generate Gaussian noise centered around 128.

    :param size: The requested size in pixels, as a 2-tuple:
       (width, height).
    :param sigma: Standard deviation of noise.
    """
    return Image()._new(core.effect_noise(size, sigma)) 
Example #25
Source File: test_file_jpeg.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_sanity(self):

        # internal version number
        self.assertRegex(Image.core.jpeglib_version, r"\d+\.\d+$")

        im = Image.open(TEST_FILE)
        im.load()
        self.assertEqual(im.mode, "RGB")
        self.assertEqual(im.size, (128, 128))
        self.assertEqual(im.format, "JPEG")
        self.assertEqual(im.get_format_mimetype(), "image/jpeg") 
Example #26
Source File: Image.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def radial_gradient(mode):
    """
    Generate 256x256 radial gradient from black to white, centre to edge.

    :param mode: Input mode.
    """
    return Image()._new(core.radial_gradient(mode))


# --------------------------------------------------------------------
# Resources 
Example #27
Source File: Image.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def linear_gradient(mode):
    """
    Generate 256x256 linear gradient from black to white, top to bottom.

    :param mode: Input mode.
    """
    return Image()._new(core.linear_gradient(mode)) 
Example #28
Source File: Image.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def close(self):
        """
        Closes the file pointer, if possible.

        This operation will destroy the image core and release its memory.
        The image data will be unusable afterward.

        This function is only required to close images that have not
        had their file read and closed by the
        :py:meth:`~PIL.Image.Image.load` method. See
        :ref:`file-handling` for more information.
        """
        try:
            if hasattr(self, "_close__fp"):
                self._close__fp()
            self.fp.close()
            self.fp = None
        except Exception as msg:
            logger.debug("Error closing: %s", msg)

        if getattr(self, "map", None):
            self.map = None

        # Instead of simply setting to None, we're setting up a
        # deferred error that will better explain that the core image
        # object is gone.
        self.im = deferred_error(ValueError("Operation on closed image")) 
Example #29
Source File: Image.py    From FODI with GNU General Public License v3.0 5 votes vote down vote up
def _apply_env_variables(env=None):
    if env is None:
        env = os.environ

    for var_name, setter in [
        ("PILLOW_ALIGNMENT", core.set_alignment),
        ("PILLOW_BLOCK_SIZE", core.set_block_size),
        ("PILLOW_BLOCKS_MAX", core.set_blocks_max),
    ]:
        if var_name not in env:
            continue

        var = env[var_name].lower()

        units = 1
        for postfix, mul in [("k", 1024), ("m", 1024 * 1024)]:
            if var.endswith(postfix):
                units = mul
                var = var[: -len(postfix)]

        try:
            var = int(var) * units
        except ValueError:
            warnings.warn("{} is not int".format(var_name))
            continue

        try:
            setter(var)
        except ValueError as e:
            warnings.warn("{}: {}".format(var_name, e)) 
Example #30
Source File: Image.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _apply_env_variables(env=None):
    if env is None:
        env = os.environ

    for var_name, setter in [
        ('PILLOW_ALIGNMENT', core.set_alignment),
        ('PILLOW_BLOCK_SIZE', core.set_block_size),
        ('PILLOW_BLOCKS_MAX', core.set_blocks_max),
    ]:
        if var_name not in env:
            continue

        var = env[var_name].lower()

        units = 1
        for postfix, mul in [('k', 1024), ('m', 1024*1024)]:
            if var.endswith(postfix):
                units = mul
                var = var[:-len(postfix)]

        try:
            var = int(var) * units
        except ValueError:
            warnings.warn("{0} is not int".format(var_name))
            continue

        try:
            setter(var)
        except ValueError as e:
            warnings.warn("{0}: {1}".format(var_name, e))