How to exit a loop if file not found

5 次查看(过去 30 天)
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

回答(1 个)

Thorsten
Thorsten 2015-11-10
编辑:Thorsten 2015-11-10
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
  1 个评论
farheen asdf
farheen asdf 2015-11-10
I tried using the code below but then it always skips the commands below.
if exist(filename) == 0
continue;
end

请先登录,再进行评论。

类别

Help CenterFile Exchange 中查找有关 File Operations 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by