Python PIL.Image.LINEAR Examples

The following are 17 code examples of PIL.Image.LINEAR(). 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: test_color_lut.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_correct_args(self):
        im = Image.new('RGB', (10, 10), 0)

        im.im.color_lut_3d('RGB', Image.LINEAR,
                           *self.generate_identity_table(3, 3))

        im.im.color_lut_3d('CMYK', Image.LINEAR,
                           *self.generate_identity_table(4, 3))

        im.im.color_lut_3d('RGB', Image.LINEAR,
                           *self.generate_identity_table(3, (2, 3, 3)))

        im.im.color_lut_3d('RGB', Image.LINEAR,
                           *self.generate_identity_table(3, (65, 3, 3)))

        im.im.color_lut_3d('RGB', Image.LINEAR,
                           *self.generate_identity_table(3, (3, 65, 3)))

        im.im.color_lut_3d('RGB', Image.LINEAR,
                           *self.generate_identity_table(3, (3, 3, 65))) 
Example #2
Source File: test_color_lut.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_wrong_mode(self):
        with self.assertRaisesRegex(ValueError, "wrong mode"):
            im = Image.new('L', (10, 10), 0)
            im.im.color_lut_3d('RGB', Image.LINEAR,
                               *self.generate_identity_table(3, 3))

        with self.assertRaisesRegex(ValueError, "wrong mode"):
            im = Image.new('RGB', (10, 10), 0)
            im.im.color_lut_3d('L', Image.LINEAR,
                               *self.generate_identity_table(3, 3))

        with self.assertRaisesRegex(ValueError, "wrong mode"):
            im = Image.new('L', (10, 10), 0)
            im.im.color_lut_3d('L', Image.LINEAR,
                               *self.generate_identity_table(3, 3))

        with self.assertRaisesRegex(ValueError, "wrong mode"):
            im = Image.new('RGB', (10, 10), 0)
            im.im.color_lut_3d('RGBA', Image.LINEAR,
                               *self.generate_identity_table(3, 3))

        with self.assertRaisesRegex(ValueError, "wrong mode"):
            im = Image.new('RGB', (10, 10), 0)
            im.im.color_lut_3d('RGB', Image.LINEAR,
                               *self.generate_identity_table(4, 3)) 
Example #3
Source File: test_color_lut.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_correct_mode(self):
        im = Image.new('RGBA', (10, 10), 0)
        im.im.color_lut_3d('RGBA', Image.LINEAR,
                           *self.generate_identity_table(3, 3))

        im = Image.new('RGBA', (10, 10), 0)
        im.im.color_lut_3d('RGBA', Image.LINEAR,
                           *self.generate_identity_table(4, 3))

        im = Image.new('RGB', (10, 10), 0)
        im.im.color_lut_3d('HSV', Image.LINEAR,
                           *self.generate_identity_table(3, 3))

        im = Image.new('RGB', (10, 10), 0)
        im.im.color_lut_3d('RGBA', Image.LINEAR,
                           *self.generate_identity_table(4, 3)) 
Example #4
Source File: test_color_lut.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_channels_order(self):
        g = Image.linear_gradient('L')
        im = Image.merge('RGB', [g, g.transpose(Image.ROTATE_90),
                                 g.transpose(Image.ROTATE_180)])

        # Reverse channels by splitting and using table
        self.assert_image_equal(
            Image.merge('RGB', im.split()[::-1]),
            im._new(im.im.color_lut_3d('RGB', Image.LINEAR,
                    3, 2, 2, 2, [
                        0, 0, 0,  0, 0, 1,
                        0, 1, 0,  0, 1, 1,

                        1, 0, 0,  1, 0, 1,
                        1, 1, 0,  1, 1, 1,
                    ]))) 
Example #5
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 #6
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 #7
Source File: spatial_transforms.py    From GAN_Review with MIT License 5 votes vote down vote up
def __init__(self, size, scale_ratios, fix_crop=True, more_fix_crop=True, max_distort=1,
                 interpolation=Image.LINEAR):
        self.height = size[0]
        self.width = size[1]
        self.scale_ratios = scale_ratios
        self.fix_crop = fix_crop
        self.more_fix_crop = more_fix_crop
        self.max_distort = max_distort
        self.interpolation = interpolation

        self._crop_scale = None
        self._crop_offset = None
        self._num_scales = len(scale_ratios)
        self._num_offsets = 5 if not more_fix_crop else 13 
Example #8
Source File: spatial_transforms.py    From GAN_Review with MIT License 5 votes vote down vote up
def resize(img, size):
    if not isinstance(size, (list, tuple)):
        size = (size, size)
    if isinstance(img, np.ndarray):
        return cv2.resize(img, size)
    return img.resize(size, Image.LINEAR) 
Example #9
Source File: resize.py    From open_model_zoo with Apache License 2.0 5 votes vote down vote up
def parameters(cls):
        parameters = super().parameters()
        parameters.update({
            'size': NumberField(
                value_type=int, optional=True, min_value=1, description="Destination sizes for both dimensions."
            ),
            'dst_width': NumberField(
                value_type=int, optional=True, min_value=1, description="Destination width for image resizing."
            ),
            'dst_height': NumberField(
                value_type=int, optional=True, min_value=1, description="Destination height for image resizing."
            ),
            'aspect_ratio_scale': StringField(
                choices=ASPECT_RATIO_SCALE, optional=True,
                description="Allows save image aspect ratio using one of these ways: "
                            "{}".format(', '.join(ASPECT_RATIO_SCALE))
            ),
            'interpolation': StringField(
                choices=_Resizer.all_provided_interpolations(), optional=True, default='LINEAR',
                description="Specifies method that will be used."
            ),
            'use_pillow': BoolField(
                optional=True, default=False,
                description="Parameter specifies usage of Pillow library for resizing."
            ),
            'use_tensorflow': BoolField(
                optional=True,
                description="Specifies usage of TensorFlow Image for resizing. Requires TensorFlow installation."
            ),
            'resize_realization': StringField(
                optional=True, choices=_Resizer.providers,
                description="Parameter specifies functionality of which library will be used for resize: "
                            "{}".format(', '.join(_Resizer.providers))
            )
        })

        return parameters 
Example #10
Source File: transform.py    From detectron2 with Apache License 2.0 5 votes vote down vote up
def __init__(self, src_rect, output_size, interp=Image.LINEAR, fill=0):
        """
        Args:
            src_rect (x0, y0, x1, y1): src coordinates
            output_size (h, w): dst image size
            interp: PIL interpolation methods
            fill: Fill color used when src_rect extends outside image
        """
        super().__init__()
        self._set_attributes(locals()) 
Example #11
Source File: transform.py    From detectron2 with Apache License 2.0 5 votes vote down vote up
def __init__(self, src_rect, output_size, interp=Image.LINEAR, fill=0):
        """
        Args:
            src_rect (x0, y0, x1, y1): src coordinates
            output_size (h, w): dst image size
            interp: PIL interpolation methods
            fill: Fill color used when src_rect extends outside image
        """
        super().__init__()
        self._set_attributes(locals()) 
Example #12
Source File: resize_images.py    From imagenet-fast with Apache License 2.0 5 votes vote down vote up
def resize_img(fname, targ, path, new_path):
    dest = os.path.join(path,new_path,str(targ),fname)
    if os.path.exists(dest): return
    im = Image.open(os.path.join(path, fname)).convert('RGB')
    r,c = im.size
    ratio = targ/min(r,c)
    sz = (scale_to(r, ratio, targ), scale_to(c, ratio, targ))
    os.makedirs(os.path.split(dest)[0], exist_ok=True)
    im.resize(sz, Image.LINEAR).save(dest) 
Example #13
Source File: test_color_lut.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_overflow(self):
        g = Image.linear_gradient('L')
        im = Image.merge('RGB', [g, g.transpose(Image.ROTATE_90),
                                 g.transpose(Image.ROTATE_180)])

        transformed = im._new(im.im.color_lut_3d('RGB', Image.LINEAR,
                              3, 2, 2, 2,
                              [
                                  -1, -1, -1,   2, -1, -1,
                                  -1,  2, -1,   2,  2, -1,

                                  -1, -1,  2,   2, -1,  2,
                                  -1,  2,  2,   2,  2,  2,
                              ])).load()
        self.assertEqual(transformed[0, 0], (0, 0, 255))
        self.assertEqual(transformed[50, 50], (0, 0, 255))
        self.assertEqual(transformed[255, 0], (0, 255, 255))
        self.assertEqual(transformed[205, 50], (0, 255, 255))
        self.assertEqual(transformed[0, 255], (255, 0, 0))
        self.assertEqual(transformed[50, 205], (255, 0, 0))
        self.assertEqual(transformed[255, 255], (255, 255, 0))
        self.assertEqual(transformed[205, 205], (255, 255, 0))

        transformed = im._new(im.im.color_lut_3d('RGB', Image.LINEAR,
                              3, 2, 2, 2,
                              [
                                  -3, -3, -3,   5, -3, -3,
                                  -3,  5, -3,   5,  5, -3,

                                  -3, -3,  5,   5, -3,  5,
                                  -3,  5,  5,   5,  5,  5,
                              ])).load()
        self.assertEqual(transformed[0, 0], (0, 0, 255))
        self.assertEqual(transformed[50, 50], (0, 0, 255))
        self.assertEqual(transformed[255, 0], (0, 255, 255))
        self.assertEqual(transformed[205, 50], (0, 255, 255))
        self.assertEqual(transformed[0, 255], (255, 0, 0))
        self.assertEqual(transformed[50, 205], (255, 0, 0))
        self.assertEqual(transformed[255, 255], (255, 255, 0))
        self.assertEqual(transformed[205, 205], (255, 255, 0)) 
Example #14
Source File: test_color_lut.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_copy_alpha_channel(self):
        g = Image.linear_gradient('L')
        im = Image.merge('RGBA', [g, g.transpose(Image.ROTATE_90),
                                  g.transpose(Image.ROTATE_180),
                                  g.transpose(Image.ROTATE_270)])

        self.assert_image_equal(im, im._new(
            im.im.color_lut_3d('RGBA', Image.LINEAR,
                               *self.generate_identity_table(3, 17)))) 
Example #15
Source File: test_color_lut.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_identities(self):
        g = Image.linear_gradient('L')
        im = Image.merge('RGB', [g, g.transpose(Image.ROTATE_90),
                                 g.transpose(Image.ROTATE_180)])

        # Fast test with small cubes
        for size in [2, 3, 5, 7, 11, 16, 17]:
            self.assert_image_equal(im, im._new(
                im.im.color_lut_3d('RGB', Image.LINEAR,
                                   *self.generate_identity_table(3, size))))

        # Not so fast
        self.assert_image_equal(im, im._new(
            im.im.color_lut_3d('RGB', Image.LINEAR,
                               *self.generate_identity_table(3, (2, 2, 65))))) 
Example #16
Source File: transfer_learning.py    From ModelZoo with Apache License 2.0 4 votes vote down vote up
def fill_samples_and_labels(self, img_idx, samples_np, labels_np):
        img_db = self.roi_db[ img_idx] 
        # load and process the image using PIL
        img_num_rois = img_db['num_gt']
        img = PascalImage(img_db['img_file'], 
                          img_db['bb'][:img_num_rois, :],
                          np.squeeze(img_db['gt_classes'][:img_num_rois, :], axis=1))
            
        debug("\n============== Processing: Image {} ({}), Shape:{}, #ROIs: {}={} =================".format(img_idx, img.file_name,
                                     img.shape, img_num_rois, img.labels))
        patches = {}
        p_id_base = 0
        for scale_idx, scale in enumerate(self.multi_scales):
            p_id_base = img.compute_patches_at_scale( scale_idx, scale, p_id_base)
            if p_id_base >= self.samples_per_img and scale_idx > 9:
                break

        debug("Sampled. # Non-BG patches:{} # BG patches:{}".format( 
            len(img.non_background_patches), len(img.background_patches)))
        
        # over-represent the non-background patches during training
        all_patches = self.resample_patches(img)

        assert len(all_patches) == self.samples_per_img
        shuf_idx = self.be.rng.permutation(self.samples_per_img)
        for i in range(self.samples_per_img):
            p_idx = shuf_idx[i]
            p = all_patches[p_idx]
            p_img = img.pil.crop([int(b) for b in p.bbox])
            p_img = p_img.resize( (self.sample_height, self.sample_height), Image.LINEAR)
            if DEBUG and False:
                debug_file_path = '{}_{}.jpg'.format( img.debug_file_path_prefix, p_idx)
                p_img.save(debug_file_path)
                
            # load it to numpy and flip the channel RGB to BGR
            p_img_np = np.array(p_img)[:, :, ::-1]
            # Mean subtract and scale an image
            p_img_np = p_img_np.astype(np.float32, copy=False)
            p_img_np -= FRCN_PIXEL_MEANS
            samples_np[:, :, :, i] = p_img_np.transpose(FRCN_IMG_DIM_SWAP)
                
            labels_np[i] = p.label
            
        return 
Example #17
Source File: test_color_lut.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_wrong_args(self):
        im = Image.new('RGB', (10, 10), 0)

        with self.assertRaisesRegex(ValueError, "filter"):
            im.im.color_lut_3d('RGB',
                               Image.CUBIC,
                               *self.generate_identity_table(3, 3))

        with self.assertRaisesRegex(ValueError, "image mode"):
            im.im.color_lut_3d('wrong',
                               Image.LINEAR,
                               *self.generate_identity_table(3, 3))

        with self.assertRaisesRegex(ValueError, "table_channels"):
            im.im.color_lut_3d('RGB',
                               Image.LINEAR,
                               *self.generate_identity_table(5, 3))

        with self.assertRaisesRegex(ValueError, "table_channels"):
            im.im.color_lut_3d('RGB',
                               Image.LINEAR,
                               *self.generate_identity_table(1, 3))

        with self.assertRaisesRegex(ValueError, "table_channels"):
            im.im.color_lut_3d('RGB',
                               Image.LINEAR,
                               *self.generate_identity_table(2, 3))

        with self.assertRaisesRegex(ValueError, "Table size"):
            im.im.color_lut_3d('RGB',
                               Image.LINEAR,
                               *self.generate_identity_table(3, (1, 3, 3)))

        with self.assertRaisesRegex(ValueError, "Table size"):
            im.im.color_lut_3d('RGB',
                               Image.LINEAR,
                               *self.generate_identity_table(3, (66, 3, 3)))

        with self.assertRaisesRegex(ValueError, r"size1D \* size2D \* size3D"):
            im.im.color_lut_3d('RGB',
                               Image.LINEAR,
                               3, 2, 2, 2, [0, 0, 0] * 7)

        with self.assertRaisesRegex(ValueError, r"size1D \* size2D \* size3D"):
            im.im.color_lut_3d('RGB',
                               Image.LINEAR,
                               3, 2, 2, 2, [0, 0, 0] * 9)

        with self.assertRaises(TypeError):
            im.im.color_lut_3d('RGB',
                               Image.LINEAR,
                               3, 2, 2, 2, [0, 0, "0"] * 8)

        with self.assertRaises(TypeError):
            im.im.color_lut_3d('RGB',
                               Image.LINEAR,
                               3, 2, 2, 2, 16)