how to rename images using a loop?
Mostrar comentarios más antiguos
Hello. I have 150 images (images_0, images_1, images_2, ......, images_140) which are saved in 4 folders called : dataset_1, dataset_2, dataset_3 and dataset_4.
I use 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'm new in MATLAB and I want to change the newName as follows : (number of the dataset)_(name of the image)
For example : 1_images_0, 1_images_1, 2_images_0, 2_images_1, ...
Please, any idea how can I change the newName to rename the images? Please help me and thanks in advance.
6 comentarios
jgg
el 17 de Dic. de 2015
I'm not 100% clear on how your code works, but I think the easiest way would be to just concatenate the strings.
Inside the iFile = 1 loop:
newFileName = strcat(num2str(m), '_images_', num2str(iFile),'.png');
newName = fullfile(mainDirectory, subDirectory(m).name, newFileName);
Does that do what you intended? The '_images_','.png' part is hardcoded in this example for clarity, but you could replace it with fileNames{ iFile } and remove the last part if you want to be more flexible.
souha abdalah
el 17 de Dic. de 2015
Geoff Hayes
el 17 de Dic. de 2015
Why doesn't the solution from jgg not work as expected or isn't the solution that you want? An alternative is to just replace your sprintf call
sprintf('%00d.png',(iFile) )
with
sprintf('%d_images_%00d.png',m,iFile);
souha abdalah
el 17 de Dic. de 2015
jgg
el 17 de Dic. de 2015
Sorry, I'm not clear what's wrong with the solution I suggested? Are your folders not arranged in order (so dataset 2 is folder 4 for instance?). If so, you should be able to easy adjust the code I gave with a simple lookup matrix.
Geoff Hayes
el 17 de Dic. de 2015
Or just remove the dataset_ portion and convert the remainder to a string. For example,
folderName = 'dataset_42';
folderId = str2num(strrep(folderName,'dataset_',''));
Respuesta aceptada
Más respuestas (0)
Categorías
Más información sobre MATLAB Coder en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
