median filter
1. Algorithm description
The algorithm idea of median filtering is very simple. For example, if a square matrix of size 3*3 is selected, then:
First, a matrix as large as the original image is established, which will be used as the median filtered image.
Then, for each pixel of the original image, 9 elements of itself and its eight neighbors are taken out and sorted by size.
Take the median of the sorted 9 elements and make it the pixel value of the new image at that pixel.
2. Matlab code
Function MedianFiltering:
MedianFiltering.m
function new_img = MedianFiltering(img)
[height,width] = size(img);
new_img = img;
for i = 2 : height - 1
for j = 2 : width - 1
tmp = img(i - 1 : i + 1, j - 1 : j + 1);
tmp = sort(tmp(:));
new_img(i - 1, j - 1) = tmp(5);
end
end
new_img = uint8(new_img);
Script Task2 that calls the function:
Task2.m
img = imread('sport car.pgm');
[height,width] = size(img);
set(figure, 'name', 'MedianFiltering');
subplot(2, 2, 1);
imshow(img);
title('Original Image');
t1 = uint8(255 * rand(height, width));
t2 = uint8(255 * rand(height, width));
for i = 1 : height
for j = 1 : width
if img(i, j) > t1(i, j) && img(i, j) > t2(i, j)
img(i, j) = 255;
end
if img(i, j) < t1(i, j) && img(i, j) < t2(i, j)
img(i, j) = 0;
end
end
end
subplot(2, 2, 2);
imshow(img);
title('Polluted Image');
new_img = MedianFiltering(img);
subplot(2, 2, 3);
imshow(new_img);
title('MedianFiltered Image');
subplot(2, 2, 4);
imshow(medfilt2(img));
title('medfilt2 Image');
3. Processing results
The following figure is the comparison of the median filter effect, in which the upper left corner is the original image, the upper right corner is the image polluted by salt and pepper noise, the lower left corner is the image obtained by using the median filter function MedianFiltering written by myself, and the lower right corner is the image obtained by using the matlab function Image obtained by medfilt2. It is obvious that the image effects processed by the two functions are the same.