souha
souha

Reputation: 1

How to batch rename images in several folders?

I have 600 images (e.g. images_0, images_1, images_2, ..., images_599) which are saved in 12 folders (e.g. dataset_1, dataset_2, dataset_3, ..., dataset_12).

I am currently using this code to rename images:

mainDirectory = 'C:\Users\Desktop\data';
subDirectory = dir([mainDirectory '/dataset_*']);
for m = 1 : length(subDirectory)
    subFolder = dir(fullfile(mainDirectory, subDirectory(m).name, '*.png'));
    fileNames = {subFolder.name};
    for iFile = 1 : numel( subFolder )
        newName = fullfile(mainDirectory, subDirectory(m).name, sprintf('%00d.png', iFile));
        movefile(fullfile(mainDirectory, subDirectory(m).name, fileNames{iFile}), newName);
    end
end

This code works well but I want to change the format of newName to the following: number-of-dataset_name-of-image (e.g. 1_images_0, 1_images_1, 2_images_0, 2_images_1, etc.). How can I make this change to newName?

Upvotes: 0

Views: 71

Answers (1)

Stephane
Stephane

Reputation: 21

You can first split your folder name to get the 1 to 12 number

str = strsplit('dataset_12', '_');     % split along '_'

The folder number will be in str{2}.

Then concatenate this piece of information with

new_name = [str{2} '_' original_image_name]

where original_image_name is the original image name (!) - or use alternatively sprintfas you already did.

Upvotes: 2

Related Questions