PIL:放大图像

9

我在使用PIL放大图片时遇到了问题。大图可以缩小,但小图无法变大。

# get the ratio of the change in height of this image using the
# by dividing the height of the first image
s = h / float(image.size[1])
# calculate the change in dimension of the new image
new_size = tuple([int(x*s) for x in image.size])
# if this image height is larger than the image we are sizing to
if image.size[1] > h: 
    # make a thumbnail of the image using the new image size
    image.thumbnail(new_size)
    by = "thumbnailed"
    # add the image to the images list
    new_images.append(image)
else:
    # otherwise try to blow up the image - doesn't work
    new_image = image.resize(new_size)
    new_images.append(new_image)
    by = "resized"
logging.debug("image %s from: %s to %s" % (by, str(image.size), str(new_size)))

你能否也请说明一下你是如何读取图像文件的? - doniyor
2个回答

23

resizetransform 方法都可以正确调整图像大小。

size_tuple = im.size
x1 = y1 = 0
x2, y2 = size_tuple

# resize
im = im.resize(size_tuple)

# transform
im = im.transform(size_tuple, Image.EXTENT, (x1,y1,x2,y2))

如果您遇到了我所描述的相同问题,请尝试在另一台机器上运行。我的服务器上的Python安装肯定有问题,在我的本地机器上可以正常工作。


使用负值来将图像居中:s = 1024 h,w = 768, 512 x1 = int(s//2) - (w//2) y1 = int(s//2) - (h//2) im = im.transform((s, s), Image.EXTENT, (-x1,-y1,s-x1,s-y1)) - fabrizioM

2

以下是使用openCV和numpy在各个方向上调整图像大小的工作示例:

import cv2, numpy

original_image = cv2.imread('original_image.jpg',0)
original_height, original_width = original_image.shape[:2]
factor = 2
resized_image = cv2.resize(original_image, (int(original_height*factor), int(original_width*factor)), interpolation=cv2.INTER_CUBIC )

cv2.imwrite('resized_image.jpg',resized_image)
#fixed var name

简单来说,你想要使用 "cv2.INTER_CUBIC" 进行放大 (系数 > 1),而使用 "cv2.INTER_AREA" 进行缩小图像 (系数 < 1)。

3
OP询问了有关在PIL框架中调整大小的问题。 - BjornW

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接