GeeM
GeeM

Reputation: 13

How do you apply a custom median filter with threshold?

I am trying to create a custom median filter for my image processing where for a 3x3 neighbourhood, the central pixel (being changed) is excluded. My kernel is therefore

 1     1     1
 1     0     1
 1     1     1

But I want to only change the central pixel to the median of the surrounding pixels if its value deviates by more than the surrounding pixels by some threshold value. E.g. if the pixel is more than 10 times the median of the surrounding pixels, then the central pixel value is changed to the median.

I've looked at using ordfilt2 and I can create a median filter with it. But I am not sure how I can implement the threshold condition. I am essentially trying to remove any outliers within my image which meet the threshold condition within my kernel.

Thanks for any help.

Upvotes: 1

Views: 1292

Answers (2)

ibezito
ibezito

Reputation: 5822

I suggest the following approach:

%defines input
A = repmat(1:5,5,1);

%step 1: median filtering, ignoring the central pixel
fun = @(x) median([x(1:ceil(length(x(:))/2-1)),x(ceil(length(x(:))/2+1):end)]);
filteredA = nlfilter(A,[3 3],fun);

%step 2: changing each pixel, onlyt if its 10 times bigger from the median
result = A;
changeMask = (A./filteredA)>10 | (A./filteredA)<0.1;
result(changeMask ) = filteredA(changeMask);

Upvotes: 1

Bentoy13
Bentoy13

Reputation: 4966

You don't have a single function for doing that, but ord2filt is a good start.

N = uint8([1 1 1 ; 1 0 1 ; 1 1 1]);   % neighborhood, faster with integer class
J = (ordfilt2(I,4,N) + ordfilt2(I,5,N))/2;   % median of even set
M = I>J+10;    % put here your threshold method
Out = I;
Out(M) = J(M);

Rem: question already asked here, but without any good answer IMO.

Upvotes: 1

Related Questions