Reputation: 3
I need help debugging my median function under the if statement. I am getting an input error. Also if there is a simpler way to write the median function it will be greatly appreciated. I am writing this code to clean up the above image for a project. Thanks. Also, I am pretty new with MATLAB.
``clear clc format compact
filenameIN = uigetfile('.bmp','Picture');
noisyRGBarray = imread(filenameIN);
%figure(1)
%imshow(noisyRGBarray)
y = noisyRGBarray;
[m,n]=size(y)
cleanRGBarray = y;
for i = 2:m-1
for j = 2:n-1
if y(i,j) == 0 | y(i,j) == 255 % clean add new
cleanRGBarray(i,j) = median( ( y ( (i-1),(j-1) ) ) , ( y ( (i-1),(j) ) ) , ( y ( (i-1),(j+1) ) ) ; ( y ( (i),(j-1) ) ), ( y ( (i),(j) ) ) ; ( y ( (i),(j+1) ) ) ; ( y ( (i+1),(j-1) ) ), ( y ( (i+1),(j) ) ), ( y ( (i+1),(j+1) ) ) ) ;
end
end
end
Upvotes: 0
Views: 124
Reputation: 46375
You are making this very hard on yourself! The simplest way to re formulate the innermost loop is
block = y((-1:1)+i, (-1:1)+j);
cleanRGBarray(i,j) = median(block(:));
A couple of things to note:
median
but didn't surround it with []
block
variable ends up being 3x3)block(:)
with dimensions 9x1
into median
- if you give it an N dimensional matrix, it will operate on the first non-singleton dimension only (so give it 3x3 and it returns 1x3 medians)blockproc
- but you need the Image Processing Toolbox for those.I hope this helps a bit.
Upvotes: 1
Reputation: 114816
matlab has a built-in median filter medfilt2
you can also try ordfilt2
Upvotes: 1