Python PIL.Image.BOX Examples

The following are 25 code examples of PIL.Image.BOX(). 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: resize.py    From open_model_zoo with Apache License 2.0 6 votes vote down vote up
def supported_interpolations(cls):
        if Image is None:
            return {}
        intrp = {
            'NEAREST': Image.NEAREST,
            'NONE': Image.NONE,
            'BILINEAR': Image.BILINEAR,
            'LINEAR': Image.LINEAR,
            'BICUBIC': Image.BICUBIC,
            'CUBIC': Image.CUBIC,
            'ANTIALIAS': Image.ANTIALIAS
        }
        try:
            optional_interpolations = {
                'BOX': Image.BOX,
                'LANCZOS': Image.LANCZOS,
                'HAMMING': Image.HAMMING,
            }
            intrp.update(optional_interpolations)
        except AttributeError:
            pass
        return intrp 
Example #2
Source File: resize.py    From open_model_zoo with Apache License 2.0 6 votes vote down vote up
def __init__(self, interpolation):
        if Image is None:
            raise ImportError(
                'pillow backend for resize operation requires TensorFlow. Please install it before usage.'
            )
        self._supported_interpolations = {
            'NEAREST': Image.NEAREST,
            'NONE': Image.NONE,
            'BILINEAR': Image.BILINEAR,
            'LINEAR': Image.LINEAR,
            'BICUBIC': Image.BICUBIC,
            'CUBIC': Image.CUBIC,
            'ANTIALIAS': Image.ANTIALIAS,
        }
        try:
            optional_interpolations = {
                'BOX': Image.BOX,
                'LANCZOS': Image.LANCZOS,
                'HAMMING': Image.HAMMING,
            }
            self._supported_interpolations.update(optional_interpolations)
        except AttributeError:
            pass
        super().__init__(interpolation) 
Example #3
Source File: image.py    From pliers with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, size, maintain_aspect_ratio=False, resample='bicubic'):
        self.size = size
        self.maintain_aspect_ratio = maintain_aspect_ratio
        resampling_mapping = {
            'nearest': Image.NEAREST,
            'bilinear': Image.BILINEAR,
            'bicubic': Image.BICUBIC,
            'lanczos': Image.LANCZOS,
            'box': Image.BOX,
            'hamming': Image.HAMMING,
        }
        if resample.lower() not in resampling_mapping.keys():
            raise ValueError(
                "Unknown resampling method '{}'. Allowed values are '{}'"
                .format(resample, "', '".join(resampling_mapping.keys())))
        self.resample = resampling_mapping[resample]
        super().__init__() 
Example #4
Source File: test_image_resample.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_subsample(self):
        # This test shows advantages of the subpixel resizing
        # after supersampling (e.g. during JPEG decoding).
        im = Image.open("Tests/images/flower.jpg")
        self.assertEqual(im.size, (480, 360))
        dst_size = (48, 36)
        # Reference is cropped image resized to destination
        reference = im.crop((0, 0, 473, 353)).resize(dst_size, Image.BICUBIC)
        # Image.BOX emulates supersampling (480 / 8 = 60, 360 / 8 = 45)
        supersampled = im.resize((60, 45), Image.BOX)

        with_box = supersampled.resize(dst_size, Image.BICUBIC,
                                       (0, 0, 59.125, 44.125))
        without_box = supersampled.resize(dst_size, Image.BICUBIC)

        # error with box should be much smaller than without
        self.assert_image_similar(reference, with_box, 6)
        with self.assertRaisesRegex(AssertionError, r"difference 29\."):
            self.assert_image_similar(reference, without_box, 5) 
Example #5
Source File: test_image_resize.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_reduce_filters(self):
        for f in [Image.NEAREST, Image.BOX, Image.BILINEAR,
                  Image.HAMMING, Image.BICUBIC, Image.LANCZOS]:
            r = self.resize(hopper("RGB"), (15, 12), f)
            self.assertEqual(r.mode, "RGB")
            self.assertEqual(r.size, (15, 12)) 
Example #6
Source File: pil_backend.py    From nnabla with Apache License 2.0 5 votes vote down vote up
def __init__(self):
        ImageUtilsBackend.__init__(self)
        if hasattr(Image, "HAMMING"):  # version >3.4.0
            self._interpolations_map["hamming"] = Image.HAMMING

        if hasattr(Image, "BOX"):  # version >3.4.0
            self._interpolations_map["box"] = Image.BOX

        if hasattr(Image, "LANCZOS"):  # version >1.1.3
            self._interpolations_map["lanczos"] = Image.LANCZOS 
Example #7
Source File: perturbation.py    From alibi-detect with Apache License 2.0 5 votes vote down vote up
def pixelate(x: np.ndarray, strength: float, xrange: tuple = None) -> np.ndarray:
    """
    Change coarseness of pixels for an image.

    Parameters
    ----------
    x
        Instance to be perturbed.
    strength
        Strength of pixelation (<1). Lower is actually more pixelated.
    xrange
        Tuple with min and max data range.

    Returns
    -------
    Perturbed instance.
    """
    rows, cols = x.shape[:2]

    if not isinstance(xrange, tuple):
        xrange = (x.min(), x.max())

    if xrange[0] != 0 or xrange[1] != 255:
        x = (x - xrange[0]) / (xrange[1] - xrange[0]) * 255

    im = Image.fromarray(x.astype('uint8'), mode='RGB')
    im = im.resize((int(rows * strength), int(cols * strength)), Image.BOX)
    im = im.resize((rows, cols), Image.BOX)
    x_pi = np.array(im, dtype=np.float32) / 255
    x_pi = x_pi * (xrange[1] - xrange[0]) + xrange[0]
    return x_pi 
Example #8
Source File: convert.py    From color-filters-reconstruction with MIT License 5 votes vote down vote up
def normalize_raw(im, imsize, scale=8):
    cropsize = imsize * scale * 2
    assert im.width >= cropsize, "image is too small"
    assert im.height >= cropsize, "image is too small"

    wpad = (im.width - cropsize) // 2
    hpad = (im.height - cropsize) // 2
    if scale == 8:
        im = im.crop((wpad-2, hpad-2, wpad+2 + cropsize, hpad+2 + cropsize))
        im = im.resize((im.width // 4, im.height // 4), Image.BOX)
        im = im.resize((imsize * 2, imsize * 2), Image.NEAREST)
    else:
        im = im.crop((wpad, hpad, wpad + cropsize, hpad + cropsize))
        im = im.resize((imsize * 2, imsize * 2), Image.BOX)
    return im 
Example #9
Source File: corruptions.py    From imagecorruptions with Apache License 2.0 5 votes vote down vote up
def pixelate(x, severity=1):
    c = [0.6, 0.5, 0.4, 0.3, 0.25][severity - 1]

    x_shape = np.array(x).shape

    x = x.resize((int(x_shape[1] * c), int(x_shape[0] * c)), Image.BOX)

    x = x.resize((x_shape[1], x_shape[0]), Image.NEAREST)

    return x


# mod of https://gist.github.com/erniejunior/601cdf56d2b424757de5 
Example #10
Source File: test_image_resize.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_endianness(self):
        # Make an image with one colored pixel, in one channel.
        # When resized, that channel should be the same as a GS image.
        # Other channels should be unaffected.
        # The R and A channels should not swap, which is indicative of
        # an endianness issues.

        samples = {
            'blank': Image.new('L', (2, 2), 0),
            'filled': Image.new('L', (2, 2), 255),
            'dirty': Image.new('L', (2, 2), 0),
        }
        samples['dirty'].putpixel((1, 1), 128)

        for f in [Image.NEAREST, Image.BOX, Image.BILINEAR,
                  Image.HAMMING, Image.BICUBIC, Image.LANCZOS]:
            # samples resized with current filter
            references = {
                name: self.resize(ch, (4, 4), f)
                for name, ch in samples.items()
            }

            for mode, channels_set in [
                ('RGB', ('blank', 'filled', 'dirty')),
                ('RGBA', ('blank', 'blank', 'filled', 'dirty')),
                ('LA', ('filled', 'dirty')),
            ]:
                for channels in set(permutations(channels_set)):
                    # compile image from different channels permutations
                    im = Image.merge(mode, [samples[ch] for ch in channels])
                    resized = self.resize(im, (4, 4), f)

                    for i, ch in enumerate(resized.split()):
                        # check what resized channel in image is the same
                        # as separately resized channel
                        self.assert_image_equal(ch, references[channels[i]]) 
Example #11
Source File: test_image_resize.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_enlarge_filters(self):
        for f in [Image.NEAREST, Image.BOX, Image.BILINEAR,
                  Image.HAMMING, Image.BICUBIC, Image.LANCZOS]:
            r = self.resize(hopper("RGB"), (212, 195), f)
            self.assertEqual(r.mode, "RGB")
            self.assertEqual(r.size, (212, 195)) 
Example #12
Source File: corruptions.py    From robustness with Apache License 2.0 5 votes vote down vote up
def pixelate(x, severity=1):
    c = [0.6, 0.5, 0.4, 0.3, 0.25][severity - 1]

    x = x.resize((int(224 * c), int(224 * c)), PILImage.BOX)
    x = x.resize((224, 224), PILImage.BOX)

    return x


# mod of https://gist.github.com/erniejunior/601cdf56d2b424757de5 
Example #13
Source File: test_image_resample.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_wrong_arguments(self):
        im = hopper()
        for resample in (Image.NEAREST, Image.BOX, Image.BILINEAR,
                         Image.HAMMING, Image.BICUBIC, Image.LANCZOS):
            im.resize((32, 32), resample, (0, 0, im.width, im.height))
            im.resize((32, 32), resample, (20, 20, im.width, im.height))
            im.resize((32, 32), resample, (20, 20, 20, 100))
            im.resize((32, 32), resample, (20, 20, 100, 20))

            with self.assertRaisesRegex(TypeError,
                                        "must be sequence of length 4"):
                im.resize((32, 32), resample, (im.width, im.height))

            with self.assertRaisesRegex(ValueError, "can't be negative"):
                im.resize((32, 32), resample, (-20, 20, 100, 100))
            with self.assertRaisesRegex(ValueError, "can't be negative"):
                im.resize((32, 32), resample, (20, -20, 100, 100))

            with self.assertRaisesRegex(ValueError, "can't be empty"):
                im.resize((32, 32), resample, (20.1, 20, 20, 100))
            with self.assertRaisesRegex(ValueError, "can't be empty"):
                im.resize((32, 32), resample, (20, 20.1, 100, 20))
            with self.assertRaisesRegex(ValueError, "can't be empty"):
                im.resize((32, 32), resample, (20.1, 20.1, 20, 20))

            with self.assertRaisesRegex(ValueError, "can't exceed"):
                im.resize((32, 32), resample, (0, 0, im.width + 1, im.height))
            with self.assertRaisesRegex(ValueError, "can't exceed"):
                im.resize((32, 32), resample, (0, 0, im.width, im.height + 1)) 
Example #14
Source File: test_image_resample.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_dirty_pixels_rgba(self):
        case = self.make_dirty_case('RGBA', (255, 255, 0, 128), (0, 0, 255, 0))
        self.run_dirty_case(case.resize((20, 20), Image.BOX), (255, 255, 0))
        self.run_dirty_case(case.resize((20, 20), Image.BILINEAR),
                            (255, 255, 0))
        self.run_dirty_case(case.resize((20, 20), Image.HAMMING),
                            (255, 255, 0))
        self.run_dirty_case(case.resize((20, 20), Image.BICUBIC),
                            (255, 255, 0))
        self.run_dirty_case(case.resize((20, 20), Image.LANCZOS),
                            (255, 255, 0)) 
Example #15
Source File: test_image_resample.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_levels_la(self):
        case = self.make_levels_case('LA')
        self.run_levels_case(case.resize((512, 32), Image.BOX))
        self.run_levels_case(case.resize((512, 32), Image.BILINEAR))
        self.run_levels_case(case.resize((512, 32), Image.HAMMING))
        self.run_levels_case(case.resize((512, 32), Image.BICUBIC))
        self.run_levels_case(case.resize((512, 32), Image.LANCZOS)) 
Example #16
Source File: test_image_resample.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_levels_rgba(self):
        case = self.make_levels_case('RGBA')
        self.run_levels_case(case.resize((512, 32), Image.BOX))
        self.run_levels_case(case.resize((512, 32), Image.BILINEAR))
        self.run_levels_case(case.resize((512, 32), Image.HAMMING))
        self.run_levels_case(case.resize((512, 32), Image.BICUBIC))
        self.run_levels_case(case.resize((512, 32), Image.LANCZOS)) 
Example #17
Source File: test_image_resample.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_enlarge_box(self):
        for mode in ['RGBX', 'RGB', 'La', 'L']:
            case = self.make_case(mode, (2, 2), 0xe1)
            case = case.resize((4, 4), Image.BOX)
            data = ('e1 e1'
                    'e1 e1')
            for channel in case.split():
                self.check_case(channel, self.make_sample(data, (4, 4))) 
Example #18
Source File: test_image_resample.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_reduce_box(self):
        for mode in ['RGBX', 'RGB', 'La', 'L']:
            case = self.make_case(mode, (8, 8), 0xe1)
            case = case.resize((4, 4), Image.BOX)
            data = ('e1 e1'
                    'e1 e1')
            for channel in case.split():
                self.check_case(channel, self.make_sample(data, (4, 4))) 
Example #19
Source File: make_imagenet_c_inception.py    From robustness with Apache License 2.0 5 votes vote down vote up
def pixelate(x, severity=1):
    c = [0.5, 0.4, 0.3, 0.25, 0.2][severity - 1]

    x = x.resize((int(299 * c), int(299 * c)), PILImage.BOX)
    x = x.resize((299, 299), PILImage.BOX)

    return x


# mod of https://gist.github.com/erniejunior/601cdf56d2b424757de5 
Example #20
Source File: make_tinyimagenet_c.py    From robustness with Apache License 2.0 5 votes vote down vote up
def pixelate(x, severity=1):
    c = [0.9, 0.8, 0.7, 0.6, 0.5][severity - 1]

    x = x.resize((int(64 * c), int(64 * c)), PILImage.BOX)
    x = x.resize((64, 64), PILImage.BOX)

    return x


# mod of https://gist.github.com/erniejunior/601cdf56d2b424757de5 
Example #21
Source File: make_cifar_c.py    From robustness with Apache License 2.0 5 votes vote down vote up
def pixelate(x, severity=1):
    c = [0.95, 0.9, 0.85, 0.75, 0.65][severity - 1]

    x = x.resize((int(32 * c), int(32 * c)), PILImage.BOX)
    x = x.resize((32, 32), PILImage.BOX)

    return x


# mod of https://gist.github.com/erniejunior/601cdf56d2b424757de5 
Example #22
Source File: make_imagenet_c.py    From robustness with Apache License 2.0 5 votes vote down vote up
def pixelate(x, severity=1):
    c = [0.6, 0.5, 0.4, 0.3, 0.25][severity - 1]

    x = x.resize((int(224 * c), int(224 * c)), PILImage.BOX)
    x = x.resize((224, 224), PILImage.BOX)

    return x


# mod of https://gist.github.com/erniejunior/601cdf56d2b424757de5 
Example #23
Source File: multimedia.py    From chepy with GNU General Public License v3.0 4 votes vote down vote up
def resize_image(
        self,
        width: int,
        height: int,
        extension: str = "png",
        resample: str = "nearest",
        quality: int = 100,
    ):
        """Resize an image. 
        
        Args:
            width (int): Required. Width in pixels
            height (int): Required. Height in pixels
            extension (str, optional): File extension of loaded image. Defaults to png
            resample (str, optional): Resample rate. Defaults to "nearest".
            quality (int, optional): Quality of output. Defaults to 100.
        
        Returns:
            Chepy: The Chepy object. 

        Examples:
            >>> c = Chepy("image.png").load_file().resize_image(256, 256, "png")
            >>> c.write_to_file("/path/to/file.png", as_binary=True)
        """
        fh = io.BytesIO()
        if resample == "nearest":
            resample = Image.NEAREST
        elif resample == "antialias":
            resample = Image.ANTIALIAS
        elif resample == "bilinear":
            resample = Image.BILINEAR
        elif resample == "box":
            resample = Image.BOX
        elif resample == "hamming":
            resample = Image.HAMMING
        else:  # pragma: no cover
            raise TypeError(
                "Valid resampling options are: nearest, antialias, bilinear, box and hamming"
            )
        image = Image.open(self._load_as_file())
        resized = image.resize((width, height), resample=resample)
        resized.save(fh, extension, quality=quality)
        self.state = fh.getvalue()
        return self 
Example #24
Source File: resize.py    From dsod.pytorch with MIT License 4 votes vote down vote up
def resize(img, boxes, size, max_size=1000, random_interpolation=False):
    '''Resize the input PIL image to given size.

    If boxes is not None, resize boxes accordingly.

    Args:
      img: (PIL.Image) image to be resized.
      boxes: (tensor) object boxes, sized [#obj,4].
      size: (tuple or int)
        - if is tuple, resize image to the size.
        - if is int, resize the shorter side to the size while maintaining the aspect ratio.
      max_size: (int) when size is int, limit the image longer size to max_size.
                This is essential to limit the usage of GPU memory.
      random_interpolation: (bool) randomly choose a resize interpolation method.

    Returns:
      img: (PIL.Image) resized image.
      boxes: (tensor) resized boxes.

    Example:
    >> img, boxes = resize(img, boxes, 600)  # resize shorter side to 600
    >> img, boxes = resize(img, boxes, (500,600))  # resize image size to (500,600)
    >> img, _ = resize(img, None, (500,600))  # resize image only
    '''
    w, h = img.size
    if isinstance(size, int):
        size_min = min(w,h)
        size_max = max(w,h)
        sw = sh = float(size) / size_min
        if sw * size_max > max_size:
            sw = sh = float(max_size) / size_max
        ow = int(w * sw + 0.5)
        oh = int(h * sh + 0.5)
    else:
        ow, oh = size
        sw = float(ow) / w
        sh = float(oh) / h

    method = random.choice([
        Image.BOX,
        Image.NEAREST,
        Image.HAMMING,
        Image.BICUBIC,
        Image.LANCZOS,
        Image.BILINEAR]) if random_interpolation else Image.BILINEAR
    img = img.resize((ow,oh), method)
    if boxes is not None:
        boxes = boxes * torch.Tensor([sw,sh,sw,sh])
    return img, boxes 
Example #25
Source File: resize.py    From torchcv with MIT License 4 votes vote down vote up
def resize(img, boxes, size, max_size=1000, random_interpolation=False):
    '''Resize the input PIL image to given size.

    If boxes is not None, resize boxes accordingly.

    Args:
      img: (PIL.Image) image to be resized.
      boxes: (tensor) object boxes, sized [#obj,4].
      size: (tuple or int)
        - if is tuple, resize image to the size.
        - if is int, resize the shorter side to the size while maintaining the aspect ratio.
      max_size: (int) when size is int, limit the image longer size to max_size.
                This is essential to limit the usage of GPU memory.
      random_interpolation: (bool) randomly choose a resize interpolation method.

    Returns:
      img: (PIL.Image) resized image.
      boxes: (tensor) resized boxes.

    Example:
    >> img, boxes = resize(img, boxes, 600)  # resize shorter side to 600
    >> img, boxes = resize(img, boxes, (500,600))  # resize image size to (500,600)
    >> img, _ = resize(img, None, (500,600))  # resize image only
    '''
    w, h = img.size
    if isinstance(size, int):
        size_min = min(w,h)
        size_max = max(w,h)
        sw = sh = float(size) / size_min
        if sw * size_max > max_size:
            sw = sh = float(max_size) / size_max
        ow = int(w * sw + 0.5)
        oh = int(h * sh + 0.5)
    else:
        ow, oh = size
        sw = float(ow) / w
        sh = float(oh) / h

    method = random.choice([
        Image.BOX,
        Image.NEAREST,
        Image.HAMMING,
        Image.BICUBIC,
        Image.LANCZOS,
        Image.BILINEAR]) if random_interpolation else Image.BILINEAR
    img = img.resize((ow,oh), method)
    if boxes is not None:
        boxes = boxes * torch.tensor([sw,sh,sw,sh])
    return img, boxes