PIL:放大图像
我在使用PIL(Python图像库)放大图片时遇到了问题。大图片可以很好地缩小,但小图片却无法放大。
# 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)))
2 个回答
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
就是这么简单。如果你想放大图片(放大倍数大于1),可以使用“cv2.INTER_CUBIC”;如果想缩小图片(放大倍数小于1),则可以使用“cv2.INTER_AREA”。
23
这段话的意思是,resize
和 transform
这两个方法都可以正确地调整图片的大小。
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安装出了问题,因为在我本地的电脑上运行得很好。