Question

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
Was it helpful?

Solution

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:

  1. You attempted to create a vector of arguments for median but didn't surround it with []
  2. I used the fact that when indexing over more than one dimension, Matlab does "nested loops" to get all the numbers (so my block variable ends up being 3x3)
  3. I feed a column vector 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)
  4. There are techniques for doing this much more efficiently - built in median filters, and things like blockproc - but you need the Image Processing Toolbox for those.

I hope this helps a bit.

OTHER TIPS

matlab has a built-in median filter medfilt2 you can also try ordfilt2

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top