在Matlab GUI中加载多个图像

时间:2018-11-06 12:54:22

标签: matlab loading matlab-guide

我想在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'); 

它在加载一张图像的情况下有效,但是在加载多张图像的情况下,会产生mi随后的错误:

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

能否请您给我一个提示,以便我可以使其正常运行?

1 个答案:

答案 0 :(得分:1)

uigetfile返回filename

  

字符向量或字符向量的单元格数组。

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

因此,如果您想选择多个文件,则您的代码需要通过检查是否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是一个包含所有选定图像的单元格阵列。