Question

Is there a method to perform custom operations in an image with a given neighborhood?.

For example, I've defined two functions fmax = @(x)max(x(:)) and fmin = @(x)min(x(:)) to calculate the gradient of a gray scale image I as:

G = nlfilter(I,[3 3],fmax) - nlfilter(I,[3 3],fmin);

However, I would like do the same with a 4-neighborhood instead of the 8-neighborhood defined in the 3-by-3 sliding block, in a similar way as the structuring elements that are used in morphological mathematical.

The idea behind this test is apply a custom function to a pixel and a given neighborhood with a radius r.

Note that I'm interested in apply user defined functions. The gradient is just an example.

Was it helpful?

Solution

The anonymous function is the "user defined" or "custom" function you are after.

You just need to use the anonymous function according to your needs. For example, in order to consider only the 4 nearest neighbors (up down left right) pixels for a 3x3 window you can write:

f = @(x) max(x(2:2:8)) - min(x(2:2:8)) 
G = nlfilter(I,[3 3],f);

as the gradient.

Another example, to do the same for a generic circular neighborhood of radius r:

r = 5;
H = fspecial('disk',r);
f = @(x) max(x(H>0))-min(x(H>0)); 
G = nlfilter(I,size(H),f); 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top