user5380136
user5380136

Reputation:

How can I catch an error when I use uigetfile ? [MATLAB]

I have this sentence colorImage = imread(uigetfile('*.jpg;*.tif;*.png;*.gif')); where I choose an image from my computer.

The problem is that when I press cancel button an error appears. How can I catch the error when I press cancel?

Thanks in advance.

Upvotes: 0

Views: 875

Answers (2)

ibezito
ibezito

Reputation: 5822

Use Matlab's try and catch mechanism. Example:

try
colorImage = imread(uigetfile('*.jpg;*.tif;*.png;*.gif'));
catch ME
  if (strcmp(ME.identifier,'MATLAB:imagesci:imread:badImageSourceDatatype'))
      %do something
  end  
end

Upvotes: 0

il_raffa
il_raffa

Reputation: 5190

When used without specifying the out parameters (as in you instruction), the function uigetfile return only the filename.

If you select an image file which is neither in the current directory nor in a folder in the MatLab path, the imread function will not be able to find the image file; in that case you have to provide imread with the complete filename (path + filename).

You have then better to split the instruction:

  • get the image filename with uigetfile
  • check for selection abort: you do it by checking class of the output variable filename
    • in case of file selection the class of filename will be char
    • in case of selection abort, it will be double since uigetfile in that case returns 0
  • in case of a valid selection, build the image full filename with fullfile
  • in case of selection abort, print a message

This is a possible implementation of the above listed steps.

% Get the image full file name (path and filename)
[filename,pathname]=uigetfile('*.jpg;*.tif;*.png;*.gif')
% Check for selection abort
if(strcmp(class(filename),'char'))
   % If an image has been selected, create the image full filename
   the_img=fullfile(pathname,filename);
   % Read the image
   colorImage = imread(the_img)
else
   % If the image selection has been aborted, print a message
   disp('Image selection aborted')
end

Upvotes: 1

Related Questions