有没有我忽略的明显的方法?我只是想做个缩略图。
当前回答
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)
其他回答
举个丑陋的例子。
函数获取像pic[0-9a-z]这样的文件。[扩展]",将它们调整为120x120,移动部分到中心,并保存到"ico[0-9a-z]。[扩展]”,肖像和风景作品:
def imageResize(filepath):
from PIL import Image
file_dir=os.path.split(filepath)
img = Image.open(filepath)
if img.size[0] > img.size[1]:
aspect = img.size[1]/120
new_size = (img.size[0]/aspect, 120)
else:
aspect = img.size[0]/120
new_size = (120, img.size[1]/aspect)
img.resize(new_size).save(file_dir[0]+'/ico'+file_dir[1][3:])
img = Image.open(file_dir[0]+'/ico'+file_dir[1][3:])
if img.size[0] > img.size[1]:
new_img = img.crop( (
(((img.size[0])-120)/2),
0,
120+(((img.size[0])-120)/2),
120
) )
else:
new_img = img.crop( (
0,
(((img.size[1])-120)/2),
120,
120+(((img.size[1])-120)/2)
) )
new_img.save(file_dir[0]+'/ico'+file_dir[1][3:])
基于@tomvon,我完成了以下使用(选择你的案例):
a)调整高度(我知道新的宽度,所以我需要新的高度)
new_width = 680
new_height = new_width * height / width
b)调整宽度(我知道新的高度,所以我需要新的宽度)
new_height = 680
new_width = new_height * width / height
然后:
img = img.resize((new_width, new_height), Image.ANTIALIAS)
只是用更现代的包装器更新了这个问题 这个图书馆包枕头(PIL的一个叉子) https://pypi.org/project/python-resize-image/
允许你这样做:-
from PIL import Image
from resizeimage import resizeimage
fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_width(img, 200)
img.save('test-image-width.jpeg', img.format)
fd_img.close()
在上面的链接中有更多的例子。
我用这种方法调整了图像的大小,效果很好
from io import BytesIO
from django.core.files.uploadedfile import InMemoryUploadedFile
import os, sys
from PIL import Image
def imageResize(image):
outputIoStream = BytesIO()
imageTemproaryResized = imageTemproary.resize( (1920,1080), Image.ANTIALIAS)
imageTemproaryResized.save(outputIoStream , format='PNG', quality='10')
outputIoStream.seek(0)
uploadedImage = InMemoryUploadedFile(outputIoStream,'ImageField', "%s.jpg" % image.name.split('.')[0], 'image/jpeg', sys.getsizeof(outputIoStream), None)
## For upload local folder
fs = FileSystemStorage()
filename = fs.save(uploadedImage.name, uploadedImage)
对我来说最简单的方法
image = image.resize((image.width*2, image.height*2), Image.ANTIALIAS)
例子
from PIL import Image, ImageGrab
image = ImageGrab.grab(bbox=(0,0,400,600)) #take screenshot
image = image.resize((image.width*2, image.height*2), Image.ANTIALIAS)
image.save('Screen.png')