Reading in a file name with a zero
Show older comments
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)
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
Daniel
on 2 May 2013
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
Categories
Find more on Startup and Shutdown in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!