How to save image with same name with python?

Question:

I have image folder as below :

|------dir--|
|           |---- input--|-- 1.jpg
|           |            |-- 2.jpg
..          ...          ...   ...

where I want to do random rotation for input folder and save the results in output folder

I tryied the fillowing script :

import torch
import torchvision.transforms as T
from PIL import Image
import os
from os import listdir

folder_dir = "/dir/input/"
out_dir = "dir/output/"
imgs = os.listdir(folder_dir) 
print(imgs)
for img in imgs:
  img = Image.open(folder_dir+img)
  print(type(img))
  # define a transform
  transform = T.RandomRotation(degrees=(0,360))
  img = transform(img)

  # display result
  img.show()
  img.save(f'{out_dir}{img}.jpg')
  print('ok')

I got resulting image in output dir with object name R<PIL.Image.Image image mode=L size=988x128 at 0x7FD72613DBE0>.jpg but I expact to save image name with same input image name for example if I have read 1.jpg in input dir I expact to save it as it is name 1.jpg after rotation done

| ---dir ---|
|           | 
|           |---- output |
|           |            |-- 1.jpg
|           |            |-- 2.jpg
..          ...          ...   ... 

Answers:

You overwrite your variable img with the image name by the image object when calling img = Image.open(...), thats why you get the object info instead. You can just rename one of the variables:

#...
for img_name in imgs:
  img = Image.open(folder_dir + img_name)
  # ...
  img.save(f'{out_dir}{img_name}.jpg')
Answered By: user_na