PIL: enlarge an image

Question:

I’m having trouble getting PIL to enlarge an image. Large images get scaled down just fine, but small images won’t get bigger.

# 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)))
Asked By: Grant Eagon

||

Answers:

Both resize and transform methods properly resize images.

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))

If you are having the same problem I described – try it on another machine. There must be something wrong with the python installation on my server. It worked fine on my local machine.

Answered By: Grant Eagon

Here is a working example how to resize an image in every direction with openCV and 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

Simple as that. You wanna use “cv2.INTER_CUBIC” to enlarge (factor > 1) and “cv2.INTER_AREA” to make the images smaller (factor < 1).

Answered By: cowhi