szymanski
szymanski

Reputation: 51

How to keep the name of (jpg) files after prosessing?

I'm a noob and can not find something similar here so please help.

I try to cut segments of images out to analyze those later but everytime i run the code the images are in a different order and i'm not sure which segment belongs to which picture. However i want to keep the original name of the file but till now it doesn't worked out. I wrote this:

#iterate through folder and resize images to proceed later
from PIL import Image, ImageEnhance, ImageOps, ImageChops
import glob
for (i, filename) in enumerate(glob.glob('/Users/sszym/SHK/Bilder/*.jpg')):
   #print(filename)
   img = Image.open(filename).resize((2350, 1250))
   img.save('{}{}{}'.format('/Users/sszym/SHK/Bilder/resized/resized',i+1,'.jpg'))
#cut the segments of the resized images and save them
for (i, filename) in enumerate(glob.glob('/Users/sszym/SHK/Bilder/resized/*.jpg')):
    img = Image.open(filename)
    img_frank = img.crop((1610,0,2350,400))
    img_frank.save('{}{}{}'.format('C:/Users/sszym/SHK/Bilder/segments/Frankierzonen/frankierzone_',i+1,'.jpg'))
img_code = img.crop((850,1100,2350,1250))
img_code.save('{}{}{}'.format('C:/Users/sszym/SHK/Bilder/segments/Codierzonen/codierzone_',i+1,'.jpg'))

After those steps the segments are in a different order and i'm not sure what to do about it. I tried to put 'filename' into the naming but it is a path and i can't save it like this. Maybe you know how to keep the original name of the file after saving it in a different folder.

Best regards :)

Upvotes: 3

Views: 53

Answers (1)

JimmyCarlos
JimmyCarlos

Reputation: 1952

If we assume filename is something like /Users/sszym/SHK/Bilder/myPic.jpg, we could extract the myPic and use that in the filename.

for (i, filename) in enumerate(glob.glob('/Users/sszym/SHK/Bilder/*.jpg')):
   filename_no_ext = filename.split("/")[-1].split(".")[0]
   #print(filename)
   img = Image.open(filename).resize((2350, 1250))
   img.save('{}{}{}'.format('/Users/sszym/SHK/Bilder/resized/resized',filename_no_ext,'.jpg'))

Upvotes: 2

Related Questions