MATLAB Program to Implement LPF
In this post, we implement a spatial-domain Low Pass Filter (LPF) in MATLAB using a 3×3 averaging kernel. A low pass filter smooths an image by replacing each pixel with the average of itself and its 8 neighbours. This reduces noise and high-frequency detail (sharp edges), producing a blurred version of the original. It is the spatial counterpart of frequency-domain low-pass filtering and is the basis of many image smoothing techniques. MATLAB Code % Low Pass Filter (LPF) in MATLAB % Applies a 3x3 averaging kernel (box filter) to a grayscale image. % Each output pixel is the mean of the 3x3 neighbourhood centred on it. clc; % Clear the command window clear all; % Clear all workspace variables % --- Load image --- % Place your image in the MATLAB working directory. originalImage = imread('sample.jpg'); % Read the colour image grayImage = rgb2gray(originalImage); % Convert to grayscale imageSize = size(grayImage); % [rows, cols] % Initialise the output image (same size as input) lpfImage = grayImage; % --- Apply 3x3 averaging kernel --- % Skip the border row/column (index 1 and last) to avoid out-of-bounds access. for i = 2 : imageSize(1) - 1 for j = 2 : imageSize(2) - 1 % Sum the 3x3 neighbourhood and divide by 9 (average) lpfImage(i, j) = ( ... double(grayImage(i-1, j-1)) + double(grayImage(i-1, j)) + double(grayImage(i-1, j+1)) + ... double(grayImage(i, j-1)) + double(grayImage(i, j)) + double(grayImage(i, j+1)) + ... double(grayImage(i+1, j-1)) + double(grayImage(i+1, j)) + double(grayImage(i+1, j+1)) ... ) / 9; end end % --- Display results --- subplot(1, 2, 1); imshow(grayImage); title('Original Grayscale Image'); subplot(1, 2, 2); imshow(lpfImage); title('Low Pass Filtered (Blurred)');