Using switch case to rename files in a folder
Afficher commentaires plus anciens
I have a folder of .png files which have a timestamp printed on them. Unfortunately, the only metadata in the .png files is the date, so I am having to manually create a timestamp for the filename of each image. To do this, I first of all numbered each .png from each day from 0001-end. For the first day of each batch of images, I can then look at which number=what time, and add that time to the filename. This is what I have done here:
%5th May 2020, Louise Wilson
%Rename files in a folder.
location=('H:\Cameras\Cameras_frames\SiteOne_rename'); %place where files to be renamed are
d=dir(fullfile(location, '*png')); %list all files in folder
files=length(d); %number of files in folder
for i=1:files
%get site
site=strsplit(location, {'\', '_'});
site=site(5);
%get date
file=strsplit(d(i).name, {'-', '.'});
filedate=file(1); %yyyymmdd
%get number
framenumber=char(file(2)); %####.png
%get time
switch framenumber
case '0001'
timeis='0600';
case '0002'
timeis='0640';
case '0003'
timeis='0650';
case '0004'
timeis='0700';
case '0005'
timeis='0710';
case '0006'
timeis='0720';
case '0007'
timeis='0730';
case '0008'
timeis='0740';
otherwise
error('Unknown time!');
end
%}
newfilename=char(strcat(site, '-', filedate, timeis, '-', framenumber));
%newfilename=char(strcat(site, '-', (d(i).name)));
movefile(fullfile(location, d(i).name), fullfile (location, newfilename)); %rename file
clearvars -except location folder d files folderparts sitename
end
I have removed some of the times to shorten the code but the times actually cover a full day up to 2000.
My problem is that this is quite a long bit of code and also, for the many batches of images I have, the first frame number on each day is not always the same time. The first time depends on when the camera was triggered and that changes every month or so when I check the camera.
I would like to be able to say what the first frame is, and rather than then subsequently list all of the other times, just say that the second image is the first image, plus 10 minutes.
To try to explain clearly:
case '0001'
timeis='0600';
case '0002'
timeis= %case0001+10mins;
case '0003'
timeis=%case0001+20mins;
So, perhaps some sort of loop to increase the case number by one on each iteration, and with that add 10 mins? Can anyone help? Thanks!
2 commentaires
Rather than concatenating strings, it is usually clearer and more efficient to use sprintf, e.g.:
newfilename = sprintf('%s-%s%s-%s',site,filedate,timeis,framenumber);
Calling clearvars is unlikely to be required.
Louise Wilson
le 13 Mai 2020
Réponse acceptée
Plus de réponses (0)
Catégories
En savoir plus sur Convert Image Type dans Centre d'aide et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!