# How to change a 3x3 median filter to 5x5?

44 ビュー (過去 30 日間)
Matthew Worker 2021 年 10 月 4 日

My code works, but i need a 5x5 filter not 3x3. I tried to alter the code to get the 5x5 but keep getting an error
%% 2. Median Filter
title('IMAGE WITH NOISE');
%PAD THE MATRIX WITH ZEROS ON ALL SIDES
%COPY THE ORIGINAL IMAGE MATRIX TO THE PADDED MATRIX
end
end
%LET THE WINDOW BE AN ARRAY
%STORE THE 3-by-3 NEIGHBOUR VALUES IN THE ARRAY
%SORT AND FIND THE MIDDLE ELEMENT
for i= 1:size(median_filt,1)-2
for j=1:size(median_filt,2)-2
window=zeros(9,1);
inc=1;
for x=1:3
for y=1:3
window(inc)=median_filt(i+x-1,j+y-1);
inc=inc+1;
end
end
med=sort(window);
%PLACE THE MEDIAN ELEMENT IN THE OUTPUT MATRIX
end
end
%CONVERT THE OUTPUT MATRIX TO 0-255 RANGE IMAGE TYPE
title('IMAGE AFTER MEDIAN FILTERING');
this was my attempt but i get the error : "ndex exceeds the number of array elements (25)."
%% 2. Median Filter
%PAD THE MATRIX WITH ZEROS ON ALL SIDES
%COPY THE ORIGINAL IMAGE MATRIX TO THE PADDED MATRIX
end
end
%LET THE WINDOW BE AN ARRAY
%STORE THE 5-by-5 NEIGHBOUR VALUES IN THE ARRAY
%SORT AND FIND THE MIDDLE ELEMENT
for i= 1:size(median_filt,1)-3
for j=1:size(median_filt,2)-3
window=zeros(25,1);
inc=1;
for x=1:5
for y=1:5
window(inc)=median_filt(i+x-1,j+y-1);
inc=inc+1;
end
end
med=sort(window);
%PLACE THE MEDIAN ELEMENT IN THE OUTPUT MATRIX
end
end
%CONVERT THE OUTPUT MATRIX TO 0-255 RANGE IMAGE TYPE
figure
subplot(2,1,1);
title('IMAGE WITH NOISE');
subplot(2,1,2);
title('IMAGE AFTER MEDIAN FILTERING');
##### 1 件のコメント表示非表示 なし
Rena Berman 2021 年 12 月 8 日

サインインしてコメントする。

### 回答 (1 件)

DGM 2021 年 10 月 4 日

Start by simplifying:
% 2. Median Filter
%imshow(inpict)
%title('IMAGE WITH NOISE');
% make things parametric instead of hard-coding everything
filtersize = [5 5]; % or whatever size
% PAD THE MATRIX WITH ZEROS ON ALL SIDES
s0 = size(inpict);
outpict = zeros(s0,class(inpict));
os = filtersize-1;
for m = 1:s0(1)
for n = 1:s0(2)
%PLACE THE MEDIAN ELEMENT IN THE OUTPUT MATRIX
outpict(m,n) = median(sample(:)); % what's wrong with median()?
end
end
% test the output against existing tools
referenceimage = medfilt2(inpict,filtersize);
immse(outpict,referenceimage) % show that this filter behaves the same as medfilt2()
title('IMAGE AFTER MEDIAN FILTERING');
imshow(outpict)

サインインしてコメントする。

### カテゴリ

Find more on Image Filtering in Help Center and File Exchange

R2021a

### Community Treasure Hunt

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

Start Hunting!

Translated by