Matlab - Applying a function in a neighborhood

126 Views Asked by At

Lets say that I have a 250*250 matrix. What I want to do is select a [3 3] neighborhood around every pixel and apply a function to it. Now the problem is that the function will output a 2*2 matrix for every pixel in the neighborhood and then I have to add the result of every pixel and finally get a 2*2 matrix for the selected pixel. So in the end I will get 62500 2*2 matrices. Also, I have to save the 2*2 matrix for every pixel in a 250*250 cell. Because these matrices will be used for further calculations. So any idea how I go about doing this because I cannot use nfilter or colfilt because in those the function must return a scalar. Any advice or suggestions are highly welcome.

2

There are 2 best solutions below

0
rahnema1 On BEST ANSWER

You can use nlfilter with a function that returns a cell so the result will be a cell matrix.:

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

Here's one pattern of how to do this:

% 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

And here is a simple example of your_function so you can test the above code:

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);