Search code examples
matlabimage-processingfilterblurnoise-reduction

How to apply median filter in all images and store in a directory?


f = 'C:\Users\HP\Desktop\images';
d = ls(f);
d(1,:)=[]
d(1,:)=[]
mkdir('New_images')
for i=1:size(d)
   I=imread(fullfile(f,d(i,:)));
   Kmedian = I;
   for i = 1:3
       Kmedian(:,:,i) = medfilt2(Kmedian(:,:,i));
   end
   Kmedian=imresize(Kmedian,[227 227]);
   imshow(Kmedian)
   imwrite(Kmedian,fullfile('New_images',strcat(num2str(i),'.jpeg')));
end

How to use median filter at once.

Errors: In resize (line 5) Index in position 3 exceeds array bounds (must not exceed 1).

Error in resize (line 10) Kmedian(:,:,i) = medfilt2(Kmedian(:,:,i));


Solution

  • The medfilt2 function only works on 1 channel at the time. If you have a color image, you will have a 3rd dimension to your pixel "matrix" for red, green, blue channels respectively.

    You can still use the medfilt2 function by either converting your image to grayscale, or apply it to each channel individually.

    Kmedian = I;
    for i = 1:size(Kmedian,3)  % Iterate over all the channels in the image
        Kmedian(:,:,i) = medfilt2(Kmedian(:,:,i));
    end
    

    Updated to account for both single and multi channel images