Image read series does not exist for & if

Hello,
I have images in a folder. They are named "1.jpg","2.jpg" etc. But lets say I want to read from 1-4 but "3.jpg" does not exist. I want the program to skip and read "4.jpg". Basically in my sample code I want to replace the statement "Does not exist" but something that recognizes that "3.jpg" does not exist and moves onto "4.jpg"
for n = 1:4 %All images in folder read, but e.g. 3 does not exist
A = ['' num2str(n,'%01d') '.jpg']
if A= "Does not exist" %Need to replace this line by something that recognizes that certain image is missing
A = ['' num2str(n+1,'%01d') '.jpg']
else
A = imread(A);
end
end

 採用された回答

Image Analyst
Image Analyst 2014 年 5 月 11 日

0 投票

for n = 1 : 4
filename = sprintf('%01d.jpg', n);
if exist(filename, 'file')
theImage = imread(filename);
end
end
Alternatively:
for n = 1 : 4
filename = sprintf('%01d.jpg', n);
if ~exist(filename, 'file')
continue; % Skip to bottom of loop.
end
theImage = imread(filename);
end

1 件のコメント

Minhal
Minhal 2014 年 5 月 11 日
Thank you for the quick and precise reply.

サインインしてコメントする。

その他の回答 (1 件)

the cyclist
the cyclist 2014 年 5 月 11 日
編集済み: the cyclist 2014 年 5 月 11 日

0 投票

You could use the dir() function to find the names of all the jpg files in the directory, and then use the ismember() command to check if each one is there.
% Get the jpg files
fileStruct = dir('*.jpg');
% Convert to a cell for convenience
fileCell = struct2cell(fileStruct);
% First row of the cell array has the filenames
if ismember('1.jpg',fileCell(1,:))
disp('is there')
else
disp('is not')
end
If can specify the exact pattern of files you want to process inside the dir() command, then you could also just use that list in a for loop directly, without needing to check individual files.

カテゴリ

ヘルプ センター および File ExchangeStartup and Shutdown についてさらに検索

タグ

質問済み:

2014 年 5 月 10 日

コメント済み:

2014 年 5 月 11 日

Community Treasure Hunt

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

Start Hunting!

Translated by