Reputation: 3177
I'm wondering is there a way to define my own 2d filter. Assuming there is a matrix A, I'd like to assign every element of A to the maximum value of its 8 neighbors. For example:
A = [1 2 3 4 5
6 7 8 9 10
-1 3 4 8 13
4 2 0 9 1]
After filtering:
A = [1 2 3 4 5
6 8 9 10 10
-1 8 9 13 13
4 2 0 9 1]
Thanks
Upvotes: 0
Views: 233
Reputation: 3574
You can create an arbitrary filter with nlfilter
, an example here. In your case:
fun = @(x) max(x(:)),
B = nlfilter(YourImage,[3 3],fun);
In the case that you want to exclude the center pixel, replace fun
by something like:
fun=@(x) max([x(1:3, 1)' x(1,2) x(3,2) x(1:3,3)'])
Upvotes: 1
Reputation: 221504
You may use imdilate
to get you the maximum of a 9x9 neighbhorhood -
%%// Dilate to get the max of a 9x9 neighborhood (including the element itself)
A1 = imdilate(A, true(3));
%%// Since you are looking to keep the boundary elements
m1 = ones(size(A));
m1(2:end-1,2:end-1)=0;
A1 = m1.*A+~m1.*A1
If you are looking to get the maximum of a 8x8 neighbhorhood, i.e. exclude the element itself, use a modified kernel for use into imdilate
-
%%// Dilate to get the max of a 8x8 neighborhood (excluding the element itself)
h = true(3);
h(2,2)=false;
A1 = imdilate(A,h);
%%// Since you are looking to keep the boundary elements
m1 = ones(size(A));
m1(2:end-1,2:end-1)=0;
A1 = m1.*A+~m1.*A1
Upvotes: 1
Reputation: 2366
You can try the following syntax and use ordfilt2 as a maximum filter:
B = ordfilt2(A, 9, ones(3,3))
Here is a doc page for ordfilt2.
Upvotes: 0