有没有我忽略的明显的方法?我只是想做个缩略图。
当前回答
我试图为幻灯片视频调整一些图像的大小,因此,我想要的不仅仅是一个最大维度,而是一个最大宽度和最大高度(视频帧的大小)。 而且总有可能拍一个人像视频…… 图像。缩略图方法是有前途的,但我不能使它放大一个较小的图像。
所以当我在这里(或其他地方)找不到明显的方法时,我写了这个函数,并把它放在这里:
from PIL import Image
def get_resized_img(img_path, video_size):
img = Image.open(img_path)
width, height = video_size # these are the MAX dimensions
video_ratio = width / height
img_ratio = img.size[0] / img.size[1]
if video_ratio >= 1: # the video is wide
if img_ratio <= video_ratio: # image is not wide enough
width_new = int(height * img_ratio)
size_new = width_new, height
else: # image is wider than video
height_new = int(width / img_ratio)
size_new = width, height_new
else: # the video is tall
if img_ratio >= video_ratio: # image is not tall enough
height_new = int(width / img_ratio)
size_new = width, height_new
else: # image is taller than video
width_new = int(height * img_ratio)
size_new = width_new, height
return img.resize(size_new, resample=Image.LANCZOS)
其他回答
如果你不想/不需要用Pillow打开图像,使用这个:
from PIL import Image
new_img_arr = numpy.array(Image.fromarray(img_arr).resize((new_width, new_height), Image.ANTIALIAS))
# Importing Image class from PIL module
from PIL import Image
# Opens a image in RGB mode
im = Image.open(r"C:\Users\System-Pc\Desktop\ybear.jpg")
# Size of the image in pixels (size of original image)
# (This is not mandatory)
width, height = im.size
# Setting the points for cropped image
left = 4
top = height / 5
right = 154
bottom = 3 * height / 5
# Cropped image of above dimension
# (It will not change original image)
im1 = im.crop((left, top, right, bottom))
newsize = (300, 300)
im1 = im1.resize(newsize)
# Shows the image in image viewer
im1.show()
import cv2
from skimage import data
import matplotlib.pyplot as plt
from skimage.util import img_as_ubyte
from skimage import io
filename='abc.png'
image=plt.imread(filename)
im=cv2.imread('abc.png')
print(im.shape)
im.resize(300,300)
print(im.shape)
plt.imshow(image)
打开图像文件
from PIL import Image
im = Image.open("image.png")
使用PIL Image。Resize (size, resample=0)方法,其中将图像的(宽度,高度)替换为2元组大小。
这将显示原始大小的图像:
display(im.resize((int(im.size[0]),int(im.size[1])), 0) )
这将显示图像大小的1/2:
display(im.resize((int(im.size[0]/2),int(im.size[1]/2)), 0) )
这将显示你的图像的1/3大小:
display(im.resize((int(im.size[0]/3),int(im.size[1]/3)), 0) )
这将显示你的图像的1/4大小:
display(im.resize((int(im.size[0]/4),int(im.size[1]/4)), 0) )
等等
from PIL import Image
img = Image.open('/your image path/image.jpg') # image extension *.png,*.jpg
new_width = 200
new_height = 300
img = img.resize((new_width, new_height), Image.ANTIALIAS)
img.save('output image name.png') # format may what you want *.png, *jpg, *.gif