Reading in a file name with a zero

I am trying to read in image files named in numerical order. Example: IMG_0567, IMG_0568, etc.
I am using the following script to do this:
source = 'G:\RESEARCH\Acetone\30x3_acetone_10deg_2013-05-01\SLR\';
first = 0567; % first frame in sequence
last = 0617; % last frame in sequence
image1=imread([source,'IMG_', num2str(first),'.JPG'],'JPG');
It appears that MATLAB does not recognize the zero in the number of the image and I receive the following error:
Error using imread (line 388)
File
"G:\RESEARCH\Acetone\30x3_acetone_10deg_2013-05-01\SLR\IMG_567.JPG"
does not exist.
My solution so far has been to go in and manually change the name of the file to remove the zero, but for a thousand files this would be obnoxiously tedious.
Suggestions?

Answers (1)

Cedric
Cedric on 2 May 2013
Edited: Cedric on 2 May 2013
You probably want to do something like this:
for imgId = first : last
fileLocator = fullfile(source, sprintf('IMG_%04d.JPG', imgId)) ;
img = imread(fileLocator, 'JPG') ;
% .. processing ..
end
where %04d in the format spec. converts imgId to string over 4 characters with 0 padding if necessary.

2 Comments

I was just in the process of finding out what %04d meant when I saw your edit.
Thank you, I will follow up with an answer acceptance when I have my script working.
You can also use EXIST with a 'file' 2nd argument to check whether the file exists or not before trying to IMREAD it, or put the call to IMREAD in a TRY statement and CATCH failures.
Examples:
for imgId = first : last
fileLocator = fullfile(source, sprintf('IMG_%04d.JPG', imgId)) ;
if ~exist(fileLocator, 'file'), continue ; end
img = imread(fileLocator, 'JPG') ;
% .. processing ..
end
or
for imgId = first : last
fileLocator = fullfile(source, sprintf('IMG_%04d.JPG', imgId)) ;
try
img = imread(fileLocator, 'JPG') ;
catch
warning('Image "%s" not found.', fileLocator) ;
continue ;
end
% .. processing ..
end

Sign in to comment.

Categories

Asked:

on 2 May 2013

Community Treasure Hunt

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

Start Hunting!