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)');
In this post, we implement two basic image transformations in MATLAB: converting a colour image to grayscale and producing its digital negative. The digital negative inverts the intensity of every pixel — dark areas become light and vice versa — by applying the transformation s = 255 - r to each pixel value r. These are fundamental point processing operations in digital image processing.
MATLAB Code
% Digital Negative and Grayscale of an Image in MATLAB
% Demonstrates two point-processing transformations:
% 1. RGB -> Grayscale
% 2. Grayscale -> Digital Negative
clc; % Clear the command window
clear all; % Clear all workspace variables
% --- Load the image ---
% Place your image in the MATLAB working directory.
originalImage = imread('desert.jpg'); % Read a colour (RGB) image
% --- Convert to Grayscale ---
grayImage = rgb2gray(originalImage); % Average the R, G, B channels
% --- Compute Digital Negative ---
% For an 8-bit image the maximum intensity is 255.
% Negative: negative(x,y) = 255 - gray(x,y)
negativeImage = 255 - grayImage;
% Optionally save the negative image to disk
imwrite(negativeImage, 'negative.jpg');
% --- Display all three images side by side ---
subplot(1, 3, 1);
imshow(originalImage);
title('Original Colour Image');
subplot(1, 3, 2);
imshow(grayImage);
title('Grayscale Image');
subplot(1, 3, 3);
imshow(negativeImage);
title('Digital Negative');
In this post, we implement gray-level slicing in MATLAB — a point processing technique used in digital image processing to highlight a specific range of gray levels while suppressing everything outside that range. The program reads a grayscale image, asks the user to specify a lower and upper gray-level boundary, and produces two sliced images: one that preserves the background and one that blacks it out.
MATLAB Code
% Gray-Level Slicing in MATLAB
% Highlights pixels within a user-defined gray-level range.
% Two sliced versions are produced:
% b - background preserved (pixels below r1 unchanged)
% c - background suppressed (only the range [r1,r2] is shown in white)
clc; % Clear the command window
clear all; % Clear all workspace variables
% --- Load image ---
% Place your image file in the MATLAB working directory.
originalImage = imread('sample.jpg'); % Read the image file
grayImage = rgb2gray(originalImage); % Convert to grayscale
imageSize = size(grayImage); % [rows, cols]
% --- User inputs ---
lowerLevel = input('Enter lower gray level : '); % e.g. 20
upperLevel = input('Enter upper gray level : '); % e.g. 50
% --- Slicing: preserve background ---
% Pixels above upperLevel are set to 255 (white); others stay the same.
slicedPreserve = grayImage;
for row = 1:imageSize(1)
for col = 1:imageSize(2)
if grayImage(row, col) > lowerLevel
if grayImage(row, col) > upperLevel
slicedPreserve(row, col) = 255; % Highlight bright pixels
end
end
end
end
% --- Slicing: suppress background ---
% Pixels inside [lowerLevel, upperLevel] -> white; outside -> black.
slicedSuppress = grayImage;
for row = 1:imageSize(1)
for col = 1:imageSize(2)
if grayImage(row, col) > lowerLevel
if grayImage(row, col) > upperLevel
slicedSuppress(row, col) = 255; % In range -> white
else
slicedSuppress(row, col) = 0; % Out of range -> black
end
end
end
end
% --- Display all three images side by side ---
subplot(1, 3, 1);
imshow(grayImage);
title('Original Grayscale');
subplot(1, 3, 2);
imshow(slicedPreserve);
title('Sliced (Background Preserved)');
subplot(1, 3, 3);
imshow(slicedSuppress);
title('Sliced (Background Suppressed)');
In this post, we plot the discrete-time sine and cosine functions in MATLAB using the stem() function. Sine and cosine are the most fundamental periodic signals in signal processing. Visualising them in the discrete-time domain helps build intuition for sampling, frequency analysis, and filter design.
MATLAB Code
% Plotting Discrete-Time sin and cos in MATLAB
% The user supplies n; the time axis runs from -n to +n.
clc; % Clear the command window
clear all; % Clear all workspace variables
% --- Sine plot ---
nSin = input('Enter n for sin plot : '); % e.g. 5
tSin = -nSin:1:nSin; % Time axis: -n, ..., 0, ..., +n
ysin = sin(tSin); % Compute sin at each sample
subplot(1, 2, 1);
stem(tSin, ysin);
title('sin(n)');
xlabel('n');
ylabel('Amplitude');
ylim([-1.5, 1.5]); % Fix y-axis for readability
% --- Cosine plot ---
nCos = input('Enter n for cos plot : '); % e.g. 5
tCos = -nCos:1:nCos; % Time axis: -n, ..., 0, ..., +n
ycos = cos(tCos); % Compute cos at each sample
subplot(1, 2, 2);
stem(tCos, ycos);
title('cos(n)');
xlabel('n');
ylabel('Amplitude');
ylim([-1.5, 1.5]); % Fix y-axis for readability
In this post, we use MATLAB to plot four fundamental discrete-time signals: the Unit Impulse, Unit Step, Unit Ramp, and Exponential Function. These signals are the building blocks of digital signal processing (DSP) and control systems theory. Understanding how to generate and visualize them in MATLAB is the first step towards analyzing more complex systems.
MATLAB Code
% Plotting Unit Impulse, Unit Step, Unit Ramp and Exponential Function
% All four signals are plotted in a 2x2 subplot grid.
clc; % Clear the command window
clear all; % Clear all workspace variables
% --- 1. Unit Impulse (delta function) ---
% Non-zero only at n=0; value = 1 at origin, 0 elsewhere
t = -2:1:2; % Time axis: -2, -1, 0, 1, 2
impulse = [zeros(1,2), 1, zeros(1,2)]; % 1 only at center (t=0)
subplot(2, 2, 1);
stem(t, impulse);
title('Unit Impulse');
xlabel('n');
ylabel('delta(n)');
% --- 2. Unit Step ---
% Value = 1 for all n >= 0
nStep = input('Enter length for unit step : '); % e.g. 5
tStep = 0:1:nStep - 1; % Time axis: 0, 1, ..., nStep-1
stepSignal = ones(1, nStep); % All ones
subplot(2, 2, 2);
stem(tStep, stepSignal);
title('Unit Step');
xlabel('n');
ylabel('u(n)');
% --- 3. Unit Ramp ---
% Value increases linearly: r(n) = n for n >= 0
nRamp = input('Enter length for unit ramp : '); % e.g. 4
tRamp = 0:1:nRamp - 1; % Time axis: 0, 1, ..., nRamp-1
subplot(2, 2, 3);
stem(tRamp, tRamp); % y = n (ramp equals the index)
title('Unit Ramp');
xlabel('n');
ylabel('r(n) = n');
% --- 4. Exponential Function ---
% y(n) = exp(a*n); decaying when a0
nExp = input('Enter length for exponential : '); % e.g. 5
tExp = 0:1:nExp - 1; % Time axis
a = input('Enter exponent value (a) : '); % e.g. -0.5 or 2
expSignal = exp(a * tExp);
subplot(2, 2, 4);
stem(tExp, expSignal);
title('Exponential Function');
xlabel('n');
ylabel('e^{an}');