To apply a median filter on a coloured image, why do I have to use 'medfilt2' on each channel separately rather than use 'medfilt3'?

15 views (last 30 days)
Hi,
I have a color image and would like to use a 9 x 9 median filter.
Method A - using 'medfilt2' on each channel separately with 'padopt' = 'symmetric'.
fn = 'exuberant.png';
[I,map] = imread(fn);
I = ind2rgb(I, map);
I = I * 255;
figure
subplot(1,2,1)
imshow(uint8(I))
R = I(:,:,1);
G = I(:,:,2);
B = I(:,:,3);
a = 9;
medfilimg(:,:,1) = medfilt2(R,[a,a],'symmetric');
medfilimg(:,:,2) = medfilt2(G,[a,a],'symmetric');
medfilimg(:,:,3) = medfilt2(B,[a,a],'symmetric');
subplot(1,2,2)
imshow(uint8(medfilimg))
I get the below, with left image the 'original image' and right image the 'median filter' image. The colors look fine comparing the right image to the left image.
Method B - using 'medfilt3' on the whole image.
fn = 'exuberant.png';
[I,map] = imread(fn);
I = ind2rgb(I, map);
I = I * 255;
figure
subplot(1,2,1)
imshow(uint8(I))
K = medfilt3(I);
subplot(1,2,2)
imshow(uint8(K))
I get the below, where left is still the original image, and the right is the median filter image using medfilt3. Noticed that the texts in the image changed from red to yellow/orange. The bird's feet changed from red to orange which doesn't appear right at all. WHY?

Answers (1)

DGM
DGM on 6 May 2023
When calling medfilt3() without any window size argument, the default 3x3x3 window is used. Besides the fact that a 3x3 window is going to yield a different result than a 9x9 window, a 3x3x3 window yields results different from what a 3x3x1 window would. You don't want your filter window to be any more than 1 page deep.
% the inputs
inpict = imread('peppers.png');
winsize = [9 9];
% use medfilt2() in a loop
op1 = inpict;
for c = 1:size(inpict,3)
op1(:,:,c) = medfilt2(inpict(:,:,c),winsize,'symmetric');
end
% use medfilt3()
op2 = medfilt3(inpict,[winsize 1],'symmetric');
% the results are identical
immse(op1,op2)
ans = 0
% show it
imshow(op2)

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!