Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

upsizing images with cubic interpolation in python PIL

Hi I am simply trying to resize a batch of images of size (a,b,3) to a bigger size (c, d, 3) (c>a, d>b) using cubic interpolation. But whenever I opened the resized images again after I seemingly resized successfully in the first place, I found the old dimension... It happened to every image and every dimension in my trials... Could anyone kindly point out what I was missing? Thanks a lot!

Here is my code:

from PIL import Image
im = Image.open("img0.jpg").convert("RGB")
im # the original size
<PIL.Image.Image image mode=RGB size=600x337 at 0x102D83450>
im.resize((800,400),Image.BICUBIC)
<PIL.Image.Image image mode=RGB size=800x400 at 0x102D834D0> # thought I was doing it right
im.save("resized.jpg")
im=Image.open("resized.jpg").convert("RGB")
im
<PIL.Image.Image image mode=RGB size=600x337 at 0x102D83490> # and the actual size seems even smaller than before!
like image 265
shenglih Avatar asked Jul 25 '26 13:07

shenglih


1 Answers

The image resizing does not happen in-place. A new, resized image is returned, so you must save it.

new_img = im.resize((800,400),Image.BICUBIC)
new_img.save("resized.jpg")

or

im.resize((800,400),Image.BICUBIC).save("resized.jpg")

Whether or not a method or a function makes changes "in place" (which means there's no return value to grab and use, and a value of None is returned) or returns a value which you must use depends on the creator of the method or function. You can always, through trial and error, figure this out, but the better way is to look at the docs. For example, for the resize() method of PIL/Pillow, look at https://pillow.readthedocs.io/en/3.4.x/reference/Image.html#PIL.Image.Image.resize There you will see that the function

Returns a resized copy of this image.

That tells you that you have to do something with the return value in order to preserve the effects of the method.

Additionally, if you go to http://effbot.org/imagingbook/image.htm and jump down to resize, you 'll see it says:

resize #

im.resize(size) ⇒ image

im.resize(size, filter) ⇒ image

The "arrow" pointing to the right is notation which says that the method returns a value. In this case, it returns an image.

like image 150
Gary02127 Avatar answered Jul 27 '26 04:07

Gary02127



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!