MATLAB: Changing part of the image’s name contained in a folder

rename images

Hello,
I'm new to Matlab and I have a dataset folder that containing 10000 images; what iIwant is to rename the images from this pattern ( 0_1.jpg, 0_2.jpg,….,99_10000.jpg) to be (1.jpg, 2.jpg,……, 10000.jpg) I want to delete the part before the underscore and the underscore, I already tried this code :
a ='D:\Corel-10k\Corel100';% folder containing images
A =dir( fullfile(a, '*.jpg') );
fileNames = { A.name };
for iFile = 1 : numel( A )
newName = fullfile(a, sprintf( '%d.jpg', iFile ) );
movefile( fullfile(a, fileNames{ iFile }), newName );
end
but the images took different numbers than before renaming ( Please note that every 100 image belong to a class, afterrenaming using the above code it is mixed ).
thanks in advance,

Best Answer

Try this (untested)
folder ='D:\Corel-10k\Corel100';% folder containing images
A = dir(fullfile(folder, '*.jpg'));
for iFile = 1 : numel( A )
thisFolder = A(iFile).folder;
thisBaseName = A(iFile).name;
underscoreLocation = strfind(thisBaseName, '_')
if ~isempty(underscoreLocation)
newBaseName = thisBaseName(underscoreLocation+1 : end);
else
newBaseName = thisBaseName;
end
oldFullFileName = fullfile(thisFolder, thisBaseName);
newFullFileName = fullfile(thisFolder, newBaseName);
movefile(oldFullFileName, newFullFileName);
end