0

I have a folder that includes a big amount of images (five categories of vegetables) have certain names (image ID), also I have a CSV file, which includes two columns, the first is the images ID, and the second is the label (each image ID is paired with label 0,1,2,3 or 4) How can I rename the images in this folder to take the labels as a new name using python?!

Iko-SOF
  • 77
  • 1
  • 7
  • it looks like a duplicate of renaming files using python: https://stackoverflow.com/questions/8858008/how-to-move-a-file – Verthais Dec 27 '20 at 13:11

1 Answers1

0

You can just rename your files using standard os module

import os
os.rename('YOU_CURRENT_IMAGE_NAME.jpg', 'NEW_NAME.jpg')

let's assume that you have an image with name my_pic.jpg and you want to rename it with ID=abc and labe=2, then code looks like this:

import os

def rename_image(existing_name, _id, label):
    existing_name = 'my_pic.jpg'
    extension = existing_name.split('.')[-1]

    new_name = f'{_id}-{label}.{extension}'
    os.rename(existing_name, new_name)

rename_image('my_pic.jpg', 'abc', 2)
# new name is: abc-2.jpg

[EDITED] Let's assume that you have a folder called 'images', all your images are stored in this folder, and you have a csv file like this:

old_name1.jpg,new_name_001.jpg
another_old_pic.svg,new_name_for_this.svg

A simple snippet to rename all files in this case would be like this:

import os
import csv

IMG_FOLDER = 'images'  # name of your image folder
CUR_PATH = os.getcwd()  # current working directory
img_dir = os.path.join(CUR_PATH, IMG_FOLDER)  # full path to images folder
with open('images.csv') as csv_file:
    csv_data = csv.reader(csv_file)
    images = os.listdir(img_dir)  # a list of file names in images folder
    for row in csv_data:
        # we iterate over each row in csv and rename files
        old_name, new_name = row
        # we are just checking in case file exists in folder
        if old_name in images:
            # main part: renaming the file
            os.rename(
                os.path.join(CUR_PATH, IMG_FOLDER, old_name),
                os.path.join(CUR_PATH, IMG_FOLDER, new_name)
            )
        else:
            print(f"Image {old_name!r} not found, skipping...")

You can tweak the renaming part, and add anything you want to new image name (you wanted to include some kind of label, I guess?).

  • Thanks for your script, actually the situation is a bit different. You can think of it this way. The csv file has two columns one is the current_names (old names), and the other is the new_names. So I'd like to change all the images names in the folder to be the new_names @Jasurbek_NURBOYEV – Iko-SOF Dec 27 '20 at 14:20
  • Can you check the answer now, I edited it @Iko-SOF – Jasurbek NURBOYEV Dec 28 '20 at 15:31