在 Matlab GUI 中加载多个图像

Loading multiple images in Matlab GUI

我想在 Matlab GUI 中加载多个图像。 算法如下:

% --- 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'); 

在加载一张图片的情况下有效,但在加载多张图片的情况下,会出现后续错误:

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))

你能给我一个提示,这样我才能让它正常运行吗?

uigetfile returns 在 filename:

a character vector or a cell array of character vectors.

(来自documentation)。前者发生在 selecting 一个文件时,后者发生在 selecting 多个文件时。

因此,如果您想要 select 多个文件,您的代码需要通过检查是否 iscell(filename) 来处理这种情况,如果是,则遍历它的每个元素.

此外,请使用 fullfile 连接路径或文件名的各个部分,这将防止以后出现可移植性问题。


你可以这样写代码:

[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

现在 img 是一个包含所有图像的元胞数组 selected.