Python PIL.Image.LANCZOS Examples

The following are 30 code examples of PIL.Image.LANCZOS(). 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: download_hpa.py    From kaggle-human-protein-atlas-image-classification with Apache License 2.0 8 votes vote down vote up
def download(pid, image_list, base_url, save_dir, image_size=(512, 512)):
    colors = ['red', 'green', 'blue', 'yellow']
    for i in tqdm(image_list, postfix=pid):
        img_id = i.split('_', 1)
        for color in colors:
            img_path = img_id[0] + '/' + img_id[1] + '_' + color + '.jpg'
            img_name = i + '_' + color + '.png'
            img_url = base_url + img_path

            # Get the raw response from the url
            r = requests.get(img_url, allow_redirects=True, stream=True)
            r.raw.decode_content = True

            # Use PIL to resize the image and to convert it to L
            # (8-bit pixels, black and white)
            im = Image.open(r.raw)
            im = im.resize(image_size, Image.LANCZOS).convert('L')
            im.save(os.path.join(save_dir, img_name), 'PNG') 
Example #2
Source File: save_shapenet_data.py    From versa with MIT License 7 votes vote down vote up
def load_pngs(input_dir, data, size):
    items = get_subdirs(input_dir)
    for item_index, item in enumerate(items):
        print(item)
        item_images = []
        instances = []
        # There are 36 generated orientations for each item
        for i in range(0, 36):
            instances.append("{0:02d}.png".format(i))

        for instance_index, instance in enumerate(instances):
            im = Image.open(os.path.join(item, instance))
            if size:
                im = im.resize((size, size), resample=Image.LANCZOS)
            image = np.array(im.getdata()).astype('float32').reshape(size, size) / 255.  # grayscale image
            item_images.append((image, item_index, instance_index))

        data.append(item_images)

    return data 
Example #3
Source File: image_manipulation.py    From self_driving_pi_car with MIT License 6 votes vote down vote up
def top_bottom_cut(input_image):
    """
    Cut off randomly part
    of the top and bottom of
    input_image and reshape it to the original dimensions

    :param input_image: image
    :type input_image: numpy.ndarray
    :return: cropped image
    :rtype: numpy.ndarray
    """
    height = input_image.shape[0]
    width = input_image.shape[1]
    input_dtype = input_image.dtype
    top = int(np.random.uniform(.325, .425) * height)
    bottom = int(np.random.uniform(.075, .175) * height)
    input_image = input_image[top:-bottom, :]
    img = Image.fromarray(input_image)
    img = img.resize((width, height), Image.LANCZOS)
    cut_image = np.array(img).astype(input_dtype)
    return cut_image 
Example #4
Source File: create_svhn_dataset.py    From see with GNU General Public License v3.0 6 votes vote down vote up
def adjust_house_number_crop(self, crop, bbox):
        max_size = int(self.image_size * self.max_size_per_number)
        if crop.width <= max_size and crop.height <= max_size:
            return crop, bbox

        new_height, new_width = max_size, max_size
        if crop.width < max_size:
            new_width = crop.width
        if crop.height < max_size:
            new_height = crop.height

        crop = crop.resize((new_width, new_height), Image.LANCZOS)
        bbox.width = new_width
        bbox.height = new_height

        return crop, bbox 
Example #5
Source File: thumbnail.py    From zou with GNU Affero General Public License v3.0 6 votes vote down vote up
def turn_into_thumbnail(file_path, size=None):
    """
    Turn given picture into a smaller version.
    """
    im = Image.open(file_path)

    if size is not None:
        (width, height) = size

        if height == 0:
            size = get_full_size_from_width(im, width)
        else:
            im = prepare_image_for_thumbnail(im, size)
    else:
        size = im.size

    im = im.resize(size, Image.LANCZOS)
    if im.mode == "CMYK":
        im = im.convert("RGB")
    im.save(file_path, "PNG")
    return file_path 
Example #6
Source File: image.py    From sticker-finder with MIT License 6 votes vote down vote up
def preprocess_image(image):
    return image


# def preprocess_image(image):
#    """Preprocessing the Image for tesseract."""
#    # Upscale an image x2
#    image = image.resize((4*image.size[0], 4*image.size[1]), resample=Image.LANCZOS)
#    image = np.array(image)
#    image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#    kernel = np.ones((1, 1), np.uint8)
#    image = cv2.dilate(image, kernel, iterations=1)
#    image = cv2.erode(image, kernel, iterations=1)
#    image = cv2.GaussianBlur(image, (5, 5), 0)
#
#    return image 
Example #7
Source File: quote.py    From sketal with MIT License 6 votes vote down vote up
def __init__(self, *commands, prefixes=None, strict=False):
        """Answers with image containing stylish quote."""

        if not commands:
            commands = ("цитата",)

        super().__init__(*commands, prefixes=prefixes, strict=strict)

        self.q = Image.open(self.get_path("q.png")).resize((40, 40), Image.LANCZOS)
        self.qf = self.q.copy().transpose(Image.FLIP_LEFT_RIGHT).transpose(Image.FLIP_TOP_BOTTOM)

        self.f = ImageFont.truetype(self.get_path("font.ttf"), 24)
        self.fs = ImageFont.truetype(self.get_path("font.ttf"), 16)
        self.fss = ImageFont.truetype(self.get_path("font.ttf"), 15)

        example = self.command_example()
        self.description = [f"Генератор цитат",
                            f"{example} [титул] - перешлите сообщение и укажите титул (по желанию) и "
                             "получите цитату!"] 
Example #8
Source File: input_static_pic_to_gif2_for_class.py    From face-detection-induction-course with MIT License 6 votes vote down vote up
def get_cigarette_info(self, face_shape, face_width):
        """
        获取当前面部的烟卷信息
        :param face_shape:
        :param face_width:
        :return:
        """
        mouth = face_shape[49:68]
        mouth_center = mouth.mean(axis=0).astype("int")

        cigarette = self.cigarette.resize(
            (face_width, int(face_width * self.cigarette.size[1] / self.cigarette.size[0])),
            resample=Image.LANCZOS)

        x = mouth[0, 0] - face_width + int(16 * face_width / self.cigarette.size[0])
        y = mouth_center[1]
        return {"image": cigarette, "pos": (x, y)} 
Example #9
Source File: images.py    From cornerwise with MIT License 6 votes vote down vote up
def make_thumbnail(image, percent=None, fit=None, dim=None, dest_file=None,
                   pad=False, pad_fill="black"):
    """Resizes an image to fit within given bounds, or scales it down to a percent
    of its original size. Returns a PIL Image.

    """

    if not isinstance(image, Image.Image):
        image = Image.open(image, "r")
    w, h = image.size

    if not percent:
        if fit:
            fit_w, fit_h = fit
            percent = min(fit_w/w, fit_h/h)

    if percent >= 1:
        # The original is smaller than the desired dimensions.
        resized = image
    else:
        resized = image.resize(
            (int(w*percent), int(h*percent)),
            Image.LANCZOS)
    return pad(image, fit_w, fit_h, pad_fill or "black") if pad else image 
Example #10
Source File: save_omniglot_data.py    From versa with MIT License 6 votes vote down vote up
def load_and_save(save_file, size=None):
    data = []
    languages = get_subdirs(os.path.join(data_dir, 'omniglot'))

    for language_num, language in enumerate(languages):
        characters = get_subdirs(language)
        characters.sort()
        for character_num, character in enumerate(characters):
            character_images = []
            instances = os.listdir(character)
            instances.sort()
            for instance in instances:
                im = Image.open(os.path.join(character, instance))
                if size:
                    im = im.resize((size, size), resample=Image.LANCZOS)
                image = np.array(im.getdata()).astype('float32').reshape(size, size) / 255.
                image = 1.0 - image  # invert the data as Omniglot is black on white

                character_images.append((image, character_num, language_num))
            data.append(character_images)

    np.save(save_file, np.array(data)) 
Example #11
Source File: img_aux_processing.py    From optimize-images with MIT License 6 votes vote down vote up
def downsize_img(img: ImageType, max_w: int, max_h: int) -> Tuple[ImageType, bool]:
    """ Reduce the size of an image to the indicated maximum dimensions

    This function takes a PIL.Image object and integer values for the maximum
    allowed width and height (a zero value means no maximum constraint),
    calculates the size that meets those constraints and resizes the image. The
    resize is done in place, changing the original object. Returns a boolean
    indicating if the image was changed.
    """
    w, h = img.size
    # Assume 0 as current size
    if not max_w:
        max_w = w
    if not max_h:
        max_h = h

    if (max_w, max_h) == (w, h):  # If no changes, do nothing
        return img, False

    img.thumbnail((max_w, max_h), resample=Image.LANCZOS)
    return img, True 
Example #12
Source File: wallpaper_merger.py    From HydraPaper with GNU General Public License v3.0 6 votes vote down vote up
def multi_setup_pillow(monitors, save_path, wp_setter_func=None):
    images = list(map(Image.open, [m.wallpaper for m in monitors]))
    resolutions = [(m.width * m.scaling, m.height * m.scaling) for m in monitors]
    offsets = [(m.offset_x, m.offset_y) for m in monitors]

    # DEBUG
    # for m in monitors:
    #     print(m)

    final_image_width = max([m.offset_x + m.width * m.scaling for m in monitors])
    final_image_height = max([m.offset_y + m.height * m.scaling for m in monitors])

    # DEBUG
    # print('Final Size: {} x {}'.format(final_image_width, final_image_height))

    n_images = []
    for i, r in zip(images, resolutions):
        n_images.append(fit(i, r, method=Image.LANCZOS))
    final_image = Image.new('RGB', (final_image_width, final_image_height))
    for i, o in zip(n_images, offsets):
        final_image.paste(i, o)
    final_image.save(save_path) 
Example #13
Source File: controller.py    From inbac with MIT License 6 votes vote down vote up
def save(self) -> bool:
        if self.model.selection_box is None:
            return False
        selected_box: Tuple[int, int, int, int] = self.view.get_canvas_object_coords(
            self.model.selection_box)
        box: Tuple[int, int, int, int] = self.get_real_box(
            selected_box, self.model.current_image.size, self.model.canvas_image_dimensions)
        new_filename: str = self.find_available_name(
            self.model.args.output_dir, self.model.images[self.model.current_file])
        saved_image: Image = self.model.current_image.copy().crop(box)
        if self.model.args.resize:
            saved_image = saved_image.resize(
                (self.model.args.resize[0], self.model.args.resize[1]), Image.LANCZOS)
        if self.model.args.image_format:
            new_filename, _ = os.path.splitext(new_filename)
        saved_image.save(os.path.join(self.model.args.output_dir, new_filename),
                         self.model.args.image_format, quality=self.model.args.image_quality)
        self.clear_selection_box()
        return True 
Example #14
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_passthrough(self):
        # When no resize is required
        im = hopper()

        for size, box in [
            ((40, 50), (0, 0, 40, 50)),
            ((40, 50), (0, 10, 40, 60)),
            ((40, 50), (10, 0, 50, 50)),
            ((40, 50), (10, 20, 50, 70)),
        ]:
            try:
                res = im.resize(size, Image.LANCZOS, box)
                self.assertEqual(res.size, size)
                self.assert_image_equal(res, im.crop(box))
            except AssertionError:
                print('>>>', size, box)
                raise 
Example #15
Source File: dataset.py    From kraken with Apache License 2.0 6 votes vote down vote up
def _fixed_resize(img, size, interpolation=Image.LANCZOS):
    """
    Doesn't do the annoying runtime scale dimension switching the default
    pytorch transform does.

    Args:
        img (PIL.Image): image to resize
        size (tuple): Tuple (height, width)
    """
    w, h = img.size
    oh, ow = size
    if oh == 0:
        oh = int(h * ow/w)
    elif ow == 0:
        ow = int(w * oh/h)
    img = img.resize((ow, oh), interpolation)
    return img 
Example #16
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 #17
Source File: transforms.py    From pytorch-image-models with Apache License 2.0 5 votes vote down vote up
def _pil_interp(method):
    if method == 'bicubic':
        return Image.BICUBIC
    elif method == 'lanczos':
        return Image.LANCZOS
    elif method == 'hamming':
        return Image.HAMMING
    else:
        # default bilinear, do we want to allow nearest?
        return Image.BILINEAR 
Example #18
Source File: sample.py    From VideoSearchEngine with MIT License 5 votes vote down vote up
def load_image(image_path, transform=None):
    image = Image.open(image_path)
    image = image.resize([224, 224], Image.LANCZOS)
    
    if transform is not None:
        image = transform(image).unsqueeze(0)
    
    return image 
Example #19
Source File: sample.py    From VideoSearchEngine with MIT License 5 votes vote down vote up
def load_image(image_path):
    image = Image.open(image_path)
    image = image.resize([256, 256], Image.LANCZOS)
    
    image = np.array([np.array(image)])
    return image 
Example #20
Source File: evaluator.py    From see with GNU General Public License v3.0 5 votes vote down vote up
def load_image(self, image_file):
        with Image.open(image_file) as the_image:
            # the_image = the_image.resize((self.image_size.width, self.image_size.height), Image.LANCZOS)
            image = self.xp.asarray(the_image, dtype=np.float32)
            image /= 255
            image = image.transpose(2, 0, 1)
            return image 
Example #21
Source File: ImageCaptioner.py    From VideoSearchEngine with MIT License 5 votes vote down vote up
def load_image(image_path):
    image = Image.open(image_path)
    image = image.resize([256, 256], Image.LANCZOS)
    
    image = np.array([np.array(image)])
    return image 
Example #22
Source File: utils.py    From autowebcompat with Mozilla Public License 2.0 5 votes vote down vote up
def prepare_images():
    try:
        os.mkdir('data_resized')
    except OSError:
        pass

    for f in get_all_images():
        if os.path.exists(os.path.join('data_resized', f)):
            continue

        try:
            orig = Image.open(os.path.join('data', f))
            orig.load()
            channels = orig.split()
            if len(channels) == 4:
                img = Image.new('RGB', orig.size, (255, 255, 255))
                img.paste(orig, mask=channels[3])
            else:
                img = orig

            if img.size[1] > 732:
                img = img.crop((0, 0, img.size[0], 732))
            img = img.resize((192, 256), Image.LANCZOS)
            img.save(os.path.join('data_resized', f))
        except IOError as e:
            print(e) 
Example #23
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_zero(self):
        for f in [Image.NEAREST, Image.BOX, Image.BILINEAR,
                  Image.HAMMING, Image.BICUBIC, Image.LANCZOS]:
            r = self.resize(Image.new('RGB', (0, 0), "white"), (212, 195), f)
            self.assertEqual(r.mode, "RGB")
            self.assertEqual(r.size, (212, 195))
            self.assertEqual(r.getdata()[0], (0, 0, 0)) 
Example #24
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 #25
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 #26
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 #27
Source File: test_file_gif.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_palette_handling(self):
        # see https://github.com/python-pillow/Pillow/issues/513

        im = Image.open(TEST_GIF)
        im = im.convert('RGB')

        im = im.resize((100, 100), Image.LANCZOS)
        im2 = im.convert('P', palette=Image.ADAPTIVE, colors=256)

        f = self.tempfile('temp.gif')
        im2.save(f, optimize=True)

        reloaded = Image.open(f)

        self.assert_image_similar(im, reloaded.convert('RGB'), 10) 
Example #28
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 #29
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_la(self):
        case = self.make_dirty_case('LA', (255, 128), (0, 0))
        self.run_dirty_case(case.resize((20, 20), Image.BOX), (255,))
        self.run_dirty_case(case.resize((20, 20), Image.BILINEAR), (255,))
        self.run_dirty_case(case.resize((20, 20), Image.HAMMING), (255,))
        self.run_dirty_case(case.resize((20, 20), Image.BICUBIC), (255,))
        self.run_dirty_case(case.resize((20, 20), Image.LANCZOS), (255,)) 
Example #30
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))