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

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

项目:Archur    作者:Foxboron    | 项目源码 | 文件源码
def generate_img(output="", theme={}, text="", resolution=(1920,1080)):

    # img = Image.open(backdrop)
    img = Image.new("RGB", resolution, theme["background"])
    W, H = img.size

    logo = Image.open(DEFAULT_DIR+"/assets/logo.png")
    colorized_img = ImageOps.colorize(logo.convert("L"), theme["text"], theme["background"])
    size = int((W/100)*17)
    logo_newsize = colorized_img.resize((size, size), Image.ANTIALIAS)
    img.paste(logo_newsize, (int((W-size)/2), int((H-size)/2)))

    draw = ImageDraw.Draw(img)

    base_font_pixle = int((56/1920)*resolution[0])

    font = ImageFont.truetype("DejaVuSansMono.ttf", base_font_pixle)
    w, h = font.getsize(text)

    text_draw(draw, text, base_font_pixle, img.size, theme)

    img.save(output, quality=100)
项目:Plamber    作者:OlegKlimenko    | 项目源码 | 文件源码
def resize_image(path, width):
    """
    Resizes the image.

    :param str path:  The path to the image file.
    :param int width: The width of the output image.
    """
    try:
        img = Image.open(path)

        ratio = width / float(img.width)
        height = int(float(img.height) * float(ratio))

        new_img = img.resize((width, height), Image.ANTIALIAS)
        new_img.save(path)

    except IOError:
        pass


# ----------------------------------------------------------------------------------------------------------------------
项目:code    作者:ActiveState    | 项目源码 | 文件源码
def resize(self,event):
        sc = self.canvas
        sc.delete(ALL)            # erase the whole canvas
        width  = sc.winfo_width()
        height = sc.winfo_height()

        imgSize = min(width, height)
        self.pad = imgSize/16
        viewport = (self.pad,self.pad,width-self.pad,height-self.pad)
        self.T = mapper(self.world,viewport)

        if self.showImage:
           flu = self.fluImg.resize((int(0.8*0.8*imgSize), int(0.8*imgSize)), Image.ANTIALIAS) 
           self.flu = ImageTk.PhotoImage(flu)
           sc.create_image(width/2,height/2,image=self.flu)
        else:
           self.canvas.create_rectangle([[0,0],[width,height]], fill = self.bgcolor)

        self.redraw()             # redraw the clock    

    ## Sets the clock colors.
    #
项目:HugoPhotoSwipe    作者:GjjvdBurg    | 项目源码 | 文件源码
def create_rescaled(self, mode):
        """ Do the actual resizing of images for modes without smartcrop """
        # get the desired dimensions
        nwidth, nheight = self.resize_dims(mode)
        logging.info("[%s] Creating %s image of dimensions: %ix%i" % 
                (self.name, mode, nwidth, nheight))

        # resize the image with PIL
        nimg = self.original_image.resize((nwidth, nheight), Image.ANTIALIAS)

        pth = self.large_path if mode == 'large' else self.small_path
        logging.info("[%s] Saving %s image to %s" % (self.name, mode, pth))
        if settings.output_format == 'jpg':
            nimg.save(pth, optimize=settings.jpeg_optimize, 
                    progressive=settings.jpeg_progressive, 
                    quality=settings.jpeg_quality)
        else:
            nimg.save(pth)
        return pth
项目: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
项目:photobooth    作者:eoghan-c    | 项目源码 | 文件源码
def resize_image(self, img_filename, new_width, new_height):
        img = Image.open(img_filename)
        img_width, img_height = img.size

        # First, resize the image
        if new_width > new_height:
            # Required image is Landscape
            scale_factor = float(new_width) / float(img_width)
            temp_width   = new_width
            temp_height  = int(float(img_height) * float(scale_factor))
        else:
            # Required image is Portrait (or Square)
            scale_factor = float(new_height) / float(img_height)
            temp_width   = int(float(img_width) * float(scale_factor))
            temp_height  = new_height

        img = img.resize((temp_width, temp_height), Image.ANTIALIAS)

        return img

    # Thanks Charlie Clark: http://code.activestate.com/recipes/577630-comparing-two-images/
项目:reddit-iambic-pentameter    作者:pmichel31415    | 项目源码 | 文件源码
def make_image(text, fontsize=45, output_file='tmp.png', fontname='HamletOrNot.ttf'):
    """Make an image out of a poem"""
    # Get font
    font = ImageFont.truetype(fontname, fontsize * factor)
    # Compute height
    num_lines = (1 + text.strip().count('\n'))
    height = num_lines * font.getsize(text[:10])[1] / factor + 2 * pad
    # Compute width
    font_length = max(font.getsize(line)[0] for line in text.split('\n'))
    width = font_length / factor + 2 * pad
    # Create big image and draw text
    image = Image.new("RGBA", (width * factor, height * factor), (241, 241, 212))
    draw = ImageDraw.Draw(image)
    draw.text((pad * factor, pad * factor), text, (0, 0, 0), font=font)
    # Resize with antialiasing
    img_resized = image.resize((width, height), Image.ANTIALIAS)
    # Save to file
    img_resized.save(output_file)
项目:Software-Architecture-with-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def thumbnail_image(filename, size=(64,64), format='.png'):
    """ Convert image thumbnails, given a filename """

    try:
        im=Image.open(filename)         
        im.thumbnail(size, Image.ANTIALIAS)

        basename = os.path.basename(filename)
        thumb_filename = os.path.join('thumbs',
                                      basename.rsplit('.')[0] + '_thumb.png')
        im.save(thumb_filename)
        print('Saved',thumb_filename)
        return True

    except Exception as e:
        print('Error converting file',filename)
        raise
        return False
项目:Software-Architecture-with-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def thumbnail_image(self, url, size=(64,64), format='.png'):
        """ Save image thumbnails, given a URL """

        im = Image.open(urllib.request.urlopen(url))
        # filename is last two parts of URL minus extension + '.format'
        pieces = url.split('/')
        filename = ''.join((pieces[-2],'_',pieces[-1].split('.')[0],format))        
        try:
            im.thumbnail(size, Image.ANTIALIAS)
            im.save(filename)
            print('Saved',filename)
            self.count += 1
        except Exception as e:
            print('Error saving URL',url,e)
            # Image can't be counted, increment semaphore
            self.release()

        return True
项目:Software-Architecture-with-Python    作者:PacktPublishing    | 项目源码 | 文件源码
def thumbnail_image(self, url, size=(64,64), format='.png'):
        """ Save image thumbnails, given a URL """

        im=Image.open(urllib.request.urlopen(url))
        # filename is last two parts of URL minus extension + '.format'
        pieces = url.split('/')
        filename = ''.join((pieces[-2],'_',pieces[-1].split('.')[0],format))        
        try:
            im.thumbnail(size, Image.ANTIALIAS)
            im.save(filename)
            print('Saved',filename)
            self.count += 1
        except Exception as e:
            print('Error saving URL',url,e)
            # Image can't be counted, increment semaphore
            self.release()

        return True
项目:cleverhans    作者:tensorflow    | 项目源码 | 文件源码
def download_image(image_id, url, x1, y1, x2, y2, output_dir):
    """Downloads one image, crops it, resizes it and saves it locally."""
    output_filename = os.path.join(output_dir, image_id + '.png')
    if os.path.exists(output_filename):
        # Don't download image if it's already there
        return True
    try:
        # Download image
        url_file = urlopen(url)
        if url_file.getcode() != 200:
            return False
        image_buffer = url_file.read()
        # Crop, resize and save image
        image = Image.open(BytesIO(image_buffer)).convert('RGB')
        w = image.size[0]
        h = image.size[1]
        image = image.crop((int(x1 * w), int(y1 * h), int(x2 * w),
                            int(y2 * h)))
        image = image.resize((299, 299), resample=Image.ANTIALIAS)
        image.save(output_filename)
    except IOError:
        return False
    return True
项目:polapi-zero    作者:pierre-muth    | 项目源码 | 文件源码
def printImageFile(filename):
    print 'prints ', filename
    # resize to printer resolution and send to printer
    try:
        image = Image.open(filename)
        im_width, im_height = image.size
        if im_width > im_height:
            image = image.rotate(90, expand=1)
            im_width, im_height = image.size
        ratio = (PRINTER_HEIGHT/float(im_width))
        height = int((float(im_height)*float(ratio)))
        image = image.resize((PRINTER_HEIGHT, height), Image.ANTIALIAS)

        printer.printImage(image, False)
        printer.justify('C')
        printer.setSize('S')
        printer.println("PolaPi-Zero")
        printer.feed(3)
    except IOError:
        print ("cannot identify image file", filename)
项目:polapi-zero    作者:pierre-muth    | 项目源码 | 文件源码
def displayImageFileOnLCD(filename):
    print 'displays ', filename
    title = 'Review Mode'
    # resize/dither to screen resolution and send to LCD
    image = Image.open(filename)
    im_width, im_height = image.size
    if im_width < im_height:
        image = image.rotate(90)
    image.thumbnail(S_SIZE, Image.ANTIALIAS)
    image_sized = Image.new('RGB', S_SIZE, (0, 0, 0))
    image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2))
    # draw filename
    draw = ImageDraw.Draw(image_sized)
    font = ImageFont.truetype('arial.ttf', 18)
    draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0))
    draw.text((2, 2), title, fill='black', font=font)
    draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0))
    draw.text((290, 218), filename, fill='black', font=font)
    # display on LCD
    image_sized = ImageOps.invert(image_sized)
    image_sized = image_sized.convert('1') # convert image to black and white
    lcd.write(image_sized.tobytes())
项目:polapi-zero    作者:pierre-muth    | 项目源码 | 文件源码
def displayImageFileOnLCD(filename):
    print 'displays ', filename
    title = 'Review Mode'
    # resize/dither to screen resolution and send to LCD
    image = Image.open(filename)
    im_width, im_height = image.size
    if im_width < im_height:
        image = image.rotate(90)
    image.thumbnail(S_SIZE, Image.ANTIALIAS)
    image_sized = Image.new('RGB', S_SIZE, (0, 0, 0))
    image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2))
    # draw filename
    draw = ImageDraw.Draw(image_sized)
    font = ImageFont.truetype('arial.ttf', 18)
    draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0))
    draw.text((2, 2), title, fill='black', font=font)
    draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0))
    draw.text((290, 218), filename, fill='black', font=font)
    # display on LCD
    image_sized = ImageOps.invert(image_sized)
    image_sized = image_sized.convert('1') # convert image to black and white
    lcd.write(image_sized.tobytes())
项目:polapi-zero    作者:pierre-muth    | 项目源码 | 文件源码
def printImageFile(filename):
    print 'prints ', filename
    # resize to printer resolution and send to printer
    try:
        image = Image.open(filename)
        im_width, im_height = image.size
        if im_width > im_height:
            image = image.rotate(90, expand=1)
            im_width, im_height = image.size
        ratio = (PRINTER_HEIGHT/float(im_width))
        height = int((float(im_height)*float(ratio)))
        image = image.resize((PRINTER_HEIGHT, height), Image.ANTIALIAS)

        printer.printImage(image, False)
        printer.justify('C')
        printer.setSize('S')
        printer.println("PolaPi-Zero")
        printer.feed(3)
    except IOError:
        print ("cannot identify image file", filename)
项目:polapi-zero    作者:pierre-muth    | 项目源码 | 文件源码
def displayImageFileOnLCD(filename):
    print 'displays ', filename
    title = 'Review Mode'
    # resize/dither to screen resolution and send to LCD
    image = Image.open(filename)
    im_width, im_height = image.size
    if im_width < im_height:
        image = image.rotate(90)
    image.thumbnail(S_SIZE, Image.ANTIALIAS)
    image_sized = Image.new('RGB', S_SIZE, (0, 0, 0))
    image_sized.paste(image,((S_SIZE[0] - image.size[0]) / 2, (S_SIZE[1] - image.size[1]) / 2))
    # draw filename
    draw = ImageDraw.Draw(image_sized)
    font = ImageFont.truetype('arial.ttf', 18)
    draw.rectangle([(0, 0), (115, 22)], fill=(255,255,255), outline=(0,0,0))
    draw.text((2, 2), title, fill='black', font=font)
    draw.rectangle([(279, 217), (399, 239)], fill=(255,255,255), outline=(0,0,0))
    draw.text((290, 218), filename, fill='black', font=font)
    # display on LCD
    image_sized = ImageOps.invert(image_sized)
    image_sized = image_sized.convert('1') # convert image to black and white
    lcd.write(image_sized.tobytes())
项目:polapi-zero    作者:pierre-muth    | 项目源码 | 文件源码
def printImageFile(filename):
    print 'prints ', filename
    # resize to printer resolution and send to printer
    try:
        image = Image.open(filename)
        im_width, im_height = image.size
        if im_width > im_height:
            image = image.rotate(90)
        image.thumbnail((P_HEIGHT, P_WIDTH), Image.ANTIALIAS)
        printer.printImage(image, False)
        printer.justify('C')
        printer.setSize('S')
        printer.println("PolaPi-Zero")
        printer.feed(3)
    except IOError:
        print ("cannot identify image file", filename)
项目:polapi-zero    作者:pierre-muth    | 项目源码 | 文件源码
def printImageFile(filename):
    print 'prints ', filename
    # resize to printer resolution and send to printer
    try:
        image = Image.open(filename)
        im_width, im_height = image.size
        if im_width > im_height:
            image = image.rotate(90)
        image.thumbnail((P_HEIGHT, P_WIDTH), Image.ANTIALIAS)
        printer.printImage(image, False)
        printer.justify('C')
        printer.setSize('S')
        printer.println("PolaPi-Zero")
        printer.feed(3)
    except IOError:
        print ("cannot identify image file", filename)
项目:nostray_prototype    作者:nostray    | 项目源码 | 文件源码
def pImgResize(filename):
    image = Image.open(filename)
    image.thumbnail((640,360),Image.ANTIALIAS)
    url = 'post_img/%Y/%m' + image.name
    name = settings.MEDIA_URL + url

    if os.path.exists(name):
        fname, ext = os.path.splitext(image.name)
        fname = fname[0:4] + str(random.randint(0,10000))
        image.name = fname + ext
        url = 'post_img/%Y/%m' + image.name
        name = settings.MEDIA_URL + url

        image.save(name, 'jpg')

        return url
    else:
        image = None

        return None
项目:enet-keras    作者:PavlosMelissinos    | 项目源码 | 文件源码
def resize(item, target_h, target_w, keep_aspect_ratio=False):
    """
    Resizes an image to match target dimensions
    :type item: np.ndarray
    :type target_h: int
    :type target_w: int
    :param item: 3d numpy array or PIL.Image
    :param target_h: height in pixels
    :param target_w: width in pixels
    :param keep_aspect_ratio: If False then image is rescaled to smallest dimension and then cropped
    :return: 3d numpy array
    """
    img = array_to_img(item, scale=False)
    if keep_aspect_ratio:
        img.thumbnail((target_w, target_w), PILImage.ANTIALIAS)
        img_resized = img
    else:
        img_resized = img.resize((target_w, target_h), resample=PILImage.NEAREST)

    # convert output
    img_resized = img_to_array(img_resized)
    img_resized = img_resized.astype(dtype=np.uint8)

    return img_resized
项目:gps2video    作者:teawater    | 项目源码 | 文件源码
def photos_paste(self, pipe, prev_point, point):
        show_camera = False

        while len(self.photos) != 0:
            (d, photo) = self.photos[0]
            if d < prev_point.time:
                self.photos.pop(0)
                continue
            if d > point.time:
                return show_camera
            print "????:", photo
            image = Image.open(photo).convert("RGBA")
            image = image.resize(self.get_fit_size(image.size), Image.ANTIALIAS)
            x_expand = (self.cf.video_width - image.size[0]) / 2
            y_expand = (self.cf.video_height - image.size[1]) / 2
            image = ImageOps.expand(image, (x_expand,y_expand,x_expand,y_expand), fill="white")
            for i in range(self.cf.video_fps * self.cf.photos_show_secs):
                image.save(pipe.stdin, 'PNG')
            self.photos.pop(0)
            show_camera = True

        return show_camera
项目:touch-pay-client    作者:HackPucBemobi    | 项目源码 | 文件源码
def __call__(self, value):
        if isinstance(value, str) and len(value) == 0:
            return (value, None)
        from PIL import Image
        from io import BytesIO
        try:
            img = Image.open(value.file)
            img.thumbnail((self.nx, self.ny), Image.ANTIALIAS)
            s = BytesIO()
            if self.padding:
                background = Image.new('RGBA', (self.nx, self.ny), (255, 255, 255, 0))
                background.paste(
                    img,
                    ((self.nx - img.size[0]) // 2, (self.ny - img.size[1]) // 2))
                background.save(s, 'JPEG', quality=self.quality)
            else:
                img.save(s, 'JPEG', quality=self.quality)
            s.seek(0)
            value.file = s
        except:
            return (value, self.error_message)
        else:
            return (value, None)
项目:iOSAppIconGenerator    作者:dorukgezici    | 项目源码 | 文件源码
def run():
    if Data.image_path == "":
        output_label["text"] = "Choose the image file first."
        return
    if os.access("{}/AppIcon.appiconset".format(Data.save_path), os.W_OK) == False:
        os.mkdir("{}/AppIcon.appiconset".format(Data.save_path))
    file = open("{}/AppIcon.appiconset/Contents.json".format(Data.save_path), mode="w")
    json.dump(json_data, file, indent=4, sort_keys=True, separators=(',', ':'))
    file.close()

    with open("{}/AppIcon.appiconset/Contents.json".format(Data.save_path), mode="r") as data_file:
        data = json.load(data_file)
        images = data["images"]
        try:
            im = Image.open(Data.image_path)
            output_label["text"] = "Image specs: {} {} {}\n{}\n".format(im.format, im.size, im.mode, "-"*35)
            for image in images:
                size = get_size(image)
                out = im.resize(size, Image.ANTIALIAS)
                out.save("{}/AppIcon.appiconset/{}".format(Data.save_path, image["filename"]), format="PNG")
                output_label["text"] += "Image generated: {}\n".format(size)
            open_saved_button.grid(row=1, column=0, columnspan=2, sticky=tk.W+tk.E)
        except IOError:
            output_label["text"] = "Please select a supported image file."
项目:index_crawler    作者:workinDead    | 项目源码 | 文件源码
def rec_img(img):

    width = img.size[0]
    height = img.size[1]
    #???????
    rangle = (24.5+6.1*length+5,int(height/2),int(width),int(height))  #???????
    # ??????
    img = img.crop(rangle)
    # ?????
    (x, y) = img.size
    x_s = int(x*2.4)
    y_s = int(y*2.4)
    imgzoom = img.resize((x_s,y_s),Image.ANTIALIAS)
    code = tesseract.image_to_string(imgzoom)
    result = re.sub("\D", "", code)
    return result
项目:micromasters    作者:mitodl    | 项目源码 | 文件源码
def make_thumbnail(full_size_image, max_dimension):
    """
    Make a thumbnail of the image

    Args:
        full_size_image (file):
            A file-like object containing an image. This file will seek back to the beginning after being read.
        max_dimension (int):
            The max size of a dimension for the thumbnail
    Returns:
        BytesIO:
            A jpeg image which is a thumbnail of full_size_image
    """
    pil_image = Image.open(full_size_image)
    pil_image.thumbnail(shrink_dimensions(pil_image.width, pil_image.height, max_dimension), Image.ANTIALIAS)
    buffer = BytesIO()
    pil_image.save(buffer, "JPEG", quality=90)
    buffer.seek(0)
    return buffer
项目:congress-headshots-lambda    作者:datadesk    | 项目源码 | 文件源码
def convert(img_path,name):
    print img_path,name
    name = name.split('.')[0]

    png = Image.open(img_path).convert('RGBA')

    print 'creating images (%s)' % name
    for x in range(0,len(sizes)):
        resized = png.resize((sizes[x],sizes[x]), Image.ANTIALIAS)
        resized.save('/tmp/transparent.png', quality=100)
        upload_path = '%s/%s' % (name,sizes[x])
        s3_client.put_object(Key='%s/transparent.png' % (upload_path), Bucket=output_bucket, Body=open('/tmp/transparent.png','rb'), ContentType='image/png')
        for color in colors:
            background = Image.new("RGBA",(sizes[x],sizes[x]),ImageColor.getrgb(colors[color]))
            background.paste(resized ,(0,0), resized)
            filename = '/tmp/%s%s.jpg' % (sizes[x],color)
            background.save(filename, quality=95)
            s3_client.put_object(Key='%s/%s.jpg' % (upload_path,color), Bucket=output_bucket, Body=open(filename,'rb'), ContentType='image/jpeg')
项目: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
项目:photobooth    作者:LoiX07    | 项目源码 | 文件源码
def process_new_picture(self):
        """ Process the new picture """
        while True:
            if not self.queue.empty():
                name = self.queue.get()
                if name == 'exit':
                    return
                # Create a compressed picture for faster display
                image_orig = Image.open(name)
                image_resized = image_orig.resize((800,480),Image.ANTIALIAS)
                new_image_name = os.path.basename(name)
                new_image_name = os.path.splitext(new_image_name)[0] + ".jpg"
                new_path = os.path.join(self.picture_compressed_path, new_image_name)
                image_resized.save(new_path, quality=98, optimize=True, progressive=True)
                # send the picture name through a TCP socket
                with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
                    # Connect to server and send data
                    sock.connect((HOST, PORT))
                    sock.sendall(bytes(os.path.join(PICTURE_FOLDER, new_image_name) + "\n", "utf-8"))
            sleep(0.2)
项目:Comictagger    作者:dickloraine    | 项目源码 | 文件源码
def average_hash(self):
        try:
            image = self.image.resize((self.width, self.height), Image.ANTIALIAS).convert("L")
        except Exception as e:
            sys.exc_clear()
            print "average_hash error:", e
            return long(0)

        pixels = list(image.getdata())
        avg = sum(pixels) / len(pixels)

        def compare_value_to_avg(i):
            return ( 1 if i > avg else 0 )

        bitlist = map(compare_value_to_avg, pixels)

        # build up an int value from the bit list, one bit at a time
        def set_bit( x, (idx, val) ):
            return (x | (val << idx))
项目:Comictagger    作者:dickloraine    | 项目源码 | 文件源码
def average_hash2( self ):
        pass
        """
        # Got this one from somewhere on the net.  Not a clue how the 'convolve2d'
        # works! 

        from numpy import array 
        from scipy.signal import convolve2d

        im = self.image.resize((self.width, self.height), Image.ANTIALIAS).convert('L')

        in_data = array((im.getdata())).reshape(self.width, self.height)
        filt = array([[0,1,0],[1,-4,1],[0,1,0]])
        filt_data = convolve2d(in_data,filt,mode='same',boundary='symm').flatten()

        result = reduce(lambda x, (y, z): x | (z << y),
                         enumerate(map(lambda i: 0 if i < 0 else 1, filt_data)),
                         0)
        #print "{0:016x}".format(result)
        return result
        """
项目:tflearn    作者:tflearn    | 项目源码 | 文件源码
def resize_image(in_image, new_width, new_height, out_image=None,
                 resize_mode=Image.ANTIALIAS):
    """ Resize an image.

    Arguments:
        in_image: `PIL.Image`. The image to resize.
        new_width: `int`. The image new width.
        new_height: `int`. The image new height.
        out_image: `str`. If specified, save the image to the given path.
        resize_mode: `PIL.Image.mode`. The resizing mode.

    Returns:
        `PIL.Image`. The resize image.

    """
    img = in_image.resize((new_width, new_height), resize_mode)
    if out_image:
        img.save(out_image)
    return img
项目:pandachaika    作者:pandabuilder    | 项目源码 | 文件源码
def save_img(self, img_link: str) -> None:
        tf2 = NamedTemporaryFile()
        request_file = requests.get(img_link, stream='True', timeout=25)

        for chunk in request_file.iter_content(4096):
            tf2.write(chunk)
        self.image.save(os.path.splitext(img_link)[1], File(tf2), save=False)
        tf2.close()
        im = PImage.open(self.image.path)
        if im.mode != 'RGB':
            im = im.convert('RGB')

        # large thumbnail
        im.thumbnail((200, 290), PImage.ANTIALIAS)
        thumb_relative_path = upload_announce_thumb_handler(self, os.path.splitext(img_link)[1])
        thumb_fn = pjoin(settings.MEDIA_ROOT, thumb_relative_path)
        os.makedirs(os.path.dirname(thumb_fn), exist_ok=True)
        im.save(thumb_fn, "JPEG")
        self.thumbnail.name = thumb_relative_path

        self.save()
项目:pandachaika    作者:pandabuilder    | 项目源码 | 文件源码
def copy_img(self, img_path: str) -> None:
        tf2 = NamedTemporaryFile()

        shutil.copy(img_path, tf2.name)

        self.image.save(os.path.splitext(img_path)[1], File(tf2), save=False)
        tf2.close()
        im = PImage.open(self.image.path)
        if im.mode != 'RGB':
            im = im.convert('RGB')

        # large thumbnail
        im.thumbnail((200, 290), PImage.ANTIALIAS)
        thumb_relative_path = upload_announce_thumb_handler(self, os.path.splitext(img_path)[1])
        thumb_fn = pjoin(settings.MEDIA_ROOT, thumb_relative_path)
        os.makedirs(os.path.dirname(thumb_fn), exist_ok=True)
        im.save(thumb_fn, "JPEG")
        self.thumbnail.name = thumb_relative_path

        self.save()
项目:pandachaika    作者:pandabuilder    | 项目源码 | 文件源码
def regen_tn(self) -> None:
        if not self.image:
            return
        im = PImage.open(self.image.path)
        if im.mode != 'RGB':
            im = im.convert('RGB')

        # large thumbnail
        im.thumbnail((200, 290), PImage.ANTIALIAS)

        thumb_fn = upload_announce_thumb_handler(self, os.path.splitext(self.image.name)[1])
        os.makedirs(os.path.dirname(thumb_fn), exist_ok=True)
        im.save(pjoin(settings.MEDIA_ROOT, thumb_fn), "JPEG")
        self.thumbnail.name = thumb_fn

        self.save()
项目:chn_handwriting    作者:zhangchunsheng    | 项目源码 | 文件源码
def inference(image):
    print('inference')
    temp_image = Image.open(image).convert('L')
    temp_image = temp_image.resize((FLAGS.image_size, FLAGS.image_size), Image.ANTIALIAS)
    temp_image = np.asarray(temp_image) / 255.0
    temp_image = temp_image.reshape([-1, 64, 64, 1])
    with tf.Session() as sess:
        logger.info('========start inference============')
        # images = tf.placeholder(dtype=tf.float32, shape=[None, 64, 64, 1])
        # Pass a shadow label 0. This label will not affect the computation graph.
        graph = build_graph(top_k=3)
        saver = tf.train.Saver()
        ckpt = tf.train.latest_checkpoint(FLAGS.checkpoint_dir)
        if ckpt:
            saver.restore(sess, ckpt)
        predict_val, predict_index = sess.run([graph['predicted_val_top_k'], graph['predicted_index_top_k']],
                                              feed_dict={graph['images']: temp_image, graph['keep_prob']: 1.0})
    return predict_val, predict_index
项目:sealionengine    作者:gecrooks    | 项目源码 | 文件源码
def _load_image(self, itype, tid, scale=1, border=0):
        fn = self.path(itype, tid=tid)

        # Workaround for weird issue in pillow that throws ResourceWarnings
        with open(fn, 'rb') as img_file:
            with Image.open(img_file) as image:
                if scale != 1:
                    width, height = image.size # width x height for PIL
                    image = image.resize((width//scale, height//scale), Image.ANTIALIAS)

                img = np.asarray(image)

        if border:
            height, width, channels = img.shape
            bimg = np.zeros(shape=(height+border*2, width+border*2, channels), dtype=np.uint8)
            bimg[border:-border, border:-border, :] = img
            img = bimg
        return img
项目:true_review_web2py    作者:lucadealfaro    | 项目源码 | 文件源码
def __call__(self, value):
        if isinstance(value, str) and len(value) == 0:
            return (value, None)
        from PIL import Image
        import cStringIO
        try:
            img = Image.open(value.file)
            img.thumbnail((self.nx, self.ny), Image.ANTIALIAS)
            s = cStringIO.StringIO()
            img.save(s, 'JPEG', quality=self.quality)
            s.seek(0)
            value.file = s
        except:
            return (value, self.error_message)
        else:
            return (value, None)
项目:ImgPy    作者:vladlenomg    | 项目源码 | 文件源码
def get_thumbnail(imgpath, save_name):
    img = Image.open(imgpath)
    size = (400, 350)
    img_ratio = img.size[0] / float(img.size[1])
    ratio = size[0] / float(size[1])

    if img.format == 'GIF': 
        print("gif!")
        img = img.convert('RGB')

    if ratio > img_ratio:
        img = img.resize((size[0], int(round(size[0] * img.size[1] / img.size[0]))),Image.ANTIALIAS)
        box = (0, int(round((img.size[1] - size[1]) / 2)), img.size[0],int(round((img.size[1] + size[1]) / 2)))
        img = img.crop(box)
    elif ratio < img_ratio:
        img = img.resize((int(round(size[1] * img.size[0] / img.size[1])), size[1]),Image.ANTIALIAS)
        box = (int(round((img.size[0] - size[0]) / 2)), 0,int(round((img.size[0] + size[0]) / 2)), img.size[1])
        img = img.crop(box)
    else :
            img = img.resize((size[0], size[1]), Image.ANTIALIAS)

    img.save(save_name, "JPEG")
项目:spc    作者:whbrewer    | 项目源码 | 文件源码
def __call__(self, value):
        if isinstance(value, str) and len(value) == 0:
            return (value, None)
        from PIL import Image
        import cStringIO
        try:
            img = Image.open(value.file)
            img.thumbnail((self.nx, self.ny), Image.ANTIALIAS)
            s = cStringIO.StringIO()
            img.save(s, 'JPEG', quality=100)
            s.seek(0)
            value.file = s
        except:
            return (value, self.error_message)
        else:
            return (value, None)
项目:SimGAN_pytorch    作者:AlexHex7    | 项目源码 | 文件源码
def butchered_mp_normalized_matlab_helper(mat_file_path):
    """
    Normalized data is provided in matlab files in MPIIGaze Dataset and these are tricky to load with Python.
    This function was made with guessing and checking. Very frustrating.

    :param mat_file_path: Full path to MPIIGaze Dataset matlab file.
    :return: np array of images.
    """
    x = sio.loadmat(mat_file_path)
    y = x.get('data')
    z = y[0, 0]

    left_imgs = z['left']['image'][0, 0]
    right_imgs = z['right']['image'][0, 0]

    for img in np.concatenate((left_imgs, right_imgs)):
        Image.fromarray(img).resize((55, 35), resample=Image.ANTIALIAS).save(
            os.path.join(save_dir, '{}.png'.format(uuid.uuid4())))

    return
项目:pcbot    作者:pckv    | 项目源码 | 文件源码
def resize(message: discord.Message, image_arg: image, resolution: parse_resolution, *options,
                 extension: str.lower=None):
    """ Resize an image with the given resolution formatted as `<width>x<height>`
    or `*<scale>` with an optional extension. """
    if extension:
        image_arg.set_extension(extension)

    # Generate a new image based on the scale
    if resolution[1] == 0:
        w, h = image_arg.object.size
        scale = resolution[0]
        assert w * scale < 3000 and h * scale < 3000, "**The result image must be less than 3000 pixels in each axis.**"
        resolution = (int(w * scale), int(h * scale))

    # Resize and upload the image
    image_arg.modify(Image.Image.resize, resolution, Image.NEAREST if "-nearest" in options else Image.ANTIALIAS)
    await send_image(message, image_arg)
项目:JetsonTX1_im2txt    作者:Netzeband    | 项目源码 | 文件源码
def _openImage(self):
    FileTypes = [('JPG Image Files', '*.jpg'), ('All files', '*')]
    Dialog = tkFileDialog.Open(self._ControlFrame, filetypes = FileTypes)
    FileName = Dialog.show()

    if not FileName == '' and not FileName == ():
      print("Open file: "+str(FileName))

      if self._IsVideoRunnung:
        self._pressPause()

      Image = image.open(FileName)
      Image = Image.resize(self._getLabelSize(self._VideoLabel, Image.width/Image.height), image.ANTIALIAS)
      Image = imagetk.PhotoImage(Image)
      self._VideoLabel.imgtk = Image
      self._VideoLabel.configure(image=Image)          

      self._OutputText.delete('1.0', tk.END)

      File = tf.gfile.GFile(FileName, "r")
      Captions = self._CaptionFunc(File.read())

      for i, Caption in enumerate(Captions):
        self._OutputText.insert(tk.END, str(i+1)+") "+Caption+"\n")
项目:script-tools    作者:rhyspang    | 项目源码 | 文件源码
def resize_img(img_name):
    splited_img_name = os.path.splitext(img_name)

    img = Image.open(img_name)
    print 'imgname', img.filename
    if img.size == (args.width, args.height):
        return

    resized_img = img.resize((args.width, args.height), Image.ANTIALIAS)

    resized_name = splited_img_name[0]+"_resized" + splited_img_name[1]
    resized_img.save(
        RESULT_FOLDER + os.path.sep + resized_name)

    print("Resize {} ====> {}".format(
        img.filename, RESULT_FOLDER + os.path.sep + resized_name))
项目:mal    作者:chaosking121    | 项目源码 | 文件源码
def genHash(filePath, hashSize = 8):
        from PIL import Image

        image = Image.open(filePath)

        image = image.convert('L').resize((hashSize + 1, hashSize), Image.ANTIALIAS)

        difference = []
        for row in xrange(hashSize):
            for col in xrange(hashSize):
                pixelLeft = image.getpixel((col, row))
                pixelRight = image.getpixel((col + 1, row))
                difference.append(pixelLeft > pixelRight)

        decimalValue = 0
        hexString = []
        for index, value in enumerate(difference):
            if value:
                decimalValue += 2**(index % 8)
            if ((index % 8) == 7):
                hexString.append(hex(decimalValue)[2:].rjust(2, '0'))
                decimalValue = 0

        return ''.join(hexString)
项目:Imagyn    作者:zevisert    | 项目源码 | 文件源码
def scale(img, scaling_factor):
    """
    Scale Image
    :param img: PIL image object
    :param scaling_factor: Integer size to scale by
    :return: PIL image object
    """
    try:
        original_width, original_height = img.size
        img.thumbnail(
            (original_height * scaling_factor, original_width * scaling_factor),
            Image.ANTIALIAS
        )

        return img
    except IOError as e:
        print(e)
项目:utils    作者:jianbing    | 项目源码 | 文件源码
def screenshot_ex(self, screenshot_dir, info='shot', compress=True, openfile=True):
        """??take_screenshot????????????????

        :param screenshot_dir:
        :param info:
        :param compress:
        :param openfile:
        :return:
        """
        result = self.screenshot(screenshot_dir, info)
        print('result is {0}'.format(os.path.normpath(result)))
        if compress:
            im = Image.open(result)
            im_size = im.size
            im = im.resize((int(im_size[0] / 2), int(im_size[1] / 2)), Image.ANTIALIAS)  # ??????
            # im = im.rotate(270, expand=1)   # ?????????????expand??????????????

            new_file = result.replace(r".png", r".jpg")  # ???????????
            im.save(new_file)
            os.remove(result)

            if openfile:
                cmd = r"mspaint {0}".format(new_file)   # ???????
                os.popen(cmd)
项目:Problematica-public    作者:TechMaz    | 项目源码 | 文件源码
def __call__(self, value):
        if isinstance(value, str) and len(value) == 0:
            return (value, None)
        from PIL import Image
        import cStringIO
        try:
            img = Image.open(value.file)
            img.thumbnail((self.nx, self.ny), Image.ANTIALIAS)
            s = cStringIO.StringIO()
            if self.padding:
                background = Image.new('RGBA', (self.nx, self.ny), (255, 255, 255, 0))
                background.paste(
                    img,
                    ((self.nx - img.size[0]) / 2, (self.ny - img.size[1]) / 2))
                background.save(s, 'JPEG', quality=self.quality)
            else:
                img.save(s, 'JPEG', queality=self.quality)
            s.seek(0)
            value.file = s
        except:
            return (value, self.error_message)
        else:
            return (value, None)
项目:google-open-image-download    作者:ejlb    | 项目源码 | 文件源码
def scale(content, min_dim):
    """ Aspect-ratio preserving scale such that the smallest dim is equal to `min_dim` """

    image = Image.open(content)

    # no scaling, keep images full size
    if min_dim == -1:
        return image

    # aspect-ratio preserving scale so that the smallest dimension is `min_dim`
    width, height = image.size
    scale_dimension = width if width < height else height
    scale_ratio = float(min_dim) / scale_dimension

    if scale_ratio == 1:
        return image

    return image.resize(
        (int(width * scale_ratio), int(height * scale_ratio)),
        Image.ANTIALIAS,
    )
项目:RobotframeworkAuto-for-PEP_PRO    作者:xiaoyaojjian    | 项目源码 | 文件源码
def img(self, Local_initial_address, i, local_store_address):
        print Local_initial_address, i, local_store_address
        # tt = u'lvziqing'
        im = Image.open(Local_initial_address)
        text = time.ctime()
        width, height = im.size
        print width, height
        txt = Image.new('RGB', im.size, (0, 0, 0, 0))
        text_width = (txt.size[0] - 280)
        text_height = (txt.size[1] - 130)
        # watermark = txt.resize((text_width,text_height), Image.ANTIALIAS)
        draw = ImageDraw.Draw(txt, 'RGBA')  # ???????
        draw.text((text_width, text_height),
                  text, fill=(255,255,255))
        watermark = txt.rotate(23, Image.BICUBIC)
        alpha = watermark.split()[2]
        alpha = ImageEnhance.Brightness(alpha).enhance(0.50)
        watermark.putalpha(alpha)
        a = local_store_address + 'ceshi' + str(i) + '.jpg'
        Image.composite(watermark, im, watermark).save(a, 'JPEG')
        return a
项目:chainer-began    作者:hvy    | 项目源码 | 文件源码
def get_example(self, i):
        path = self.paths[i]

        with Image.open(path) as f:
            if self.crop is not None:
                f = f.crop(self.crop)
            if self.size is not None:
                f = f.resize(self.size, Image.ANTIALIAS)
            im = np.asarray(f, dtype=np.float32)

        # NOTE: Uncomment if it is necessary to modify the image
        # im = im.copy()

        im = im.transpose((2, 0, 1))

        # Rescale from [0, 255] to [-1, 1]
        im *= (2 / 255)
        im -= 1

        return im