In this post, we implement image thresholding in MATLAB. Thresholding is one of the simplest and most widely used segmentation techniques. It converts a grayscale image into a binary image by comparing each pixel’s intensity against a threshold value: pixels below the threshold are set to 0 (black) and pixels at or above the threshold are set to 255 (white). This cleanly separates foreground objects from the background.
MATLAB Code
% Image Thresholding in MATLAB
% Converts a grayscale image to binary using a user-supplied threshold.
% Pixels below the threshold -> 0 (black)
% Pixels >= threshold -> 255 (white)
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]
% --- Get threshold from user ---
thresholdValue = input('Enter threshold value (0-255) : '); % e.g. 128
% --- Apply threshold ---
binaryImage = grayImage; % Copy to preserve border pixels
for i = 1 : imageSize(1)
for j = 1 : imageSize(2)
if grayImage(i, j) black
else
binaryImage(i, j) = 255; % At or above threshold -> white
end
end
end
% --- Display results ---
subplot(1, 2, 1);
imshow(grayImage);
title('Original Grayscale Image');
subplot(1, 2, 2);
imshow(binaryImage);
title(['Thresholded at ', num2str(thresholdValue)]);
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)');
In this post, we implement Histogram Equalisation in MATLAB. Histogram equalisation is an image enhancement technique that redistributes the pixel intensity values of an image so that the resulting histogram is approximately uniform. This increases the global contrast of the image, especially when the usable image data is represented by close contrast values. It is widely used in medical imaging, satellite imagery, and photography.
MATLAB Code
% Histogram Equalisation in MATLAB
% Reads a colour image, converts to grayscale, reduces contrast
% intentionally (to simulate a low-contrast image), applies
% histogram equalisation, and displays both images with their histograms.
clc; % Clear the command window
clear all; % Clear all workspace variables
% --- Load and prepare image ---
% Place your image in the MATLAB working directory.
originalImage = imread('sample.jpg'); % Read the colour image
grayImage = rgb2gray(originalImage); % Convert to grayscale
grayImage = imresize(grayImage, [256, 256]); % Resize to 256x256
% Reduce contrast by scaling pixel values to half range (simulate low contrast)
lowContrastImage = uint8(0.5 * double(grayImage));
% --- Apply histogram equalisation ---
% histeq() redistributes intensity values to flatten the histogram.
equalizedImage = histeq(lowContrastImage, 256);
% --- Display results: images and histograms ---
figure;
subplot(2, 2, 1);
imshow(lowContrastImage);
title('Low Contrast (Original)');
subplot(2, 2, 2);
imshow(equalizedImage);
title('Histogram Equalised');
subplot(2, 2, 3);
imhist(lowContrastImage);
title('Original Histogram');
subplot(2, 2, 4);
imhist(equalizedImage);
title('Equalised Histogram');
In this post, we implement a spatial-domain High Pass Filter (HPF) in MATLAB. A high pass filter suppresses low-frequency (smooth) regions of an image and enhances high-frequency content such as edges and sharp transitions. Unlike the Low Pass Filter which blurs an image, the HPF makes edges more visible by computing the Laplacian of the image at every pixel.
MATLAB Code
% High Pass Filter (HPF) in MATLAB
% Applies a 3x3 Laplacian high-pass kernel to a grayscale image.
% The kernel: [-1 -1 -1; -1 8 -1; -1 -1 -1]
% Computes: HPF(i,j) = 8*center - sum_of_8_neighbours
clc; % Clear the command window
clear all; % Clear all workspace variables
% --- Load image ---
% Place your image in the MATLAB working directory.
originalImage = imread('hills.jpg'); % Read the colour image
grayImage = rgb2gray(originalImage); % Convert to grayscale
imageSize = size(grayImage); % [rows, cols]
% Initialise output as double to avoid uint8 overflow
hpfImage = double(grayImage);
% --- Apply Laplacian HPF kernel ---
% Skip the border pixels (row/col 1 and last row/col)
% to avoid out-of-bounds indexing.
for i = 2 : imageSize(1) - 1
for j = 2 : imageSize(2) - 1
% Laplacian: multiply centre by 8, subtract all 8 neighbours
hpfImage(i, j) = ...
-double(grayImage(i-1, j-1)) ...
-double(grayImage(i-1, j )) ...
-double(grayImage(i-1, j+1)) ...
-double(grayImage(i, j-1)) ...
+8*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));
end
end
% --- Display results ---
subplot(1, 2, 1);
imshow(grayImage);
title('Original Grayscale Image');
subplot(1, 2, 2);
imshow(hpfImage, []);
title('High Pass Filtered Image');
In this post, we implement three popular edge detection algorithms in MATLAB: Canny, Prewitt, and Sobel. Edge detection is a critical step in image processing and computer vision — it identifies points where image brightness changes sharply, which typically corresponds to object boundaries. We apply all three detectors to the same input image and display the results side by side for comparison.
MATLAB Code
% Edge Detection in MATLAB: Canny, Prewitt, and Sobel
% Applies three edge detectors to the same grayscale image
% and displays all results in a 2x2 subplot grid.
clc; % Clear the command window
clear all; % Clear all workspace variables
close all; % Close all open figure windows
% --- Load image ---
% 'cameraman.tif' is a standard MATLAB sample image.
% Replace with any grayscale image in your working directory.
originalImage = imread('cameraman.tif');
% --- Apply edge detectors ---
% edge(I, 'method') returns a binary image:
% 1 = edge pixel | 0 = non-edge pixel
% Canny: optimal detector - good noise suppression, thin edges
canny = edge(originalImage, 'canny');
% Prewitt: gradient-based, uses 3x3 horizontal/vertical kernels
prewitt = edge(originalImage, 'prewitt');
% Sobel: similar to Prewitt but weights the central row/column more
sobel = edge(originalImage, 'sobel');
% --- Display results ---
figure;
subplot(2, 2, 1);
imshow(originalImage);
title('Original Image');
subplot(2, 2, 2);
imshow(canny);
title('Canny Edge Detection');
subplot(2, 2, 3);
imshow(prewitt);
title('Prewitt Edge Detection');
subplot(2, 2, 4);
imshow(sobel);
title('Sobel Edge Detection');
In this post, we implement the Discrete Fourier Transform (DFT) in MATLAB using the built-in fft() function and plot the resulting frequency-domain representation of a user-supplied sequence. The DFT converts a finite-length discrete-time signal from the time domain into the frequency domain, revealing which frequency components are present and at what amplitudes.
MATLAB Code
% Implementing DFT in MATLAB using fft()
% The user supplies a sequence and the DFT length.
% The magnitude spectrum is plotted using stem().
clc; % Clear the command window
clear all; % Clear all workspace variables
% --- Input ---
xSignal = input('Enter the input sequence (e.g. [0.25 0.25 0.25 0]) : ');
nPoints = input('Enter the DFT length N : ');
% --- Compute DFT ---
% fft(x, N) computes the N-point FFT (a fast algorithm for the DFT).
% If N > length(x), the sequence is zero-padded.
% If N < length(x), the sequence is truncated.
dftResult = fft(xSignal, nPoints);
% --- Compute magnitude spectrum ---
magnitude = abs(dftResult); % |X(k)| for each frequency bin k
% --- Plot ---
figure;
subplot(1, 2, 1);
stem(real(dftResult));
title('DFT - Real Part');
xlabel('Frequency Bin (k)');
ylabel('Re{X(k)}');
subplot(1, 2, 2);
stem(imag(dftResult));
title('DFT - Imaginary Part');
xlabel('Frequency Bin (k)');
ylabel('Im{X(k)}');
% Display the magnitude spectrum in a separate figure
figure;
stem(magnitude);
title('DFT Magnitude Spectrum |X(k)|');
xlabel('Frequency Bin (k)');
ylabel('|X(k)|');
In this post, we implement the Discrete Cosine Transform (DCT) and its inverse (IDCT) on a grayscale image in MATLAB. The DCT is the mathematical backbone of JPEG image compression: it converts spatial pixel data into frequency coefficients, allowing low-energy (high-frequency) components to be discarded with minimal perceptual loss. The IDCT reconstructs the image from those coefficients.
MATLAB Code
% Implementing DCT and IDCT on an Image in MATLAB
% Shows the original image, its DCT coefficient map, and the IDCT reconstruction.
clc; % Clear the command window
clear all; % Clear all workspace variables
% --- Load and prepare image ---
% Place your image in the MATLAB working directory.
originalImage = imread('sample.jpg'); % Read the colour image
grayImage = rgb2gray(originalImage); % Convert to grayscale
[numRows, numCols] = size(grayImage); % Get image dimensions
% --- Forward DCT (2D) ---
% dct2() computes the 2-D Discrete Cosine Transform.
% The output Y contains DCT coefficients (frequency domain).
dctCoefficients = dct2(double(grayImage)); % Cast to double for precision
% --- Inverse DCT ---
% idct2() reconstructs the image from the DCT coefficients.
% Ideally the reconstruction should match the original exactly.
reconstructedImage = idct2(dctCoefficients);
% --- Display results ---
subplot(2, 3, 1);
imshow(originalImage);
title('Original Colour Image');
subplot(2, 3, 2);
imshow(grayImage);
title('Grayscale Image');
subplot(2, 3, 3);
imshow(dctCoefficients, [0, 255]);
title('DCT Coefficients');
subplot(2, 3, 4);
imshow(reconstructedImage, [0, 255]);
title('IDCT (Reconstructed)');