Search code examples
matlabimage-processingmatlab-cvst

Matlab - Applying a function in a neighborhood


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.


Solution

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