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

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

项目:FRG-Crowdsourcing    作者:97amarnathk    | 项目源码 | 文件源码
def crop(self, file, coordinates):
        """Crop filename and overwrite it."""
        try:
            filename = file.filename
            extension = self.get_filename_extension(filename)
            from io import BytesIO
            m = BytesIO()
            im = Image.open(file)
            target = im.crop(coordinates)
            # target = target.resize(self.size, Image.ANTIALIAS)
            # Scale down the image to Indexed mode
            scale_down_img = target.convert('P', colors=255, palette=Image.ADAPTIVE)
            scale_down_img.save(m, format=extension)
            file.stream = m
            file.stream.seek(0)
            return True
        except:
            return False
项目:show-adapt-and-tell    作者:tsenghungchen    | 项目源码 | 文件源码
def extract_image(net, image_file):
    batch_size = 1
    transformer = set_transformer(net)
    if image_file.split('.')[-1] == 'gif':
        img = Image.open(image_file).convert("P",palette=Image.ADAPTIVE, colors=256)
        newfile = ''.join(image_file.split('.')[:-1])+'.png'
        for i, frame in enumerate(iter_frames(img)):
            frame.save(newfile,**frame.info)
        image_file = newfile

    img = cv2.imread(image_file)
    img = img.astype('float') / 255
    net.blobs['data'].data[:] = transformer.preprocess('data', img)
    net.forward()
    blobs_out_pool5 = net.blobs['pool5'].data[0,:,0,0]
    return blobs_out_pool5
项目:GLaDOS2    作者:TheComet    | 项目源码 | 文件源码
def save_target_image(self, source, name, x_offset, y_offset, x_size, y_size, flip, convert):
        m_img = Image.open(source)
        if x_size!=0 and y_size!=0:
            m_img = m_img.crop((x_offset, y_offset, x_offset + x_size, y_offset + y_size))
        if flip is True:
            m_img = m_img.transpose(Image.FLIP_LEFT_RIGHT)
        if convert is True:
            m_img.load()
            alpha = m_img.split()[- 1]
            m_img = m_img.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
            mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
            m_img.paste(255, mask)
            m_img.save(join(self.emotedb_path, name) + ".png", transparency=255, optimize=True)
        else:
            m_img.save(join(self.emotedb_path, name) + ".png", optimize=True)
项目:GLaDOS2    作者:TheComet    | 项目源码 | 文件源码
def save_target_image(self, source, name, x_offset, y_offset, x_size, y_size, flip, convert):
        m_img = Image.open(source)
        if x_size!=0 and y_size!=0:
            m_img = m_img.crop((x_offset, y_offset, x_offset + x_size, y_offset + y_size))
        if flip is True:
            m_img = m_img.transpose(Image.FLIP_LEFT_RIGHT)
        if convert is True:
            m_img.load()
            alpha = m_img.split()[- 1]
            m_img = m_img.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=255)
            mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
            m_img.paste(255, mask)
            m_img.save(join(self.emotes_path, name) + ".png", transparency=255, optimize=True)
        else:
            m_img.save(join(self.emotes_path, name) + ".png", optimize=True)
项目:TnyBot-Discord    作者:00firestar00    | 项目源码 | 文件源码
def set_text(self, text):
        font = ImageFont.truetype(self.fontname, 14)

        formatted_lines = []
        max_width = 400
        max_height = 0
        offset = 5

        for line in text.split("\n"):
            width, height = font.getsize(line)
            if width > max_width:
                max_width = width
            splits = textwrap.wrap(line, width=40)
            max_height += (height * len(splits))
            formatted_lines.extend(splits)

        max_height += 10

        spoiler_im = self.get_spoiler_text(max_width, max_height)

        im = Image.new("RGB", (max_width, max_height), (54, 57, 62))
        draw = ImageDraw.Draw(im)

        for line in formatted_lines:
            width, height = font.getsize(line)
            draw.text((5, offset), line, font=font)
            offset += height

        content_im = im.convert('P', palette=Image.ADAPTIVE, colors=5)
        spoiler_im.save("res/temp.gif", "GIF", save_all=True, append_images=[content_im])
项目:TnyBot-Discord    作者:00firestar00    | 项目源码 | 文件源码
def get_spoiler_text(self, width=400, height=100):

        im = Image.new("RGB", (width, height), (54, 57, 62))
        d = ImageDraw.Draw(im)

        font = ImageFont.truetype(self.fontname, 14)
        d.text((5, 5), "( Hover to reveal spoiler )", font=font)
        return im.convert('P', palette=Image.ADAPTIVE, colors=5)
项目:constantina    作者:wwoast    | 项目源码 | 文件源码
def __upload_avatar(self, auth, upload):
        """
        If a valid token for a user is presented, upload a new avatar to:
           private/images/avatars/{username.png}
        Since the path is fixed per username, this is a detail managed in the
        preferences form, but isn't tracked in the preferences token.
        """
        pixel_width = 80
        # 32 bits rgba per pixel, times number of pixels. File shouldn't be bigger
        max_image_size = pixel_width * pixel_width * 4

        if upload == '' or upload == None or auth.account.valid == False:
            return
        # If file is too large for its bytes-size, return.
        if len(upload) > max_image_size:
            return

        try:
            # Check if it's an 80x80 PNG
                # If not, return an error response
            # If it is a decent image, write to the image path.tmp
            # Then atomic overwrite the existing image
            tmp = self.avatar + "." + self.cookie_id
            iotmp = BytesIO(upload)
            src = Image.open(iotmp)
            if src.size[0] == 80 and src.size[1] == 80:
                dst = src.convert('RGB').convert('P', palette=Image.ADAPTIVE, colors=128)
                dst.save(tmp, "PNG")
                rename(tmp, self.avatar)
        except OSError:
            syslog.syslog("oserror when dealing with image upload")
            return
        except IOError:
            syslog.syslog("ioerror, likely from the image failing to open")
            return
项目:tichu-tournament    作者:aragos    | 项目源码 | 文件源码
def _convert2pilp(im):
    Image = _getImage()
    return im.convert("P", dither=Image.NONE, palette=Image.ADAPTIVE)
项目:tichu-tournament    作者:aragos    | 项目源码 | 文件源码
def drawToPILP(d, dpi=72, bg=0xffffff, configPIL=None, showBoundary=rl_config._unset_):
    Image = _getImage()
    im = drawToPIL(d, dpi=dpi, bg=bg, configPIL=configPIL, showBoundary=showBoundary)
    return im.convert("P", dither=Image.NONE, palette=Image.ADAPTIVE)
项目:SDV-Summary    作者:Sketchy502    | 项目源码 | 文件源码
def watermark(img, **kwargs):
    asset_dir = app.config.get('ASSET_PATH')
    mark = None if 'mark' not in kwargs else kwargs['mark']
    filename = 'u.f.png' if 'filename' not in kwargs else kwargs['filename']
    if mark is None:
        mark = Image.open(os.path.join(asset_dir, 'watermarks',filename))
    x = 16
    y = img.size[1] - 16 - mark.size[1]
    if img.mode != 'RGBA':
        img = img.convert('RGBA')
    img.paste(mark, box=(x, y), mask=mark)
    return img.convert('P', palette=Image.ADAPTIVE, colors=255)
项目:sudomemo-utils    作者:Sudomemo    | 项目源码 | 文件源码
def _limitImageColors(self, image, paletteSlots=0):
        # Convert the image to RGB, then posterize to clamp the color channels to 5 bit values
        image = image.convert("RGB")
        image = ImageOps.posterize(image, 5)
        return image.convert("P", palette=Image.ADAPTIVE, colors=paletteSlots)

    # Reads an npf image from buffer, and returns an array of RGBA pixels
项目:RasterFairy    作者:Quasimondo    | 项目源码 | 文件源码
def convertImagesToPIL(self, images, dither, nq=0):
        """ convertImagesToPIL(images, nq=0)

        Convert images to Paletted PIL images, which can then be
        written to a single animaged GIF.

        """

        # Convert to PIL images
        images2 = []
        for im in images:
            if isinstance(im, Image.Image):
                images2.append(im)
            elif np and isinstance(im, np.ndarray):
                if im.ndim==3 and im.shape[2]==3:
                    im = Image.fromarray(im,'RGB')
                elif im.ndim==3 and im.shape[2]==4:
                    im = Image.fromarray(im[:,:,:3],'RGB')
                elif im.ndim==2:
                    im = Image.fromarray(im,'L')
                images2.append(im)

        # Convert to paletted PIL images
        images, images2 = images2, []
        if nq >= 1:
            # NeuQuant algorithm
            for im in images:
                im = im.convert("RGBA") # NQ assumes RGBA
                nqInstance = NeuQuant(im, int(nq)) # Learn colors from image
                if dither:
                    im = im.convert("RGB").quantize(palette=nqInstance.paletteImage())
                else:
                    im = nqInstance.quantize(im)  # Use to quantize the image itself
                images2.append(im)
        else:
            # Adaptive PIL algorithm
            AD = Image.ADAPTIVE
            for im in images:
                im = im.convert('P', palette=AD, dither=dither)
                images2.append(im)

        # Done
        return images2
项目:CycleGAN-Tensorflow-PyTorch-Simple    作者:LynnHo    | 项目源码 | 文件源码
def convertImagesToPIL(self, images, dither, nq=0):
        """ convertImagesToPIL(images, nq=0)

        Convert images to Paletted PIL images, which can then be
        written to a single animaged GIF.

        """

        # Convert to PIL images
        images2 = []
        for im in images:
            if isinstance(im, Image.Image):
                images2.append(im)
            elif np and isinstance(im, np.ndarray):
                if im.ndim == 3 and im.shape[2] == 3:
                    im = Image.fromarray(im, 'RGB')
                elif im.ndim == 3 and im.shape[2] == 4:
                    im = Image.fromarray(im[:, :, :3], 'RGB')
                elif im.ndim == 2:
                    im = Image.fromarray(im, 'L')
                images2.append(im)

        # Convert to paletted PIL images
        images, images2 = images2, []
        if nq >= 1:
            # NeuQuant algorithm
            for im in images:
                im = im.convert("RGBA")  # NQ assumes RGBA
                nqInstance = NeuQuant(im, int(nq))  # Learn colors from image
                if dither:
                    im = im.convert("RGB").quantize(palette=nqInstance.paletteImage())
                else:
                    im = nqInstance.quantize(im)  # Use to quantize the image itself
                images2.append(im)
        else:
            # Adaptive PIL algorithm
            AD = Image.ADAPTIVE
            for im in images:
                im = im.convert('P', palette=AD, dither=dither)
                images2.append(im)

        # Done
        return images2
项目:pixelsorter    作者:rkargon    | 项目源码 | 文件源码
def convertImagesToPIL(self, images, dither, nq=0, images_info=None):
        """ convertImagesToPIL(images, nq=0)

        Convert images to Paletted PIL images, which can then be
        written to a single animated GIF.

        """

        # Convert to PIL images
        images2 = []
        for im in images:
            if isinstance(im, Image.Image):
                images2.append(im)
            elif np and isinstance(im, np.ndarray):
                if im.ndim == 3 and im.shape[2] == 3:
                    im = Image.fromarray(im, 'RGB')
                elif im.ndim == 3 and im.shape[2] == 4:
                    # im = Image.fromarray(im[:,:,:3],'RGB')
                    self.transparency = True
                    im = Image.fromarray(im[:, :, :4], 'RGBA')
                elif im.ndim == 2:
                    im = Image.fromarray(im, 'L')
                images2.append(im)

        # Convert to paletted PIL images
        images, images2 = images2, []
        if nq >= 1:
            # NeuQuant algorithm
            for im in images:
                im = im.convert("RGBA")  # NQ assumes RGBA
                nqInstance = NeuQuant(im, int(nq))  # Learn colors from image
                if dither:
                    im = im.convert("RGB").quantize(palette=nqInstance.paletteImage(), colors=255)
                else:
                    im = nqInstance.quantize(im, colors=255)  # Use to quantize the image itself

                self.transparency = True  # since NQ assumes transparency
                if self.transparency:
                    alpha = im.split()[3]
                    mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
                    im.paste(255, mask=mask)
                images2.append(im)
        else:
            # Adaptive PIL algorithm
            AD = Image.ADAPTIVE
            # for index,im in enumerate(images):
            for i in range(len(images)):
                im = images[i].convert('RGB').convert('P', palette=AD, dither=dither, colors=255)
                if self.transparency:
                    alpha = images[i].split()[3]
                    mask = Image.eval(alpha, lambda a: 255 if a <= 128 else 0)
                    im.paste(255, mask=mask)
                images2.append(im)

        # Done
        return images2
项目:CAPE    作者:ctxis    | 项目源码 | 文件源码
def _get_icon_info(self):
        """Get icon in PNG format and information for searching for similar icons
        @return: tuple of (image data in PNG format encoded as base64, md5 hash of image data, md5 hash of "simplified" image for fuzzy matching)
        """
        if not self.pe:
            return None, None, None

        try:
            rt_group_icon_idx = [entry.id for entry in self.pe.DIRECTORY_ENTRY_RESOURCE.entries].index(pefile.RESOURCE_TYPE['RT_GROUP_ICON'])
            rt_group_icon_dir = self.pe.DIRECTORY_ENTRY_RESOURCE.entries[rt_group_icon_idx]
            entry = rt_group_icon_dir.directory.entries[0]
            offset = entry.directory.entries[0].data.struct.OffsetToData
            size = entry.directory.entries[0].data.struct.Size
            peicon = PEGroupIconDir(self.pe.get_memory_mapped_image()[offset:offset+size])
            bigwidth = 0
            bigheight = 0
            bigbpp = 0
            bigidx = -1
            iconidx = 0
            for idx,icon in enumerate(peicon.icons):
                if icon.bWidth >= bigwidth and icon.bHeight >= bigheight and icon.wBitCount >= bigbpp:
                    bigwidth = icon.bWidth
                    bigheight = icon.bHeight
                    bigbpp = icon.wBitCount
                    bigidx = icon.nID
                    iconidx = idx

            rt_icon_idx = [entry.id for entry in self.pe.DIRECTORY_ENTRY_RESOURCE.entries].index(pefile.RESOURCE_TYPE['RT_ICON'])
            rt_icon_dir = self.pe.DIRECTORY_ENTRY_RESOURCE.entries[rt_icon_idx]
            for entry in rt_icon_dir.directory.entries:
                if entry.id == bigidx:
                    offset = entry.directory.entries[0].data.struct.OffsetToData
                    size = entry.directory.entries[0].data.struct.Size
                    icon = peicon.get_icon_file(iconidx, self.pe.get_memory_mapped_image()[offset:offset+size])

                    strio = StringIO()
                    output = StringIO()

                    strio.write(icon)
                    strio.seek(0)
                    img = Image.open(strio)
                    img.save(output, format="PNG")

                    img = img.resize((8,8), Image.BILINEAR)
                    img = img.convert("RGB").convert("P", palette=Image.ADAPTIVE, colors=2).convert("L")
                    lowval = img.getextrema()[0]
                    img = img.point(lambda i: 255 if i > lowval else 0)
                    img = img.convert("1")
                    simplified = bytearray(img.getdata())

                    m = hashlib.md5()
                    m.update(output.getvalue())
                    fullhash = m.hexdigest()
                    m = hashlib.md5()
                    m.update(simplified)
                    simphash = m.hexdigest()
                    return base64.b64encode(output.getvalue()), fullhash, simphash
        except:
            pass

        return None, None, None
项目:artemis    作者:QUVA-Lab    | 项目源码 | 文件源码
def convertImagesToPIL(self, images, dither, nq=0):
        """ convertImagesToPIL(images, nq=0)

        Convert images to Paletted PIL images, which can then be
        written to a single animaged GIF.

        """

        # Convert to PIL images
        images2 = []
        for im in images:
            if isinstance(im, Image.Image):
                images2.append(im)
            elif np and isinstance(im, np.ndarray):
                if im.ndim==3 and im.shape[2]==3:
                    im = Image.fromarray(im,'RGB')
                elif im.ndim==3 and im.shape[2]==4:
                    im = Image.fromarray(im[:,:,:3],'RGB')
                elif im.ndim==2:
                    im = Image.fromarray(im,'L')
                images2.append(im)

        # Convert to paletted PIL images
        images, images2 = images2, []
        if nq >= 1:
            # NeuQuant algorithm
            for im in images:
                im = im.convert("RGBA") # NQ assumes RGBA
                nqInstance = NeuQuant(im, int(nq)) # Learn colors from image
                if dither:
                    im = im.convert("RGB").quantize(palette=nqInstance.paletteImage())
                else:
                    im = nqInstance.quantize(im)  # Use to quantize the image itself
                images2.append(im)
        else:
            # Adaptive PIL algorithm
            AD = Image.ADAPTIVE
            for im in images:
                im = im.convert('P', palette=AD, dither=dither)
                images2.append(im)

        # Done
        return images2
项目:Model-Free-Episodic-Control    作者:ShibiHe    | 项目源码 | 文件源码
def writeGif(filename, images, duration=0.1, loops=0, dither=1):
    """ writeGif(filename, images, duration=0.1, loops=0, dither=1)
    Write an animated gif from the specified images.
    images should be a list of numpy arrays of PIL images.
    Numpy images of type float should have pixels between 0 and 1.
    Numpy images of other types are expected to have values between 0 and 255.
    """

    if PIL is None:
        raise RuntimeError("Need PIL to write animated gif files.")

    AD = Image.ADAPTIVE
    images2 = []

    # convert to PIL
    for im in images:

        if isinstance(im,Image.Image):
            images2.append( im.convert('P', palette=AD, dither=dither) )

        elif np and isinstance(im, np.ndarray):
            if im.dtype == np.uint8:
                pass
            elif im.dtype in [np.float32, np.float64]:
                im = (im*255).astype(np.uint8)
            else:
                im = im.astype(np.uint8)
            # convert
            if len(im.shape)==3 and im.shape[2]==3:
                im = Image.fromarray(im,'RGB').convert('P', palette=AD, dither=dither)
            elif len(im.shape)==2:
                im = Image.fromarray(im,'L').convert('P', palette=AD, dither=dither)
            else:
                raise ValueError("Array has invalid shape to be an image.")
            images2.append(im)

        else:
            raise ValueError("Unknown image type.")

    # check duration
    if hasattr(duration, '__len__'):
        if len(duration) == len(images2):
            durations = [d for d in duration]
        else:
            raise ValueError("len(duration) doesn't match amount of images.")
    else:
        durations = [duration for im in images2]


    # open file
    fp = open(filename, 'wb')

    # write
    try:
        n = _writeGifToFile(fp, images2, durations, loops)
        print n, 'frames written'
    finally:
        fp.close()