Matlab - 在邻域中应用函数

问题描述 投票:0回答:2

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

matlab image-processing matlab-cvst
2个回答
2
投票

你可以使用nlfilter函数返回一个单元格,结果将是一个单元格矩阵:

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

0
投票

以下是如何执行此操作的一种模式:

% 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);
© www.soinside.com 2019 - 2024. All rights reserved.