【问题标题】:Matlab - Applying a function in a neighborhoodMatlab - 在邻域中应用函数
【发布时间】:2018-08-10 14:32:45
【问题描述】:

假设我有一个 250*250 的矩阵。我想要做的是在每个像素周围选择一个 [3 3] 邻域并对其应用一个函数。现在的问题是该函数将为邻域中的每个像素输出一个 2*2 矩阵,然后我必须将每个像素的结果相加,最后为所选像素得到一个 2*2 矩阵。所以最后我会得到 62500 个 2*2 矩阵。另外,我必须为 250*250 单元格中的每个像素保存 2*2 矩阵。因为这些矩阵将用于进一步的计算。所以知道我是怎么做的,因为我不能使用 nfilter 或 colfilt 因为在那些函数中必须返回一个标量。非常欢迎任何意见或建议。

【问题讨论】:

  • 如果没有一个标准函数是合适的,为什么不干脆自己写呢?
  • 循环x,循环y,将函数应用于像素。

标签: matlab image-processing matlab-cvst


【解决方案1】:

您可以将nlfilter 与返回单元格的函数一起使用,因此结果将是一个单元格矩阵。:

a = rand(10);
result = nlfilter(a,[3 3],@(x){x(1:2,1:2)});

【讨论】:

    【解决方案2】:

    以下是如何做到这一点的一种模式:

    % define matrix
    N = 250; % dimensionality
    M = rand(N); % random square N-by-N matrix
    
    % initialize output cell array
    C = cell(N);
    
    % apply the function (assume the function is called your_function)
    for row = 1 : N
        for col = 1 : N
    
            % determine a 3x3 neighborhood (if on edge of matrix, 2x2)
            row_index = max(1, row - 1) : min(N, row + 1);
            col_index = max(1, col - 1) : min(N, col + 1);
            neighborhood = mat(row_index, col_index);
    
            % apply the function and save to cell
            C{row, col} = your_function(neighborhood);
    
        end
    end
    

    这里是your_function的一个简单例子,所以你可以测试上面的代码:

    function mat = your_function(mat)
    S = size(mat);
    if S(1) < 2 || S(2) < 2, error('Bad input'); end
    mat = mat(1:2, 1:2);
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 2014-10-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-15
      • 1970-01-01
      相关资源
      最近更新 更多