我想在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))
你能给我一个提示吗?这样我就可以让它发挥作用了?
uigetfile
在filename
:中返回
字符向量或字符向量的单元数组。
(来自文档(。前者发生在选择一个文件时,后者发生在选择多个文件时。
因此,如果您希望能够选择多个文件,那么您的代码需要通过检查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
是包含所有所选图像的单元阵列。