【问题标题】:Optional input arguments on Matlab functionMatlab 函数的可选输入参数
【发布时间】:2016-03-08 23:41:15
【问题描述】:

我需要实现一个函数,该函数对位于文件夹 (folder1) 中的特定数量的图像 (nFrames) 进行一些图像处理。该函数看起来像:

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,同时考虑到一个是数字,另一个是字符串?

【问题讨论】:

    标签: matlab


    【解决方案1】:

    要解决代码中的问题:

    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'
    

    【讨论】:

    • 效果很好,但我有一个小问题。我如何将默认帧值设置为可以在输入/默认路径中找到的确切图像数量?
    • @MartaSampietro:这不受支持,我认为您的要求是错误的。您希望默认为所有文件,而不是特定数量的文件。让a 成为您的默认目录,其中包含 5 个文件,b 是另一个包含 10 个文件的目录。在这种情况下,您可能想要处理 10 帧。
    • 我想我解释得不是很好。例如,假设您在答案中像第三种情况一样调用函数。用户给出了文件夹路径,但没有给出他想要处理的帧数,所以nFrames变量应该采用用户输入的文件夹内图像总数的值。
    • @MartaSampietro:我已经更新了我将如何实现它的代码。
    猜你喜欢
    • 1970-01-01
    • 2011-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-22
    • 2019-02-06
    • 2018-06-21
    • 1970-01-01
    相关资源
    最近更新 更多