So, I am reading hundreds of image files via imread('D:\pic1\foo.jpg')
and some of them are like imread('D:\pic2\Thumbs.db')
. After reading I am storing in a database like this, train(i) = imread('D:\pic1\foo.jpg')
. The problem is with imread('D:\pic2\Thumbs.db')
, the reading of such files gives error obviously . I wanted to mitigate this problem like this:
for i=1:N
try
train(i) = imread(link{i})
%link{i} can be 'D:\pic2\Thumbs.db' or 'D:\pic1\foo.jpg'
catch
disp('Error')
end
end
The issue is in the try block here. There are two things happening one is reading the file another is assigning imread value to train(i)
. Now, this is important, only on a successful imread()
should there be an assignment and on a failure there would an error. Matlab takes care of the error via catch block, there isn't a block to take care of the success condition where I can do the assignment, so that I can read and write without much hassle.
I want something like this:
j = 0;
for i=1:N
try:
imread(links{i})
if success:
train(j) = imread(links{i})
j = j+1;
if fail:
error
end
end
I only came up with try and catch while searching Matlab docs, I will really appreciate if there is anything which will help me to write the code succinctly.
The solution by @gnovice is correct, but it can be written a bit more succinctly:
ct = 1;
for i=1:N
try
train(ct) = imread(links{i});
ct = ct +1; %# if imread fails, this line is not executed
catch me
%# report the problematic image, and the reason for failure
fprintf('image #%i (%s) cannot be opened: %s\n',i,links{i},me.message)
end
end
You can solve this problem with a continue
statement and a temporary variable like so:
for i=1:N
try
tempVar = imread(link{i});
catch
disp(['Error reading file ' link{i}]);
continue
end
train(i) = tempVar;
end
When imread
throws an error, control is passed to the catch
block, which displays a message and then calls continue
to pass control to the next iteration of the for loop, skipping any later commands. When imread
is successful, the code after the try\catch
block is run, assigning the output from imread
to your variable train
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With