Change image names systematically
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Zeynab Mousavikhamene
am 2 Nov. 2019
Kommentiert: Walter Roberson
am 2 Nov. 2019
I need to change the name of all images in a folder to numerical values like 1.jpg, 2.jpg, ...
I am using this code to do so:
selpath = uigetdir;
imagefiles = dir(fullfile(selpath, '*.jpg'));
% Loop through each
for id = 1:length(imagefiles)
% Get the file name (minus the extension)
[~, f] = fileparts(imagefiles(id).name);
movefile(f,num2str(id));
end
I get this error:
Error using movefile
No matching files were found.
Error in Rename_images (line 14)
movefile(f,num2str(id));
Any idea of why? and how can I fix this?
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 2 Nov. 2019
Bearbeitet: Walter Roberson
am 2 Nov. 2019
fileparts() and ignoring the first output gives you only the basic file name with no directory and no file extension. When you movefile() specifying only that basic file name, you are not telling it which directory to look in, so it would have no chance of finding the files unless your uigetdir() happened to select the current directory. And even if you did happen to be working with the current directory, the fact that you discarded the file extension is a problem.
You are also not naming a destination directory, which again is important because you do not want to move them into the current directory.
There is also a risk because your file names might already include numbered files.
selpath = uigetdir;
outdir = fullfile(selpath, 'renamed');
num_in_out = length( dir( fullfile(outdir, '*.jpg')) );
if ~exist(outdir, 'dir'); mkdir(outdir); end
imagefiles = dir(fullfile(selpath, '*.jpg'));
filenames = fullfile(selpath, {imagefiles.name});
% Loop through each
for id = 1:length(filenames)
thisfile = filenames{id};
outfile = fullfile(outdir, sprintf('%d.jpg', id+num_in_out));
movefile(thisfile, outfile);
end
This is designed to be able to resume if it is interrupted: it counts the number of files already in the output directory and continues numbering from there.
2 Kommentare
Weitere Antworten (0)
Siehe auch
Kategorien
Mehr zu File Operations finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!