Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PIL: enlarge an image

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)))
like image 663
Grant Eagon Avatar asked Mar 09 '11 19:03

Grant Eagon


People also ask

How do I make a picture bigger in PIL?

To resize an image, you call the resize() method on it, passing in a two-integer tuple argument representing the width and height of the resized image. The function doesn't modify the used image; it instead returns another Image with the new dimensions.

Is PIL better than OpenCV?

OpenCV+albumentations is faster than PIL+torchvisionDataLoader by using cv2.


2 Answers

For anyone reading this, having the same problem - try it on another machine. I got both

im = im.resize(size_tuple)

and

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

to properly resize files. There must be something wrong with the python installation on my server. Worked fine on my local machine.

like image 153
Grant Eagon Avatar answered Sep 19 '22 13:09

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

like image 45
cowhi Avatar answered Sep 17 '22 13:09

cowhi