Franta Mráz
Franta Mráz

Reputation: 37

Loading multiple images in Matlab GUI

I want to load multiple images in Matlab GUI. Algorithm below:

% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton1 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
[filename path] = uigetfile('*.jpg','*.png','Chose files to 
load','MultiSelect','on');

if isequal(filename,0) || isequal(path,0) 
return
end


if iscell(filename)
img = cell(size(filename));
for ii = 1:numel(filename)
  img{ii} = imread(fullfile(path,filename{ii}));
end
else
img{1} = imread(fullfile(path,filename));
end


filename = strcat(path,filename);
fullpathname = strcat(path, filename);
set(handles.edit1,'String', fullpathname);
fileID = fopen(strcat(path, filename), 'r'); 

It works in case of loading one image, but in case of loading multiple images, it gives mi subsequent error:

Error using imread>parse_inputs (line 457)
The file name or URL argument must be a string.

Error in imread (line 316)
[filename, fmt_s, extraArgs] = parse_inputs(varargin{:});

Error in untitled>pushbutton1_Callback (line 112)
im = rgb2gray(imread(filename));

Error in gui_mainfcn (line 95)
    feval(varargin{:});

Error in untitled (line 42)
gui_mainfcn(gui_State, varargin{:});

Error in 
@(hObject,eventdata)
untitled('pushbutton1_Callback',hObject,eventdata,guidata(hObject))

Could you please give me a hint, so I could make it functional?

Upvotes: 0

Views: 243

Answers (1)

Cris Luengo
Cris Luengo

Reputation: 60770

uigetfile returns in filename:

a character vector or a cell array of character vectors.

(From the documentation). The former happens when selecting one file, the latter when selecting multiple files.

Thus, if you want to be ale to select multiple files, your code needs to handle that case by checking to see if iscell(filename), and if so, looping over each of its elements.

Also, please use fullfile to concatenate parts of a path or file name, it will prevent portability issues down the road.


You could write code like this:

[filename,path] = uigetfile({'*.jpg';'*.png'},'Chose files to load','MultiSelect','on');

if isequal(filename,0)
   return
end

if iscell(filename)
   img = cell(size(filename));
   for ii = 1:numel(filename)
      img{ii} = imread(fullfile(path,filename{ii}));
   end
else
   img{1} = imread(fullfile(path,filename));
end

Now img is a cell array containing all the images selected.

Upvotes: 1

Related Questions