有没有我忽略的明显的方法?我只是想做个缩略图。


当前回答

我还推荐使用PIL的缩略图方法,因为它消除了所有的比例麻烦。

不过,有一个重要的提示:替换

im.thumbnail(size)

with

im.thumbnail(size,Image.ANTIALIAS)

默认情况下,PIL使用映像。最近的过滤器调整大小,结果良好的性能,但质量差。

其他回答

已经更新了上面的答案“tomvon”

from PIL import Image

img = Image.open(image_path)

width, height = img.size[:2]

if height > width:
    baseheight = 64
    hpercent = (baseheight/float(img.size[1]))
    wsize = int((float(img.size[0])*float(hpercent)))
    img = img.resize((wsize, baseheight), Image.ANTIALIAS)
    img.save('resized.jpg')
else:
    basewidth = 64
    wpercent = (basewidth/float(img.size[0]))
    hsize = int((float(img.size[1])*float(wpercent)))
    img = img.resize((basewidth,hsize), Image.ANTIALIAS)
    img.save('resized.jpg')
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)

如果你不想/不需要用Pillow打开图像,使用这个:

from PIL import Image

new_img_arr = numpy.array(Image.fromarray(img_arr).resize((new_width, new_height), Image.ANTIALIAS))

下面的脚本创建所有JPEG图像的漂亮缩略图,保留128x128最大分辨率的纵横比。

from PIL import Image
img = Image.open("D:\\Pictures\\John.jpg")
img.thumbnail((680,680))
img.save("D:\\Pictures\\John_resize.jpg")

定义最大大小。 然后,通过取min(maxwidth/width, maxheight/height)来计算调整大小的比率。

合适的尺寸是旧尺寸*比例。

当然,还有一个库方法可以做到这一点:Image.thumbnail方法。 下面是来自PIL文档的一个(编辑过的)示例。

import os, sys
import Image

size = 128, 128

for infile in sys.argv[1:]:
    outfile = os.path.splitext(infile)[0] + ".thumbnail"
    if infile != outfile:
        try:
            im = Image.open(infile)
            im.thumbnail(size, Image.Resampling.LANCZOS)
            im.save(outfile, "JPEG")
        except IOError:
            print "cannot create thumbnail for '%s'" % infile