How to exit a loop if file not found
2 views (last 30 days)
Show older comments
Hi. I'm trying to read several images from a folder. However, the image names are not continuous. For example image 2 is followed by image 4 followed by image 12. I can not change the names of the images. I want the program to exit the loop once an image is not found (if image 3 is not found, it starts the next iteration and reads image 4). How do i do that? This is my code.
clear all;
for AT = 1:4
fdir=fullfile('D:\Documents\Research\MAM LUBNA\Images\BRATS-1 JPG');
filename=sprintf('BRATS_HG000%d_T2.jpg',AT);
I1 = imread(fullfile(fdir,filename));
Im{AT} = I1(:,:,1); % im1=rgb2gray(c1);
GLCM{AT} = graycomatrix(Im{AT},'Offset',[2 0;0 2]);
end
0 Comments
Answers (1)
Thorsten
on 10 Nov 2015
Edited: Thorsten
on 10 Nov 2015
Use "exist" to check if the file exists:
fdir=fullfile('D:\Documents\Research\MAM LUBNA\Images\BRATS-1 JPG');
for AT = 1:4
filename=fullfile(fdir,sprintf('BRATS_HG000%d_T2.jpg',AT));
if exist(filename, 'file')
I1 = imread(filename));
Im{AT} = I1(:,:,1); % im1=rgb2gray(c1);
GLCM{AT} = graycomatrix(Im{AT},'Offset',[2 0;0 2]);
end
end
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!