-2

I have the following code that resizes the image by a number hardcoded

I would like it to resize using the following formula - image_size / 2

f = r'C:\Users\elazar\bucket\PHOTO'
for file in os.listdir(f):
    f_img = f+"/"+file
    img = Image.open(f_img).resize((540,540)).save(f_img)

Is it possible to shorten this code to fewer lines and instead of using something like 540,540 be able to cut the original size (divide) by 2

I've tried following some other formula that I couldn't fully understand here Open CV Documentation

Elazar
  • 190
  • 7
  • And why do you want to reduce amount of lines? Are you running some embedded system where a few bytes make some difference? Then you should look at other programming languages, python is not the most memory efficient. – STerliakov Nov 27 '22 at 11:16
  • It is work for a client and one of his requests – Elazar Nov 27 '22 at 11:18

1 Answers1

2

".size" gives the width and height of a picture as a tuple. You can replace the code below with your 4th line.

Image.open(f_img).resize((int(Image.open(f_img).size[0] / 2), int(Image.open(f_img).size[1] / 2))).save(f_img)

However, this one line code is much more inefficient than the code below. It opens the image 3 times instead of one time.

image = Image.open(f_img)
image.resize((int(image.size[0] / 2), int(image.size[1] / 2))).save(f_img)