本文整理匯總了Python中PIL.ImageOps.fit方法的典型用法代碼示例。如果您正苦於以下問題:Python ImageOps.fit方法的具體用法?Python ImageOps.fit怎麽用?Python ImageOps.fit使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類PIL.ImageOps
的用法示例。
在下文中一共展示了ImageOps.fit方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: resize_gif
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def resize_gif(im: GifImageFile, size: int=DEFAULT_EMOJI_SIZE) -> bytes:
frames = []
duration_info = []
# If 'loop' info is not set then loop for infinite number of times.
loop = im.info.get("loop", 0)
for frame_num in range(0, im.n_frames):
im.seek(frame_num)
new_frame = Image.new("RGBA", im.size)
new_frame.paste(im, (0, 0), im.convert("RGBA"))
new_frame = ImageOps.fit(new_frame, (size, size), Image.ANTIALIAS)
frames.append(new_frame)
duration_info.append(im.info['duration'])
out = io.BytesIO()
frames[0].save(out, save_all=True, optimize=True,
format="GIF", append_images=frames[1:],
duration=duration_info,
loop=loop)
return out.getvalue()
示例2: download_image
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def download_image(url, title):
uaurl = request.Request(url, headers={'User-Agent': 'wallpaper-reddit python script by /u/MarcusTheGreat7'})
f = request.urlopen(uaurl)
print("downloading " + url)
try:
img = Image.open(f).convert('RGB')
if config.resize:
config.log("resizing the downloaded wallpaper")
img = ImageOps.fit(img, (config.minwidth, config.minheight), Image.ANTIALIAS)
if config.settitle:
img = set_image_title(img, title)
if config.opsys == "Windows":
img.save(config.walldir + '\\wallpaper.bmp', "BMP")
else:
img.save(config.walldir + '/wallpaper.jpg', "JPEG")
except IOError:
print("Error saving image!")
sys.exit(1)
# in - string, string - path of the image to set title on, title for image
示例3: multi_setup_pillow
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def multi_setup_pillow(monitors, save_path, wp_setter_func=None):
images = list(map(Image.open, [m.wallpaper for m in monitors]))
resolutions = [(m.width * m.scaling, m.height * m.scaling) for m in monitors]
offsets = [(m.offset_x, m.offset_y) for m in monitors]
# DEBUG
# for m in monitors:
# print(m)
final_image_width = max([m.offset_x + m.width * m.scaling for m in monitors])
final_image_height = max([m.offset_y + m.height * m.scaling for m in monitors])
# DEBUG
# print('Final Size: {} x {}'.format(final_image_width, final_image_height))
n_images = []
for i, r in zip(images, resolutions):
n_images.append(fit(i, r, method=Image.LANCZOS))
final_image = Image.new('RGB', (final_image_width, final_image_height))
for i, o in zip(n_images, offsets):
final_image.paste(i, o)
final_image.save(save_path)
示例4: get_img_batch
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def get_img_batch(files_list,
secret_size,
batch_size=4,
size=(400,400)):
batch_cover = []
batch_secret = []
for i in range(batch_size):
img_cover_path = random.choice(files_list)
try:
img_cover = Image.open(img_cover_path).convert("RGB")
img_cover = ImageOps.fit(img_cover, size)
img_cover = np.array(img_cover, dtype=np.float32) / 255.
except:
img_cover = np.zeros((size[0],size[1],3), dtype=np.float32)
batch_cover.append(img_cover)
secret = np.random.binomial(1, .5, secret_size)
batch_secret.append(secret)
batch_cover, batch_secret = np.array(batch_cover), np.array(batch_secret)
return batch_cover, batch_secret
示例5: forward
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def forward(self, input_image):
(width, height) = (self.width, self.height)
# Resize image to work with neural network.
if height < input_image.height < input_image.width:
new_height = height
new_width = new_height * input_image.width // input_image.height
else:
new_width = width
new_height = new_width * input_image.height // input_image.width
image = input_image.resize((new_width, new_height), Image.ANTIALIAS)
image = ImageOps.fit(image, (width, height), Image.ANTIALIAS)
# Generate predictions.
image_tensor = torch.Tensor(np.array(image) / 255.0)
input_image = image_tensor.permute(2, 0, 1)
image_normalized = self.preprocess(input_image)
out = self.net(image_normalized[None, :, :, :].to(self.device))
return out
示例6: generate_ascii
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def generate_ascii(self, image):
font = ImageFont.truetype(str(cog_data_path(self)) + "/FreeMonoBold.ttf", 15)
image_width, image_height = image.size
aalib_screen_width = int(image_width / 24.9) * 10
aalib_screen_height = int(image_height / 41.39) * 10
screen = aalib.AsciiScreen(width=aalib_screen_width, height=aalib_screen_height)
im = image.convert("L").resize(screen.virtual_size)
screen.put_image((0, 0), im)
y = 0
how_many_rows = len(screen.render().splitlines())
new_img_width, font_size = font.getsize(screen.render().splitlines()[0])
img = Image.new("RGBA", (new_img_width, how_many_rows * 15), (255, 255, 255))
draw = ImageDraw.Draw(img)
for lines in screen.render().splitlines():
draw.text((0, y), lines, (0, 0, 0), font=font)
y += 15
imagefit = ImageOps.fit(img, (image_width, image_height), Image.ANTIALIAS)
return imagefit
示例7: save
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def save(self, data, file_id=None, metadata={}, THUMB_SIZE=()):
if file_id is None:
file_id = unicode(uuid.uuid4())
with open(self._get_filename(file_id), "w") as f:
f.write(data)
# Store metadata
with open(self._get_metadata_filename(file_id), "w") as f:
f.write(json.dumps(metadata))
img = None
try:
img = Image.open(self._get_filename(file_id))
except IOError:
log.info('Not an image file, skipping medium & thumbnail generation')
else:
# Store thumbnail & medium
kw = {}
if 'transparency' in img.info:
kw['transparency'] = img.info["transparency"]
orig_width, orig_height = img.size
medium_size = self.MEDIUM_WIDTH, int(float(self.MEDIUM_WIDTH) * orig_height / orig_width)
medium = img.copy()
medium.thumbnail(medium_size, Image.ANTIALIAS)
medium.save(self._get_filename(file_id, 'medium'), img.format, quality=75, **kw) # 'JPEG')
thumb = ImageOps.fit(img, THUMB_SIZE if THUMB_SIZE else self.THUMB_SIZE, Image.ANTIALIAS)
thumb.save(self._get_filename(file_id, 'thumb'), img.format, quality=75, **kw) # 'JPEG')
return file_id
示例8: resize_avatar
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def resize_avatar(image_data: bytes, size: int=DEFAULT_AVATAR_SIZE) -> bytes:
try:
im = Image.open(io.BytesIO(image_data))
im = exif_rotate(im)
im = ImageOps.fit(im, (size, size), Image.ANTIALIAS)
except OSError:
raise BadImageError(_("Could not decode image; did you upload an image file?"))
except DecompressionBombError:
raise BadImageError(_("Image size exceeds limit."))
out = io.BytesIO()
if im.mode == 'CMYK':
im = im.convert('RGB')
im.save(out, format='png')
return out.getvalue()
示例9: resize_emoji
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def resize_emoji(image_data: bytes, size: int=DEFAULT_EMOJI_SIZE) -> bytes:
try:
im = Image.open(io.BytesIO(image_data))
image_format = im.format
if image_format == "GIF":
# There are a number of bugs in Pillow.GifImagePlugin which cause
# results in resized gifs being broken. To work around this we
# only resize under certain conditions to minimize the chance of
# creating ugly gifs.
should_resize = any((
im.size[0] != im.size[1], # not square
im.size[0] > MAX_EMOJI_GIF_SIZE, # dimensions too large
len(image_data) > MAX_EMOJI_GIF_FILE_SIZE_BYTES, # filesize too large
))
return resize_gif(im, size) if should_resize else image_data
else:
im = exif_rotate(im)
im = ImageOps.fit(im, (size, size), Image.ANTIALIAS)
out = io.BytesIO()
im.save(out, format=image_format)
return out.getvalue()
except OSError:
raise BadImageError(_("Could not decode image; did you upload an image file?"))
except DecompressionBombError:
raise BadImageError(_("Image size exceeds limit."))
### Common
示例10: test_1pxfit
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def test_1pxfit(self):
# Division by zero in equalize if image is 1 pixel high
newimg = ImageOps.fit(hopper("RGB").resize((1, 1)), (35, 35))
self.assertEqual(newimg.size, (35, 35))
newimg = ImageOps.fit(hopper("RGB").resize((1, 100)), (35, 35))
self.assertEqual(newimg.size, (35, 35))
newimg = ImageOps.fit(hopper("RGB").resize((100, 1)), (35, 35))
self.assertEqual(newimg.size, (35, 35))
示例11: update_preview
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def update_preview(self, widget):
if self.item:
#get a crop for the preview
#box = tuple((int(round(v)) for v in widget.coords(self.item)))
box = self.getRealBox()
pbox = self.getPreviewBox()
if fast_preview:
preview = self.image.crop(pbox) # region of interest
else:
preview = self.imageOrig.crop(box) # region of interest
#add black borders for correct aspect ratio
#if preview.size[0] > 512:
preview.thumbnail(self.image.size, Image.ANTIALIAS) #downscale to preview rez
paspect = preview.size[0]/float(preview.size[1])
aspect = self.image.size[0]/float(self.image.size[1])
if paspect < aspect:
bbox = (0, 0, int(preview.size[1] * aspect), preview.size[1])
else:
bbox = (0, 0, preview.size[0], int(preview.size[0] / aspect))
preview = ImageOps.expand(preview, border=((bbox[2]-preview.size[0])//2, (bbox[3]-preview.size[1])//2))
#preview = ImageOps.fit(preview, size=self.image.size, method=Image.ANTIALIAS, bleed=-10.0)
#resize to preview rez (if too small)
self.preview = preview.resize(self.image.size, Image.ANTIALIAS)
self.previewPhoto = ImageTk.PhotoImage(self.preview)
self.previewLabel.configure(image=self.previewPhoto)
print str(box[2]-box[0])+"x"+str(box[3]-box[1])+"+"+str(box[0])+"+"+str(box[1])
示例12: process_image
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def process_image(self, image, image_format, save_kwargs,
width, height):
"""
Return a BytesIO instance of `image` cropped to `width` and `height`.
Cropping will first reduce an image down to its longest side
and then crop inwards centered on the Primary Point of Interest
(as specified by `self.ppoi`)
"""
imagefile = BytesIO()
palette = image.getpalette()
cropped_image = self.crop_on_centerpoint(
image,
width,
height,
self.ppoi
)
# Using ImageOps.fit on GIFs can introduce issues with their palette
# Solution derived from: http://stackoverflow.com/a/4905209/1149774
if image_format == 'GIF':
cropped_image.putpalette(palette)
cropped_image.save(
imagefile,
**save_kwargs
)
return imagefile
示例13: download_and_resize_image
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def download_and_resize_image(url, new_width=256, new_height=256,
display=False):
_, filename = tempfile.mkstemp(suffix=".jpg")
response = urlopen(url)
image_data = response.read()
image_data = BytesIO(image_data)
pil_image = Image.open(image_data)
pil_image = ImageOps.fit(pil_image, (new_width, new_height), Image.ANTIALIAS)
pil_image_rgb = pil_image.convert("RGB")
pil_image_rgb.save(filename, format="JPEG", quality=90)
print("Image downloaded to %s." % filename)
if display:
display_image(pil_image)
return filename
示例14: resize_imgs
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def resize_imgs(self, path):
for i, img_path in enumerate(glob.glob(path)):
print(i, img_path)
img = Image.open(img_path)
img = ImageOps.fit(img, (self.img_size[0], self.img_size[1]), Image.ANTIALIAS)
name = img_path.split("\\")[-1].split('.')[0]
if not os.path.exists(f"resized_{self.img_size[0]}_{self.img_size[1]}"):
os.makedirs(f"resized_{self.img_size[0]}_{self.img_size[1]}")
img.save(f"resized_{self.img_size[0]}_{self.img_size[1]}/{name}.png")
示例15: image_to_tensor
# 需要導入模塊: from PIL import ImageOps [as 別名]
# 或者: from PIL.ImageOps import fit [as 別名]
def image_to_tensor(pil_image):
#resize image
resized=ImageOps.fit(pil_image, imgsize, Image.ANTIALIAS)
# transform it into a torch tensor
loader = transforms.Compose([
transforms.ToTensor()])
return loader(resized).unsqueeze(0) #need to add one dimension, need to be 4D to pass into the network
#load model