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?

답변 (1개)

Cedric
Cedric 2013년 5월 2일
편집: Cedric 2013년 5월 2일

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

Daniel
Daniel 2013년 5월 2일
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.
Cedric
Cedric 2013년 5월 2일
편집: Cedric 2013년 5월 2일
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

댓글을 달려면 로그인하십시오.

카테고리

도움말 센터File Exchange에서 Convert Image Type에 대해 자세히 알아보기

질문:

2013년 5월 2일

Community Treasure Hunt

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

Start Hunting!

Translated by