我需要实现一个函数,对位于文件夹 (folder1) 中的特定数量的图像 (nFrame) 进行一些图像处理。该函数看起来像:
function imgProc( nFrames,path )
假设我有几个文件夹,每个文件夹中都有不同数量的图像。我需要的是可选的输入参数,这意味着如果用户愿意,他可以对前 10 个图像进行图像处理,例如,但如果他没有指定数字,则该函数应该对所有图像执行任务图片。对于文件夹来说也是如此,应该有一个默认文件夹,以防用户没有指定他想要从哪个文件夹中获取图像。有趣的是,用户可以使用 0、1 或 2 个输入参数调用该函数。
我想过使用这样的 exist
函数:
function imgProc( nFrames,path )
if exist( path,'var' ) == 0
path = 'img/record_space';
end
if exist( nFrames,'var' ) == 0
d = dir([ path,'\*.png' ]);
nFrames = length( d( not([ d.isdir ]) ) );
end
end
但是,如果我在没有输入参数的情况下调用该函数,则会出现错误,指出输入参数不足。 是否可以创建一个函数,其所有参数都是可选的,并且允许您根据需要输入 0、1 或 2,同时考虑到一个是数字,另一个是字符串?
最佳答案
要解决代码中的问题:
function imgProc( nFrames,path )
if exist( 'path','var' ) == 0
path = 'img/record_space';
end
if exist( 'nFrames','var' ) == 0
d = dir([ path,'\*.png' ]);
nFrames = length( d( not([ d.isdir ]) ) );
end
end
exists
需要变量名称,而不是变量本身。您可以传递包含字符串的变量,但随后它会检查该字符串是否存在:
x='y'
exist(x,'var') % checks if y exists
exist('x','var') %checks if x exists
我建议使用inputParser
来拥有灵活的界面
function imgProc( varargin )
p = inputParser;
addOptional(p,'frames',inf,@isnumeric);
addOptional(p,'path',pwd,@(x)exist(x,'dir'));
parse(p,varargin{:});
%lower frames if required to the maximum possible value
frames=min(p.Results.frames,numel(dir(fullfile(p.Results.path,'*.png'))));
%if frame was previously a number (not inf) and is lowered, print a warning.
if frames<p.Results.frames&&p.Results.frames~=inf
warning('parameter frames exceeded number of images present. Frames set to %d',frames);
end
disp(p.Results);
end
调用该函数的可能方法:
>> imgProc
frames: Inf
path: 'D:\Documents\MATLAB'
>> imgProc('frames',1)
frames: 1
path: 'D:\Documents\MATLAB'
>> imgProc('path','foo')
frames: Inf
path: 'foo'
>> imgProc('path','bar','frames',9)
frames: 9
path: 'bar'
关于matlab - Matlab 函数的可选输入参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35880250/