Change image names systematically

조회 수: 3 (최근 30일)
Zeynab Mousavikhamene
Zeynab Mousavikhamene 2019년 11월 2일
댓글: Walter Roberson 2019년 11월 2일
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?

채택된 답변

Walter Roberson
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
Zeynab Mousavikhamene
Zeynab Mousavikhamene 2019년 11월 2일
Thanks Walter. I need to keep original files as well. Any idea?
Walter Roberson
Walter Roberson 2019년 11월 2일
Change from movefile() to copyfile()

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 File Operations에 대해 자세히 알아보기

태그

Community Treasure Hunt

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

Start Hunting!

Translated by