Resize Images in bulk and maintain aspect ratio with python | python project for beginners

preview_player
Показать описание

Рекомендации по теме
Комментарии
Автор

from PIL import Image
import os

def resize(im, new_width):
width, height = im.size
ratio = height/width
new_height = int(ratio*new_width)
resized_image = im.resize((new_width, new_height))
return resized_image

files = os.listdir("assets")
extensions = ['jpg', 'png', 'jpeg']
for file in files:
ext = file.split('.')[-1]
if ext in extensions:
im = Image.open('assets/'+file)
im_resized = resize(im, 600)
new_dir = 'resized_images'
if not os.path.exists(new_dir):
os.makedirs(new_dir)
file = f'{new_dir}/{file}.jpg'
im_resized.save(file, 'png', quality=100)





Here you add the photos inside another folder called "assets" then it creates another folder with the resized images. Thanks for the video!

EduardoNicoleit
Автор

What's about fix height? Is new_width = int(ratio*new_height) ?

ThanasornsawanVarathanamongkol
Автор

I hope you put the code in the description for your followers. Thank you and good job.

zinaespoir
Автор

Here you are calculating new height, to maintain aspect ratio, but i want all images to resize to 224 X 224 by maintaining aspect ratio, what more should i do after resizing images as per your code

chitti
Автор

Hello sir, i tried follow the tutorial step by step. I would love to resize a 150 px image into 1080 px however, the result is still ugly. Could anyone here give me some advices

saudagarnegeriseberang
Автор

Sir,
i have some medical images with different sizes, I want to resize all of them to 224 X 224 without loosing aspect to do it sir

chitti