Change image names systematically

3 views (last 30 days)
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?

Accepted Answer

Walter Roberson
Walter Roberson on 2 Nov 2019
Edited: Walter Roberson on 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 Comments
Zeynab Mousavikhamene
Zeynab Mousavikhamene on 2 Nov 2019
Thanks Walter. I need to keep original files as well. Any idea?
Walter Roberson
Walter Roberson on 2 Nov 2019
Change from movefile() to copyfile()

Sign in to comment.

More Answers (0)

Categories

Find more on File Operations in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!