Change image names systematically
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
采纳的回答
Walter Roberson
2019-11-2
编辑:Walter Roberson
2019-11-2
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 个评论
更多回答(0 个)
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 File Operations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!