All of this gets easier if you can set up conditions first and then loop doing the getframe and writing files sequentially, instead of each time having to independently figure out which file to write.
But to handle your situation as-is, and presuming that there are no other jpg files in the directory:
img = getframe(gcf);
nowstr = datestr(now, 'yyyymmddHHMM');
folder = 'C:\Users\Taiko\Desktop\FalseColor\';
ImageFiles = dir( fullfile(folder, '*.jpg') );
if isempty(ImageFiles)
next_idx = 1;
else
lastfile = ImageFiles(end).name;
[~, basename, ~] = fileparts(lastfile);
file_number_str = regexp('(?<=.*_)\d+$', basename, 'match' );
if isempty(file_number_str)
error('There is a .jpg file present that does not follow the expected naming pattern: "%s", lastfile);
end
last_idx = str2double(file_number_str);
next_idx = last_idx + 1;
end
newfilename = fullfile( folder, sprintf('%s_%04d.jpg', nowstr, next_idx) );
imwrite(img.cdata, newfilename);
Note: if you expect to write more than 9999 frames in one series, then change the %04d to %05d or larger. Make sure that you keep the 0 after the % though. Not %4d for example.
Most this code could be eliminated if it was permitted to initialize some variables first and then write files in a loop instead of having to figure out what the next file is independently each time.
Best Answer