Python PIL.Image 模块,LANCZOS 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PIL.Image.LANCZOS

项目:mets2man    作者:thegetty    | 项目源码 | 文件源码
def create_thumb(img_name):
    image = Image.open('{}.tiff'.format(img_name))
    (imageW, imageH) = image.size
    if imageW > imageH:
        ratio = thumb_size / imageW
        newWidth = 400
        newHeight = int(imageH * ratio)
    else:
        ratio = thumb_size / imageH
        newHeight = 400
        newWidth = int(imageW * ratio)  

    image = image.resize((newWidth, newHeight), Image.LANCZOS)
    outfh = open('{}_thumb.tiff'.format(img_name), 'wb')
    image.save(outfh, format='TIFF')
    outfh.close()
项目:1-tk1-zener-learner    作者:mlennox    | 项目源码 | 文件源码
def crop_resize(img, dimension):
    inv_img = ImageOps.invert(img.convert("RGB"))
    # returns left, upper, right, lower
    left, upper, right, lower = inv_img.getbbox()
    width = right - left
    height = lower - upper
    if width > height:
        # we want to add half the difference between width and height
        # to the upper and lower dimension
        padding = int(math.floor((width - height) / 2))
        upper -= padding
        lower += padding
    else:
        padding = int(math.floor((height - width) / 2))
        left -= padding
        right += padding

    img = img.crop((left, upper, right, lower))

    # Image.LANCZOS
    # Image.BICUBIC
    return img.resize((dimension, dimension), Image.LANCZOS)


# pulls together all the methods to distort and finalise the image
项目:pytorch-tutorial    作者:yunjey    | 项目源码 | 文件源码
def load_image(image_path, transform=None, max_size=None, shape=None):
    image = Image.open(image_path)

    if max_size is not None:
        scale = max_size / max(image.size)
        size = np.array(image.size) * scale
        image = image.resize(size.astype(int), Image.ANTIALIAS)

    if shape is not None:
        image = image.resize(shape, Image.LANCZOS)

    if transform is not None:
        image = transform(image).unsqueeze(0)

    return image.type(dtype)

# Pretrained VGGNet
项目:kdpv_generator    作者:spbpython    | 项目源码 | 文件源码
def _round_image(cls, image: PILImage.Image):

        if image.mode != 'RGBA':
            image = image.convert('RGBA')

        mask_size = image.size[0] * cls.ANTIALIAS_RATIO, image.size[1] * cls.ANTIALIAS_RATIO
        mask = PILImage.new('L', mask_size, color=0)
        mask_draw = cls._get_image_draw(mask)
        mask_draw.ellipse(((0, 0), mask.size), fill=255)

        mask = mask.resize(image.size, PILImage.LANCZOS)

        canvas = PILImage.new('RGBA', image.size, color=(0, 0, 0, 0))
        canvas.paste(image, mask=mask)

        return canvas
项目:painters    作者:inejc    | 项目源码 | 文件源码
def _prepare_image_for_cropping(image):
    width, height = image.size

    fixed_width = IMGS_DIM_2D[0] if width < IMGS_DIM_2D[0] else width
    fixed_height = IMGS_DIM_2D[1] if height < IMGS_DIM_2D[1] else height
    if (fixed_width, fixed_height) != image.size:
        image = image.resize((fixed_width, fixed_height), resample=LANCZOS)

    crop_coordinates = [
        (0, 0, IMGS_DIM_2D[0], IMGS_DIM_2D[1]),
        (fixed_width - IMGS_DIM_2D[0], 0, fixed_width, IMGS_DIM_2D[1]),
        (0, fixed_height - IMGS_DIM_2D[1], IMGS_DIM_2D[0], fixed_height),
        (fixed_width - IMGS_DIM_2D[0], fixed_height - IMGS_DIM_2D[1],
         fixed_width, fixed_height),
    ]

    return image, crop_coordinates
项目:pudzu    作者:Udzu    | 项目源码 | 文件源码
def from_pattern(cls, pattern, size, align=0, scale=(False,False), preserve_aspect=False, resample=Image.LANCZOS):
        """Create an image using a background pattern, either scaled or tiled."""
        align = Alignment(align)
        img = Image.new("RGBA", size)
        if preserve_aspect:
            if scale[0] and scale[1]: raise ValueError("Cannot preserve aspect when scaling in both dimensions.")
            elif scale[0]: pattern = pattern.resize_fixed_aspect(width=size[0], resample=resample)
            elif scale[1]: pattern = pattern.resize_fixed_aspect(height=size[1], resample=resample)
        else:
            if scale[0]: pattern = pattern.resize((size[0], pattern.height), resample=resample)
            if scale[1]: pattern = pattern.resize((pattern.width, size[1]), resample=resample)
        xover = (pattern.width - size[0] % pattern.width) % pattern.width
        yover = (pattern.height - size[1] % pattern.height) % pattern.height
        for i in range(ceil(size[0] / pattern.width)):
            for j in range(ceil(size[1] / pattern.height)):
                x = int(i*pattern.width-xover*align.x)
                y = int(j*pattern.height-yover*align.y)
                img.overlay(pattern, (x,y))
        return img
项目:pudzu    作者:Udzu    | 项目源码 | 文件源码
def __new__(cls, size, fg="black", bg=None, antialias=4, invert=False, **kwargs):
        """Generate an image of the appropriate shape. See mask method for additional shape-specific parameters.
        - size (int/(int,int)): image size
        - fg (color/pattern): image foreground [black]
        - bg (color/pattern): image background [None]
        - antialias (x>0): level of antialiasing (if supported), where 1.0 is none [4.0]
        - invert (boolean): whether to invert the shape mask [False]
        """
        if isinstance(size, Integral): size = (size, size)
        if bg is None: bg = ImageColor.getrgba(fg)._replace(alpha=0)
        if cls.antialiasing:
            orig_size, size = size, [round(s * antialias) for s in size]
            if isinstance(bg, Image.Image): bg = bg.resize([round(s * antialias) for s in bg.size], Image.NEAREST)
            if isinstance(fg, Image.Image): fg = fg.resize([round(s * antialias) for s in fg.size], Image.NEAREST)
        mask = cls.mask(size, **kwargs)
        if invert: mask = mask.invert_mask()
        base = Image.from_pattern(bg, mask.size) if isinstance(bg, Image.Image) else Image.new("RGBA", mask.size, bg)
        fore = Image.from_pattern(fg, mask.size) if isinstance(fg, Image.Image) else  Image.new("RGBA", mask.size, fg)
        img = base.overlay(fore, mask=mask)
        if cls.antialiasing:
            img = img.resize(orig_size, resample=Image.LANCZOS if antialias > 1 else Image.NEAREST)
        return img
项目:AdaptationSeg    作者:YangZhang4065    | 项目源码 | 文件源码
def load_image_single(f_path):
    im = Image.open(f_path).convert('RGB')
    width_side = im.size[0]
    new_h=width_side/2
    im = im.crop(
        (
            0,
            im.size[1]/2-new_h/2,
            width_side,
            im.size[1]/2+new_h/2
        )
    )
    im = im.resize( (image_size[0],image_size[1]),Image.LANCZOS)
    in_ = np.array(im, dtype=np.uint8)
    in_ = in_.transpose((2,0,1))
    return in_[np.newaxis, ...]
项目:TensorArtist    作者:vacancy    | 项目源码 | 文件源码
def resize(image, dsize, interpolation='LINEAR'):
    assert interpolation in ('NEAREST', 'LINEAR', 'CUBIC', 'LANCZOS4')

    dsize = tuple(map(int, dsize))
    assert len(dsize) == 2
    if cv2:
        interpolation = getattr(cv2, 'INTER_' + interpolation)
        return cv2.resize(image, dsize, interpolation=interpolation)
    else:
        if interpolation == 'NEAREST':
            interpolation = Image.NEAREST
        elif interpolation == 'LANCZOS4':
            interpolation = Image.LANCZOS
        else:
            interpolation = getattr(Image, 'BI' + interpolation)

        image = pil_nd2img(image)
        image = image.resize(dsize, resample=interpolation)
        return pil_img2nd(image)
项目:stn-ocr    作者:Bartzi    | 项目源码 | 文件源码
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
项目:orange3-imageanalytics    作者:biolab    | 项目源码 | 文件源码
def _load_image_or_none(self, file_path):
        image = self._load_image_from_url_or_local_path(file_path)

        if image is None:
            return image

        if not image.mode == 'RGB':
            try:
                image = image.convert('RGB')
            except ValueError:
                return None

        image.thumbnail(self._target_image_size, LANCZOS)
        image_bytes_io = BytesIO()
        image.save(image_bytes_io, format="JPEG")
        image.close()

        image_bytes_io.seek(0)
        image_bytes = image_bytes_io.read()
        image_bytes_io.close()
        return image_bytes
项目:tcv    作者:whentze    | 项目源码 | 文件源码
def print_fitting(path):
    img      = Image.open(path)
    termsize = shutil.get_terminal_size((9001, 9001))
    if args.bilevel:
        scale    = min(1, termsize[0]/img.size[0], 2*(termsize[1]-2)/(img.size[1]))
        newsize  = (2*int(scale*img.size[0]), int(scale*img.size[1]))
        newimg   = img.convert("1").resize(newsize, Image.LANCZOS)
        print_image_bl(newimg)
    else:
        scale    = min(1, termsize[0]/img.size[0], 2*(termsize[1]-2)/(img.size[1]))
        newsize  = (int(scale*img.size[0]), int(scale*img.size[1]))
        newimg   = img.convert("RGBA").resize(newsize, Image.LANCZOS)
        print_image_tc(newimg)
项目:imagepaste    作者:robinchenyu    | 项目源码 | 文件源码
def _save(im, fp, filename):
    fp.write(_MAGIC)  # (2+2)
    sizes = im.encoderinfo.get("sizes",
                               [(16, 16), (24, 24), (32, 32), (48, 48),
                                (64, 64), (128, 128), (255, 255)])
    width, height = im.size
    filter(lambda x: False if (x[0] > width or x[1] > height or
                               x[0] > 255 or x[1] > 255) else True, sizes)
    fp.write(struct.pack("<H", len(sizes)))  # idCount(2)
    offset = fp.tell() + len(sizes)*16
    for size in sizes:
        width, height = size
        fp.write(struct.pack("B", width))  # bWidth(1)
        fp.write(struct.pack("B", height))  # bHeight(1)
        fp.write(b"\0")  # bColorCount(1)
        fp.write(b"\0")  # bReserved(1)
        fp.write(b"\0\0")  # wPlanes(2)
        fp.write(struct.pack("<H", 32))  # wBitCount(2)

        image_io = BytesIO()
        tmp = im.copy()
        tmp.thumbnail(size, Image.LANCZOS)
        tmp.save(image_io, "png")
        image_io.seek(0)
        image_bytes = image_io.read()
        bytes_len = len(image_bytes)
        fp.write(struct.pack("<I", bytes_len))  # dwBytesInRes(4)
        fp.write(struct.pack("<I", offset))  # dwImageOffset(4)
        current = fp.tell()
        fp.seek(offset)
        fp.write(image_bytes)
        offset = offset + bytes_len
        fp.seek(current)
项目:sketal    作者:vk-brain    | 项目源码 | 文件源码
def __init__(self, *commands, prefixes=None, strict=False):
        """Answers with image containing stylish quote."""

        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"), 20)
        self.fs = ImageFont.truetype(self.get_path("font.ttf"), 14)

        example = self.command_example()
        self.description = [f"????????? ?????",
                            f"{example} [?????] - ????????? ????????? ? ??????? ????? (?? ???????) ? "
                             "???????? ??????!"]
项目:tumblr-photo-video-crawler    作者:zerohd4869    | 项目源码 | 文件源码
def resize(self, maxwidth=1000, maxheight=1000):
        """
        ????????????????
        ???????????????

        ???????? 0
        ????? maxwidth ?? 1
        ????? maxheight ?? 2
        ????? maxwidth, maxheight ?? 3

        maxwidth - ??????
        maxheight - ??????
        ??????????? False ???
        """
        # ?????
        ret = 0
        if maxwidth:
            if self.width > maxwidth:
                wpercent = (maxwidth / self.width)
                hsize = int((self.height * wpercent))
                fname = self.image.filename
                # Image.LANCZOS ?????????????
                self.image = self.image.resize((maxwidth, hsize), Image.LANCZOS)
                self.image.filename = fname
                self.width, self.height = self.image.size
                self.total_pixels = self.width * self.height
                ret += 1
        if maxheight:
            if self.height > maxheight:
                hpercent = (maxheight / float(self.height))
                wsize = int((float(self.width) * float(hpercent)))
                fname = self.image.filename
                self.image = self.image.resize((wsize, maxheight), Image.LANCZOS)
                self.image.filename = fname
                self.width, self.height = self.image.size
                self.total_pixels = self.width * self.height
                ret += 2
        return ret

    # ????
项目:ascii-art-py    作者:blinglnav    | 项目源码 | 文件源码
def _save(im, fp, filename):
    fp.write(_MAGIC)  # (2+2)
    sizes = im.encoderinfo.get("sizes",
                               [(16, 16), (24, 24), (32, 32), (48, 48),
                                (64, 64), (128, 128), (255, 255)])
    width, height = im.size
    filter(lambda x: False if (x[0] > width or x[1] > height or
                               x[0] > 255 or x[1] > 255) else True, sizes)
    fp.write(struct.pack("<H", len(sizes)))  # idCount(2)
    offset = fp.tell() + len(sizes)*16
    for size in sizes:
        width, height = size
        fp.write(struct.pack("B", width))  # bWidth(1)
        fp.write(struct.pack("B", height))  # bHeight(1)
        fp.write(b"\0")  # bColorCount(1)
        fp.write(b"\0")  # bReserved(1)
        fp.write(b"\0\0")  # wPlanes(2)
        fp.write(struct.pack("<H", 32))  # wBitCount(2)

        image_io = BytesIO()
        tmp = im.copy()
        tmp.thumbnail(size, Image.LANCZOS)
        tmp.save(image_io, "png")
        image_io.seek(0)
        image_bytes = image_io.read()
        bytes_len = len(image_bytes)
        fp.write(struct.pack("<I", bytes_len))  # dwBytesInRes(4)
        fp.write(struct.pack("<I", offset))  # dwImageOffset(4)
        current = fp.tell()
        fp.seek(offset)
        fp.write(image_bytes)
        offset = offset + bytes_len
        fp.seek(current)
项目:radar    作者:amoose136    | 项目源码 | 文件源码
def _save(im, fp, filename):
    fp.write(_MAGIC)  # (2+2)
    sizes = im.encoderinfo.get("sizes",
                               [(16, 16), (24, 24), (32, 32), (48, 48),
                                (64, 64), (128, 128), (255, 255)])
    width, height = im.size
    filter(lambda x: False if (x[0] > width or x[1] > height or
                               x[0] > 255 or x[1] > 255) else True, sizes)
    fp.write(struct.pack("<H", len(sizes)))  # idCount(2)
    offset = fp.tell() + len(sizes)*16
    for size in sizes:
        width, height = size
        fp.write(struct.pack("B", width))  # bWidth(1)
        fp.write(struct.pack("B", height))  # bHeight(1)
        fp.write(b"\0")  # bColorCount(1)
        fp.write(b"\0")  # bReserved(1)
        fp.write(b"\0\0")  # wPlanes(2)
        fp.write(struct.pack("<H", 32))  # wBitCount(2)

        image_io = BytesIO()
        tmp = im.copy()
        tmp.thumbnail(size, Image.LANCZOS)
        tmp.save(image_io, "png")
        image_io.seek(0)
        image_bytes = image_io.read()
        bytes_len = len(image_bytes)
        fp.write(struct.pack("<I", bytes_len))  # dwBytesInRes(4)
        fp.write(struct.pack("<I", offset))  # dwImageOffset(4)
        current = fp.tell()
        fp.seek(offset)
        fp.write(image_bytes)
        offset = offset + bytes_len
        fp.seek(current)
项目:pytorch-tutorial    作者:yunjey    | 项目源码 | 文件源码
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
项目:RosePrisma    作者:zjucx    | 项目源码 | 文件源码
def load_img(filename, max_size=None):
    im = Image.open(filename)
    if max_size is not None:
        factor = max_size / np.max(im.size)
        # Scale the image's height and width.
        size = np.array(im.size) * factor

        # The size is now floating-point because it was scaled.
        # But PIL requires the size to be integers.
        size = size.astype(int)

        # Resize the image.
        im = im.resize(size, Image.LANCZOS)
    return np.float32(im)
项目:ngraph    作者:NervanaSystems    | 项目源码 | 文件源码
def transform_and_save(target_size, tar_handle, img_object, output_filename):
    """
    Takes a tar file handle and a TarInfo object inside that tarfile and
    optionally transforms it and then writes it out to output_filename
    """
    img_handle = tar_handle.extractfile(img_object)
    img = Image.open(img_handle)
    width, height = img.size

    # Take the smaller image dimension down to target_size
    # while retaining aspect_ration. Otherwise leave it alone
    if width < height:
        if width > target_size:
            scale_factor = float(target_size) / width
            width = target_size
            height = int(height * scale_factor)
    else:
        if height > target_size:
            scale_factor = float(target_size) / height
            height = target_size
            width = int(width * scale_factor)
    if img.size[0] != width or img.size[1] != height:
        img = img.resize((width, height), resample=Image.LANCZOS)
        img.save(output_filename, quality=95)
    else:
        # Avoid recompression by saving file out directly without transformation
        dname, fname = os.path.split(output_filename)
        tar_handle.extract(img_object, path=dname)
        if fname != img_object.name:
            # Rename if name inside of tar is different than what we want it
            # called on the outside
            shutil.move(os.path.join(dname, img_object.name), output_filename)
    assert(os.stat(output_filename).st_size > 0), "{} has size 0".format(output_filename)
项目:kdpv_generator    作者:spbpython    | 项目源码 | 文件源码
def _draw_ellipse(self, image: PILImage.Image):
        x, y = self.position
        w, h = self.size
        # create mask in higher resolution for antialias effect
        mask_size = image.size[0] * self.ANTIALIAS_RATIO, image.size[1] * self.ANTIALIAS_RATIO
        mask = PILImage.new('L', mask_size, color='black')
        mask_draw = PILImageDraw.Draw(mask)
        left, top = x * self.ANTIALIAS_RATIO, y * self.ANTIALIAS_RATIO
        right, bottom = left + w * self.ANTIALIAS_RATIO, top + h * self.ANTIALIAS_RATIO
        # draw ellipse and then downscale from higher resolution for antialias effect
        mask_draw.ellipse((left, top, right, bottom), fill='white')
        mask = mask.resize(image.size, PILImage.LANCZOS)
        image.paste(self.color, mask=mask)
        return image
项目:kdpv_generator    作者:spbpython    | 项目源码 | 文件源码
def _resize_image(self, image: PILImage.Image) -> PILImage.Image:
        if self.size:
            image = image.resize(self.size, PILImage.LANCZOS)

        return image
项目:forget    作者:codl    | 项目源码 | 文件源码
def resize_image(basename, width, image_format):
    from PIL import Image
    with Image.open('assets/{}.png'.format(basename)) as im:
        if 'A' in im.getbands() and image_format != 'jpeg':
            im = im.convert('RGBA')
        else:
            im = im.convert('RGB')
        height = im.height * width // im.width
        new = im.resize((width, height), resample=Image.LANCZOS)
        if image_format == 'jpeg':
            kwargs = dict(
                    optimize=True,
                    progressive=True,
                    quality=80,
                    )
        elif image_format == 'webp':
            kwargs = dict(
                    quality=79,
                    )
        elif image_format == 'png':
            kwargs = dict(
                    optimize=True,
                    )
        new.save('static/{}-{}.{}'.format(basename, width, image_format),
                 **kwargs)
        reltouch('assets/{}.png'.format(basename),
                 'static/{}-{}.{}'.format(basename, width, image_format))
项目:tensorflow-cyclegan    作者:Eyyub    | 项目源码 | 文件源码
def _image_preprocessing(filename, xsize, ysize):
    im = Image.open(filename)

    if im.mode != 'RGB':
        print('Mode: ', im.mode)
        tmp = im.convert('RGB')
        im.close()
        im = tmp

    downsampled_im = ImageOps.fit(im, (xsize, ysize), method=Image.LANCZOS)
    norm_im = np.array(downsampled_im, dtype=np.float32)

    downsampled_im.close()
    im.close()
    return norm_im
项目:painters    作者:inejc    | 项目源码 | 文件源码
def _save_scaled_cropped_img(src, dest):
    image = load_img(src)
    image = fit(image, IMGS_DIM_2D, method=LANCZOS)
    image.save(dest)
    return image
项目:Circadia    作者:hooyah    | 项目源码 | 文件源码
def updatePosterLabel(self):
        """ resize the poster to the UI and overlay the theme name """

        if self.poster:
            thumb = self.poster.resize( (self.posterWidth, self.posterHeight), resample=Image.LANCZOS ) if (self.poster.width!=self.posterWidth or self.poster.height!=self.posterHeight) else self.poster
        else:
            thumb = Image.new('RGB', (self.posterWidth, self.posterHeight), (55,55,55))

        fnt = ImageFont.truetype(self.posterFont, 40) if self.posterFont else None
        txt = Image.new('RGBA', thumb.size, (255,255,255,0))
        dr = ImageDraw.Draw(txt)
        dr.text((8,8), self.theme['name'], font=fnt, fill=(0,0,0,128))
        dr.text((8,12), self.theme['name'], font=fnt, fill=(0,0,0,128))
        dr.text((12,12), self.theme['name'], font=fnt, fill=(0,0,0,128))
        dr.text((12,8), self.theme['name'], font=fnt, fill=(0,0,0,128))
        dr.text((10,10), self.theme['name'], font=fnt, fill=(255,255,255,180))
        thumb.paste(txt, (0,0), txt)

        self.posterTk = ImageTk.PhotoImage(thumb)
        self.posterLabel.config(image=self.posterTk)
项目:Circadia    作者:hooyah    | 项目源码 | 文件源码
def __init__(self, master, cfg):

        tk.Frame.__init__(self, master)

        img = Image.open('lamp.png')
        self.lampSrc = img.resize( (img.width/2, img.height/2), resample=Image.LANCZOS)
        self.lampImg = ImageTk.PhotoImage(self.lampSrc)
        self.backgroundLabel = tk.Label(master, image=self.lampImg, background='#252525')
        self.backgroundLabel.pack(side='left', anchor='sw', fill='y')
项目:sketchnet    作者:jtoy    | 项目源码 | 文件源码
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
项目:thaanaOCR    作者:Sofwath    | 项目源码 | 文件源码
def size_randpad(picture):
    """Padding a PIL image to a random position and returning it as a keras friendly matrix"""
    backc = sample_background(picture)
    newpic = Image.new('RGB', (512, 64), (backc, backc, backc, 255))
    orw = picture.getbbox()[2]
    orh = picture.getbbox()[3]
    new = newpic.getbbox()[2]
    neh = newpic.getbbox()[3]

    if orw > new or orh > neh:
        wr = float(new) / float(orw)
        hr = float(neh) / float(orh)
        rat = min([wr, hr]) * .9
        picture = picture.resize((int(orw * rat) - 1, int(orh * rat) - 1), Image.LANCZOS)
        orw = picture.getbbox()[2]
        orh = picture.getbbox()[3]

    if orh > float(neh) * .5:
        multw = float(randint(int(orw * .5), new)) / float(orw)
        multh = float(randint(int(orh * .5), neh)) / float(orh)
    else:
        multw = float(randint(orw, new)) / float(orw)
        multh = float(randint(orh, neh)) / float(orh)
    mult = min([multw, multh])
    orw = int(float(orw) * float(mult))
    orh = int(float(orh) * float(mult))
    picture = picture.resize((orw, orh), Image.LANCZOS)
    randoffw = randint(0, new - orw)
    randoffh = randint(0, neh - orh)
    tup = (randoffw, randoffh)
    newpic.paste(picture, tup)
    newpic = newpic.convert("L")
    numparr = np.array(newpic)
    numparr = numparr.astype(np.float32) / 255
    numparr = numparr.transpose()[None, :, :]
    return numparr
项目:tensorflow-layer-library    作者:bioinf-jku    | 项目源码 | 文件源码
def per_image(self, img):
        resample = {
            'nearest' : Image.NEAREST,
            'bilinear' : Image.BILINEAR,
            'bicubic' : Image.BICUBIC,
            'lanczos' : Image.LANCZOS}[self.resample]

        lower_left = [p * (s / self.factor) for p, s in zip(self.position, img.size)]
        return zoom_into_image(img, self.factor, tuple(lower_left), resample=resample)
项目:pudzu    作者:Udzu    | 项目源码 | 文件源码
def resize(self, size, resample=Image.LANCZOS, *args, **kwargs):
        """Return a resized copy of the image, handling zero-width/height sizes and defaulting to LANCZOS resampling."""
        if size[0] == 0 or size[1] == 0:
            return Image.new(self.mode, size)
        else:
            return self.resize_nonempty(size, resample, *args, **kwargs)
项目:pudzu    作者:Udzu    | 项目源码 | 文件源码
def resize_fixed_aspect(self, *, width=None, height=None, scale=None, resample=Image.LANCZOS):
        """Return a resized image with an unchanged aspect ratio."""
        if all(x is None for x in (width, height, scale)):
            raise ValueError("Resize expects either width/height or scale.")
        elif any(x is not None for x in (width, height)) and scale is not None:
            raise ValueError("Resize expects just one of width/height or scale.")
        elif scale is not None:
            return self.resize((int(self.width * scale), int(self.height * scale)), resample=resample)
        elif height is None or width is not None and self.width / self.height > width / height:
            return self.resize((width, int(width * (self.height / self.width))), resample=resample)
        else:
            return self.resize((int(height * (self.width / self.height)), height), resample=resample)
项目:PornDetective    作者:songluyi    | 项目源码 | 文件源码
def resize(self,max_width=1000,max_height=1000):
        """
        ????????????????
        ???????????????

        ???????? 0
        ????? maxwidth ?? 1
        ????? maxheight ?? 2
        ????? maxwidth, maxheight ?? 3

        maxwidth - ??????
        maxheight - ??????
        """
        ret = 0
        if self.width > max_width:
            wpercent = (max_width / self.width)
            hsize = int((self.height * wpercent))
            fname = self.image.filename
            # Image.LANCZOS ?????????????
            self.image = self.image.resize((max_width, hsize), Image.LANCZOS)
            self.image.filename = fname
            self.width, self.height = self.image.size
            self.pixels = self.width * self.height
            ret += 1
        if self.height > max_height:
            hpercent = (max_height / float(self.height))
            wsize = int((float(self.width) * float(hpercent)))
            fname = self.image.filename
            self.image = self.image.resize((wsize, max_height), Image.LANCZOS)
            self.image.filename = fname
            self.width, self.height = self.image.size
            self.total_pixels = self.width * self.height
            ret += 2
        return ret
项目:loris-redux    作者:jpstroop    | 项目源码 | 文件源码
def _resize(self, pil_image, image_request, sampling=Image.LANCZOS):
        wh = (image_request.width, image_request.height)
        pil_image = pil_image.resize(wh, resample=sampling)
        return pil_image
项目:cozmo-python-sdk    作者:anki    | 项目源码 | 文件源码
def get_low_res_view(self):
        '''Downsizes Cozmo's camera view to the specified dimensions.

        Returns:
            PIL image downsized to low-resolution version of Cozmo's camera view.
        '''
        image = self.robot.world.latest_image.raw_image
        downsized_image = image.resize((DOWNSIZE_WIDTH, DOWNSIZE_HEIGHT), resample = Image.LANCZOS)
        return downsized_image
项目:style_transfer    作者:crowsonkb    | 项目源码 | 文件源码
def resize_to_fit(image, size, scale_up=False):
    """Resizes image to fit into a size-by-size square."""
    size = int(round(size)) // ARGS.div * ARGS.div
    w, h = image.size
    if not scale_up and max(w, h) <= size:
        return image
    new_w, new_h = w, h
    if w > h:
        new_w = size
        new_h = int(round(size * h/w)) // ARGS.div * ARGS.div
    else:
        new_h = size
        new_w = int(round(size * w/h)) // ARGS.div * ARGS.div
    return image.resize((new_w, new_h), Image.LANCZOS)
项目:MNIST-Neural-Net    作者:MLavrentyev    | 项目源码 | 文件源码
def resizeImage(self, image):
        return image.resize((28,28), Image.LANCZOS)
项目:visual-backprop-mxnet    作者:Bartzi    | 项目源码 | 文件源码
def image(self, value):
        window_width = self.frame.winfo_width()
        window_height = self.frame.winfo_height()
        value = value.resize((window_width, window_height), Image.LANCZOS)
        image = ImageTk.PhotoImage(value)
        self._image = image
        self._sprite = self.canvas.create_image(value.width // 2, value.height // 2, image=self._image)
        self.canvas.config(width=value.width, height=value.height)
项目:mlAlgorithms    作者:gu-yan    | 项目源码 | 文件源码
def get_image(path, shape, format):
    """

    :param path:
    :param shape:
    :param format:
    :return:
    """
    img = Image.open(path)
    img = img.resize(size=(shape[1], shape[2]), resample=Image.LANCZOS)
    img_array = np.asarray(img, dtype=np.uint8)
    if format == 'NCHW':
        img_array = img_array.transpose(2, 0, 1)
    img_array = img_array.reshape([1, shape[0], shape[1], shape[2]])
    return img_array
项目:mlAlgorithms    作者:gu-yan    | 项目源码 | 文件源码
def resize(data, width, height, channel, width_new, height_new):
    res_data = []
    for _ in data:
        image = (reshape(_, width, height, channel)[0:1, :, :, :]).reshape([width, height, channel])
        img_obj = Image.fromarray(image)
        # img_obj.show()
        img_obj = img_obj.resize(size=(width_new, height_new), resample=Image.LANCZOS)
        # img_obj.show()
        img_array = np.asarray(img_obj, dtype=np.uint8)
        res_data.append(img_array)
    return res_data
项目:WXBotForPi    作者:nemoTyrant    | 项目源码 | 文件源码
def _save(im, fp, filename):
    fp.write(_MAGIC)  # (2+2)
    sizes = im.encoderinfo.get("sizes",
                               [(16, 16), (24, 24), (32, 32), (48, 48),
                                (64, 64), (128, 128), (255, 255)])
    width, height = im.size
    filter(lambda x: False if (x[0] > width or x[1] > height or
                               x[0] > 255 or x[1] > 255) else True, sizes)
    fp.write(struct.pack("<H", len(sizes)))  # idCount(2)
    offset = fp.tell() + len(sizes)*16
    for size in sizes:
        width, height = size
        fp.write(struct.pack("B", width))  # bWidth(1)
        fp.write(struct.pack("B", height))  # bHeight(1)
        fp.write(b"\0")  # bColorCount(1)
        fp.write(b"\0")  # bReserved(1)
        fp.write(b"\0\0")  # wPlanes(2)
        fp.write(struct.pack("<H", 32))  # wBitCount(2)

        image_io = BytesIO()
        tmp = im.copy()
        tmp.thumbnail(size, Image.LANCZOS)
        tmp.save(image_io, "png")
        image_io.seek(0)
        image_bytes = image_io.read()
        bytes_len = len(image_bytes)
        fp.write(struct.pack("<I", bytes_len))  # dwBytesInRes(4)
        fp.write(struct.pack("<I", offset))  # dwImageOffset(4)
        current = fp.tell()
        fp.seek(offset)
        fp.write(image_bytes)
        offset = offset + bytes_len
        fp.seek(current)
项目:django-clubhouse    作者:chazmead    | 项目源码 | 文件源码
def _crop_image(cls, origin_image, target_image, size, crop_box, image_format="JPEG"):
        """
        Resizes an image from one model field and saves into another
        :param origin_image: django.db.models.fields.files.ImageFieldFile
        :param target_image: django.db.models.fields.files.ImageFieldFile
        :param size: tuple of final desired width and height
        :param crop_box: str, 4-coordinate crop box
        :param image_format: str, Pillow Image format
        """
        # Original photo
        origin_image.seek(0)
        image_file = Image.open(origin_image)

        # Convert to RGB
        if image_file.mode not in ("L", "RGB"):
            image_file = image_file.convert("RGB")

        if crop_box:
            try:
                values = [int(x) for x in crop_box.split(",")]
                width = abs(values[2] - values[0])
                height = abs(values[3] - values[1])
                if width and height and (width != image_file.size[0] or height != image_file.size[1]):
                    image_file = image_file.crop(values)
            except (ValueError, TypeError, IndexError):
                # There's garbage in the cropping field, ignore
                print("Unable to parse crop_box parameter value '%s'. Ignoring." % crop_box)

        image_file = ImageOps.fit(image_file, size, method=Image.LANCZOS)
        image_content = BytesIO()
        image_file.save(image_content, format=image_format, quality=IMAGE_QUALITY)
        image_content = ImageFile(image_content, origin_image.name)
        target_image.save(name=image_content.name, content=image_content, save=False)
项目:pytgasu    作者:alemonmk    | 项目源码 | 文件源码
def _pil_scale(d, scalebywidth=None):
    """*scale all png in ``d`` using Pillow."""
    # scalebywidth is unused here
    for fp in d.iterdir():
        with Image.open(fp) as i:
            scale_ratio = 512 / max(i.size)
            final_size = tuple(int(x * scale_ratio) for x in i.size)
            resized = i.resize(final_size, resample=Image.LANCZOS)
            resized.save(fp=fp, format='PNG')
项目:OCkRE    作者:rossumai    | 项目源码 | 文件源码
def size_randpad(picture):
    """Padding a PIL image to a random position and returning it as a keras friendly matrix"""
    backc = sample_background(picture)
    newpic = Image.new('RGB', (512, 64), (backc, backc, backc, 255))
    orw = picture.getbbox()[2]
    orh = picture.getbbox()[3]
    new = newpic.getbbox()[2]
    neh = newpic.getbbox()[3]

    if orw > new or orh > neh:
        wr = float(new) / float(orw)
        hr = float(neh) / float(orh)
        rat = min([wr, hr]) * .9
        picture = picture.resize((int(orw * rat) - 1, int(orh * rat) - 1), Image.LANCZOS)
        orw = picture.getbbox()[2]
        orh = picture.getbbox()[3]

    if orh > float(neh) * .5:
        multw = float(randint(int(orw * .5), new)) / float(orw)
        multh = float(randint(int(orh * .5), neh)) / float(orh)
    else:
        multw = float(randint(orw, new)) / float(orw)
        multh = float(randint(orh, neh)) / float(orh)
    mult = min([multw, multh])
    orw = int(float(orw) * float(mult))
    orh = int(float(orh) * float(mult))
    picture = picture.resize((orw, orh), Image.LANCZOS)
    randoffw = randint(0, new - orw)
    randoffh = randint(0, neh - orh)
    tup = (randoffw, randoffh)
    newpic.paste(picture, tup)
    newpic = newpic.convert("L")
    numparr = np.array(newpic)
    numparr = numparr.astype(np.float32) / 255
    numparr = numparr.transpose()[None, :, :]
    return numparr
项目:tensorflow-pix2pix    作者:Eyyub    | 项目源码 | 文件源码
def _image_preprocessing(filename, xsize, ysize):
    im = Image.open(filename)

    if filename.endswith('.png'):
        im = im.convert('RGB')
    downsampled_im = ImageOps.fit(im, (xsize, ysize), method=Image.LANCZOS)
    norm_im = np.array(downsampled_im, dtype=np.float32) / 255.

    downsampled_im.close()
    im.close()
    return norm_im
项目:teleport    作者:eomsoft    | 项目源码 | 文件源码
def _save(im, fp, filename):
    fp.write(_MAGIC)  # (2+2)
    sizes = im.encoderinfo.get("sizes",
                               [(16, 16), (24, 24), (32, 32), (48, 48),
                                (64, 64), (128, 128), (255, 255)])
    width, height = im.size
    filter(lambda x: False if (x[0] > width or x[1] > height or
                               x[0] > 255 or x[1] > 255) else True, sizes)
    fp.write(struct.pack("<H", len(sizes)))  # idCount(2)
    offset = fp.tell() + len(sizes)*16
    for size in sizes:
        width, height = size
        fp.write(struct.pack("B", width))  # bWidth(1)
        fp.write(struct.pack("B", height))  # bHeight(1)
        fp.write(b"\0")  # bColorCount(1)
        fp.write(b"\0")  # bReserved(1)
        fp.write(b"\0\0")  # wPlanes(2)
        fp.write(struct.pack("<H", 32))  # wBitCount(2)

        image_io = BytesIO()
        tmp = im.copy()
        tmp.thumbnail(size, Image.LANCZOS)
        tmp.save(image_io, "png")
        image_io.seek(0)
        image_bytes = image_io.read()
        bytes_len = len(image_bytes)
        fp.write(struct.pack("<I", bytes_len))  # dwBytesInRes(4)
        fp.write(struct.pack("<I", offset))  # dwImageOffset(4)
        current = fp.tell()
        fp.seek(offset)
        fp.write(image_bytes)
        offset = offset + bytes_len
        fp.seek(current)
项目:teleport    作者:eomsoft    | 项目源码 | 文件源码
def _save(im, fp, filename):
    fp.write(_MAGIC)  # (2+2)
    sizes = im.encoderinfo.get("sizes",
                               [(16, 16), (24, 24), (32, 32), (48, 48),
                                (64, 64), (128, 128), (255, 255)])
    width, height = im.size
    filter(lambda x: False if (x[0] > width or x[1] > height or
                               x[0] > 255 or x[1] > 255) else True, sizes)
    fp.write(struct.pack("<H", len(sizes)))  # idCount(2)
    offset = fp.tell() + len(sizes)*16
    for size in sizes:
        width, height = size
        fp.write(struct.pack("B", width))  # bWidth(1)
        fp.write(struct.pack("B", height))  # bHeight(1)
        fp.write(b"\0")  # bColorCount(1)
        fp.write(b"\0")  # bReserved(1)
        fp.write(b"\0\0")  # wPlanes(2)
        fp.write(struct.pack("<H", 32))  # wBitCount(2)

        image_io = BytesIO()
        tmp = im.copy()
        tmp.thumbnail(size, Image.LANCZOS)
        tmp.save(image_io, "png")
        image_io.seek(0)
        image_bytes = image_io.read()
        bytes_len = len(image_bytes)
        fp.write(struct.pack("<I", bytes_len))  # dwBytesInRes(4)
        fp.write(struct.pack("<I", offset))  # dwImageOffset(4)
        current = fp.tell()
        fp.seek(offset)
        fp.write(image_bytes)
        offset = offset + bytes_len
        fp.seek(current)
项目:swn-gen    作者:jimmayjr    | 项目源码 | 文件源码
def save(self, path):
        # Check arguments
        path = exception.arg_check(path, str)

        # Draw image if it hasn't been
        if self._workingImage is None:
            self.draw()

        # Resize background image.
        # Get scale of actual image to background image.
        bgScale  = float(self._height)/float(self._background.height)
        # Calculate width assuming resizing background image height to actual 
        # image height.
        bgWidth  = int(math.ceil(bgScale*self._background.width))
        # Calculate number of times background image is requred to tile to fit
        # width.
        bgTile   = int(math.ceil(float(self._width)/float(bgWidth)))
        # Resize background image to match actual image height.
        bgResize = self._background.resize((bgWidth,self._height), pilimage.LANCZOS)

        # Create image to save
        saveImage = pilimage.new('RGBA', (self._width, self._height))

        # Paste background
        for tile in xrange(bgTile):
            saveImage.paste(bgResize, box=((tile)*bgWidth,0), mask=bgResize)

        # Paste working image
        saveImage.paste(self._workingImage, box=(0,0), mask=self._workingImage)

        # Resize/scale down with antialiasing to smooth jagged lines
        saveImage = saveImage.resize((self._width/_SECTOR_IMAGE_SCALE, 
                                      self._height/_SECTOR_IMAGE_SCALE),
                                     pilimage.LANCZOS)

        # Save image
        saveImage.save(path)

## Sector information table class.
#
#  The sector information table class is used to create images of an SWN sector.
项目:swn-gen    作者:jimmayjr    | 项目源码 | 文件源码
def save(self, path):
        # Check arguments
        path = exception.arg_check(path, str)

        # Draw image if it hasn't been
        if self._workingImage is None:
            self.draw()

        # Resize background image.
        # Get scale of actual image to background image.
        bgScale  = float(self._height)/float(self._background.height)
        # Calculate width assuming resizing background image height to actual 
        # image height.
        bgWidth  = int(math.ceil(bgScale*self._background.width))
        # Calculate number of times background image is requred to tile to fit
        # width.
        bgTile   = int(math.ceil(float(self._width)/float(bgWidth)))
        # Resize background image to match actual image height.
        bgResize = self._background.resize((bgWidth,self._height), pilimage.LANCZOS)

        # Create image to save
        saveImage = pilimage.new('RGBA', (self._width, self._height))

        # Paste background
        for tile in xrange(bgTile):
            saveImage.paste(bgResize, box=((tile)*bgWidth,0), mask=bgResize)

        # Paste working image
        saveImage = pilimage.alpha_composite(saveImage, self._workingImage)

        # Resize/scale down with antialiasing to smooth jagged lines
        saveImage = saveImage.resize((self._width/_SECTOR_IMAGE_SCALE, 
                                      self._height/_SECTOR_IMAGE_SCALE),
                                     pilimage.LANCZOS)

        # Save image
        saveImage.save(path)

## Orbit map image class.
#
# The orbit map image class is used to create images of orbit maps.
项目:Semi-automatic-Annotation    作者:Luoyadan    | 项目源码 | 文件源码
def set_ref_img(self, img_arr, img_path):
        # seg_arr (r * c) 2D size, init with 255
        # seg_arr[r, c] -- label of pixel on (r, c)
        print ">>>>>>>>>>> img_arr.shape: ", img_arr.shape
        if self.ref_pic:
            ## resize to 720P if original image larger than 720
            self.h0 = img_arr.shape[0]
            self.w0 = img_arr.shape[1]
            self.ori_sized_img_arr = img_arr.copy()
            if (self.h0 > 720):
                # img720 = Image.fromarray(img_arr)
                # shape720 = (int(self.w0 * (720.0/self.h0)), 720)
                # print ">>>>>>> shape720: ", shape720
                # img720.show()
                img_arr = np.array(Image.fromarray(img_arr).resize((int(self.w0 * (720.0/self.h0)), 720), Image.LANCZOS))


            self.skip = False   # skip init to False  
            self.large_ref_img = None
            self.ImgLoaded = True
            self.ref_pic.img_arr = img_arr
            # print ">>>>>>>>>> self.ref_pic.img_arr.shape: ", self.ref_pic.img_arr.shape
            # self.lineSeg_BI_dict = {}
            self.ori_img = self.ref_pic.img_arr.copy()

            if self.parent().edit_method == "polygon" and (self.seg_disp_polygon is None or len(self.seg_disp_polygon.shape) < 3):
                self.seg_disp_polygon = self.ref_pic.img_arr.copy()
            self.seg_arr = np.zeros(img_arr.shape[:2], dtype=np.uint8)
            self.seg_arr[:] = 255
            self.ref_pic.img_path = img_path
            self.w = self.ref_pic.img_arr.shape[1]
            self.h = self.ref_pic.img_arr.shape[0]

            self.update_disp()
            return True
        return False