3

I'm in an introductory neural networking class so mind my ignorance. Also my first SO post.

I'm trying to resize some very highly resolved images within a dataset into 80x80p grayscale images in a new dataset. However, when I do this, I'd like to keep the filenames of each new image the same as the original image. The only way I know how to resave images into a new file is through a str(count) which isn't what I want. The filenames are important in creating a .csv file for my dataset later.

The only SO post I can find that is related is this:

Use original file name to save image

But the code suggested there didn't work - wasn't sure if I was going about it the wrong way.

import os
from PIL import Image
import imghdr
count=0
path1 = "/Users/..."
path2 = "/Users/..."
listing = os.listdir(path1)  
for file in listing:
    type = imghdr.what((path1 + file))
    if type == "jpeg":   
        img = Image.open("/Users/..." +file).convert('LA')
        img_resized = img.resize((80,80))
        img_resized.save(path2 + str(count) + '.png')
        count +=1
    pass
pass
qiki
  • 41
  • 3

2 Answers2

1

Reuse the original filename that you get from the for loop i.e. file and, split it into filename and extension using os.path.splitext() like below:

import os
from PIL import Image
import imghdr
count=0
path1 = "/Users/..."
path2 = "/Users/..."
listing = os.listdir(path1)  
for file in listing:
    type = imghdr.what((path1 + file))
    if type == "jpeg":   
        img = Image.open("/Users/..." +file).convert('LA')
        img_resized = img.resize((80,80))

        # splitting the original filename to remove extension
        img_filename = os.path.splitext(file)[0]
        img_resized.save(path2 + img_filename + '.png')
        count +=1
    pass

Another option, we can use python str's built-in split method to split the original filename by . and discard the extension.

import os
from PIL import Image
import imghdr
count=0
path1 = "/Users/..."
path2 = "/Users/..."
listing = os.listdir(path1)  
for file in listing:
    type = imghdr.what((path1 + file))
    if type == "jpeg":   
        img = Image.open("/Users/..." +file).convert('LA')
        img_resized = img.resize((80,80))

        # splitting the original filename to remove extension
        img_filename = file.split(".")[0]
        img_resized.save(path2 + img_filename + '.png')
        count +=1
    pass

So, if an image has a name such as some_image.jpeg then, the img_filename will have a value some_image as we splitted by . and discarded .jpeg part of it.

NOTE: This option assumes the original_filename will not contain any . other than the extension.

Wasi
  • 1,473
  • 3
  • 16
  • 32
0

I assume that image name is on path1. If so you can grap image name from there in this way:

x=path1.rsplit('/',1)[1]

We are splitting path1 on last slash and taking image name string via indexing.

Mert Köklü
  • 2,183
  • 2
  • 16
  • 20