Rubric Legends for CE318 Lab Assessment (15 Marks)
Category Criteria Excellent (4-5 Marks) Good (2-3 Marks) Poor (1-1.5 Marks)
The code is accurate, The code is mostly
Accuracy and The code has major
Code well-structured, and accurate but
correctness of errors or does not
Implementation error-free. Functions contains minor
the written function properly.
(5 Marks) correctly and efficiently. errors or
code. (1-1.5/5)
(5/5) inefficiencies. (2-3/5)
Minimal
Depth of Demonstrates thorough Shows basic
Analysis & understanding or
analysis and understanding and understanding with
Understanding (4 incorrect analysis
comprehension applies logical analysis some analysis but
Marks) with major gaps in
of the task. effectively. (4/4) lacks depth. (2-3/4)
logic. (1-1.5/4)
Proficiency in Highly skilled in tool Basic skill level uses Lacks proficiency,
Tool Usage (3 using MATLAB usage, applies functions tools but makes frequent mistakes
Marks) or Python for correctly with no errors. occasional errors. or incorrect tool
implementation. (3/3) (2/3) usage. (1-1.5/3)
Accuracy and Results are
Results are accurate, Results are partially
Results & Output relevance of the incorrect or
properly presented, and correct, but some
(3 Marks) results irrelevant to the
highly relevant. (3/3) errors exist. (2/3)
obtained. task. (1-1.5/3)
Overall
performance 7-10 Points: 1-5 Points: Needs
Total (15 Marks) 14-15 Points: Excellent
score based on Satisfactory Improvement
all criteria.
Mapping of CLOs and PLOs
Bloom's Taxonomy
Course Learning Outcomes Upon successful completion of Mapped
Sr. No (Psychomotor
this course, the student will be able to: PLOs (BS CE)
Domain)
Understanding the fundamentals and basic
CLO-1 concepts of image processing related to image PLO 1 P2 (Manipulation)
enhancement, filtering and segmentation etc
Performing di erent mathematical transformations,
histogram-based operations and filtering concepts for P3
CLO-2 PLO 3
solving image enhancement and feature extraction (Precision)
problems
Analyze and design image processing techniques for P3
CL0-3 PLO 5
object recognition and related applications. (Precision)
Lab 01: Introduction to Digital Image Processing & Basic Matrix
Operations
Objective:
The purpose of this lab is to introduce students to the fundamentals of digital image
processing, focusing on how images are stored and manipulated in MATLAB. This lab will
provide a strong foundation for more advanced image processing techniques in later sessions.
1. Introduction to Digital Image Processing
Digital Image Processing (DIP) involves applying computational techniques to process
and manipulate images for various applications, such as:
Medical Imaging: Enhancing X-rays, CT scans, and MRI images.
Facial Recognition: Identifying faces in security and authentication systems.
Remote Sensing: Processing satellite images for environmental analysis.
Industrial Automation: Detecting defects in manufacturing processes.
Since MATLAB is designed for matrix-based computations, it is widely used for DIP
tasks.
An image is essentially a matrix:
Grayscale Image: A 2D matrix where each element represents the intensity of a
pixel.
RGB Image: A 3D matrix with three layers corresponding to red, green, and blue
channels.
Understanding basic matrix operations is essential for performing image
transformations, enhancements, and feature extraction.
2. Image Representation in MATLAB
Images in MATLAB are stored as arrays, and various functions are available to process
them.
2.1 Image Storage and Display
Images can be loaded using imread().
They can be displayed using imshow().
The size() function provides the image dimensions and color channels.
2.2 Color Image vs. Grayscale Image
Color images contain three channels (R, G, B).
Grayscale images have a single intensity value per pixel.
Converting an image to grayscale reduces complexity and is useful for many
processing techniques.
2.3 Basic Matrix Operations on Images
Since images are matrices, MATLAB’s built-in matrix functions can be used to modify
them, such as:
Extracting individual colour channels (Red, Green, Blue).
Adjusting brightness by adding or subtracting pixel values.
Performing image negation by inverting pixel values.
3. MATLAB Implementation
% Read and Display an Image
img = imread('peppers.png');
imshow(img);
title ('Original Image');
% Get Image Dimensions
[rows, cols, channels] = size(img);
disp(['Image Dimensions: ', num2str(rows), ' x ', num2str(cols)]);
disp(['Number of Channels: ', num2str(channels)]);
% Convert RGB to Grayscale
gray_img = rgb2gray(img);
figure, imshow(gray_img);
title('Grayscale Image');
% Extracting Color Channels
red_channel = img(:,:,1);
green_channel = img(:,:,2);
blue_channel = img(:,:,3);
figure, subplot(1,3,1), imshow(red_channel), title('Red Channel');
subplot(1,3,2), imshow(green_channel), title('Green Channel');
subplot(1,3,3), imshow(blue_channel), title('Blue Channel');
% Adjust Brightness
brighter_img = gray_img + 50;
figure, imshow(brighter_img);
title('Brighter Image');
darker_img = gray_img - 50;
figure, imshow(darker_img);
title('Darker Image');
% Image Negation
negative_img = 255 - gray_img;
figure, imshow(negative_img);
title('Negative Image');
Tasks:
1. Convert an Image to Binary:
o Convert the grayscale image to a binary image using a threshold value.
o Use imbinarize() or manually apply a threshold (e.g., gray_img > 128).
2. Rotate an Image Without Built-in Functions:
o Rotate an image by 90 degrees using only matrix operations (e.g.,
transposing and flipping).
3. Split an Image into Non-Overlapping Blocks:
o Divide an image into 4×4 or 8×8 non-overlapping blocks and display them
separately.
Lab 02: Image Transformations & Grey Level Adjustments
Objective:
The objective of this lab is to understand and implement various image
transformations and gray level adjustments in MATLAB. Students will learn how to
manipulate image size, orientation, and intensity levels to enhance image quality. These
techniques are fundamental in image processing applications such as medical imaging,
satellite imaging, and computer vision.
Theory:
Image processing techniques allow for modifications in both spatial domain
(geometric transformations) and intensity domain (gray level adjustments).
1. Geometric Transformations
Geometric transformations alter an image’s shape, size, or position. The key types
include:
Scaling: Enlarging or shrinking an image.
Rotation: Changing the orientation of an image at specific angles.
Translation: Moving an image to a di erent position.
Reflection (Flipping): Mirroring an image along the horizontal or vertical axis.
2. Gray Level Adjustments
These techniques modify the pixel intensity values to improve contrast and visibility.
Common methods include:
Contrast Stretching: Expanding pixel values to enhance contrast.
Histogram Equalization: Distributing intensity values evenly for better
brightness.
Log and Power-Law (Gamma) Transformations: Adjusting intensity levels for
better visibility of dark or bright regions.
Lab Tasks
Task 1: Load and Display an Image
Read a grayscale image using imread().
Display the image using imshow().
Observe and analyze the original intensity distribution.
Task 2: Image Scaling & Rotation
Resize the image to 50% and 200% of its original size using imresize().
Rotate the image by 45° and 90° using imrotate().
Compare the transformed images with the original.
Task 3: Translation and Reflection
Translate the image by shifting pixels horizontally and vertically.
Perform horizontal and vertical reflection using fliplr() and flipud().
Task 4: Contrast Adjustment
Apply contrast stretching using imadjust().
Perform histogram equalization using histeq().
Display and analyze histograms before and after adjustment using imhist().
Task 5: Log and Power-Law (Gamma) Transformations
Implement log transformation to enhance darker regions using
c * log(1 + double(image)).
Apply gamma correction using imadjust(image, [], [], gamma) with γ = 0.5 and
2.2.
Formula Used
If γ<1 (e.g., 0.5) → Image becomes brighter.
If γ>1(e.g., 2.2) → Image becomes darker.
r is the normalized input pixel intensity (ranging from 0 to 1).
γ (gamma value) controls how pixel values are transformed.
s is the output intensity after gamma correction.
MATLAB Code
% Task 1: Load and Display Image
img = imread('cameraman.tif');
figure, imshow(img), title('Original Image');
% Task 2: Scaling & Rotation
scaled_img_small = imresize(img, 0.5);
scaled_img_large = imresize(img, 2);
rotated_img_45 = imrotate(img, 45);
rotated_img_90 = imrotate(img, 90);
% Display results
figure, imshow(scaled_img_small), title('Scaled Image (50%)');
figure, imshow(scaled_img_large), title('Scaled Image (200%)');
figure, imshow(rotated_img_45), title('Rotated Image (45°)');
figure, imshow(rotated_img_90), title('Rotated Image (90°)');
% Task 3: Translation & Reflection
horiz_flip = fliplr(img);
vert_flip = flipud(img);
% Display reflections
figure, imshow(horiz_flip), title('Horizontally Flipped');
figure, imshow(vert_flip), title('Vertically Flipped');
% Task 4: Contrast Adjustment
contrast_img = imadjust(img);
histeq_img = histeq(img);
% Display contrast adjustments
figure, imshow(contrast_img), title('Contrast Adjusted');
figure, imshow(histeq_img), title('Histogram Equalization');
% Display Histograms
figure, imhist(img), title('Original Histogram');
figure, imhist(histeq_img), title('Equalized Histogram');
% Task 5: Log & Gamma Transformations
c = 1; % Scaling factor ,c is a scaling factor that controls the
%brightness.A larger c makes the image brighter.
log_transform = c * log(1 + double(img));
gamma_transform_1 = imadjust(img, [], [], 0.5);
gamma_transform_2 = imadjust(img, [], [], 2.2);
% Display log and gamma transformations
figure, imshow(mat2gray(log_transform)), title('Log Transformation');
figure, imshow(gamma_transform_1), title('Gamma Correction (γ = 0.5)');
figure, imshow(gamma_transform_2), title('Gamma Correction (γ = 2.2)')
Gamma values:
gamma = 0.5 → Brightens the image (expands dark pixel values).
gamma = 2.2 → Darkens the image (reduces bright pixel values).
Tasks
Load and display a grayscale image.
Resize the image by 50% and 200%.
Rotate the image by 45° and 90°.
Perform horizontal and vertical flipping.
Implement contrast stretching and histogram equalization.
Plot and compare histograms before and after adjustment.
Apply log transformation and analyze its e ect.
Apply gamma correction with γ = 0.5 and 2.2 and compare results.
Analyze the e ects of contrast and gamma adjustments in a report.
Lab 3
Sampling, Quantization, and Image Transformations
1. Sampling and Quantization
Introduction
In digital image processing, an image is represented as a 2D array of pixels, but real-
world images are continuous signals in both space and intensity. To convert them into
a digital format, two key steps occur: sampling (dividing the image into discrete pixels)
and quantization (assigning intensity values to each pixel from a finite set).
When a camera captures an image, its lens focuses light onto a sensor (CCD/CMOS),
which contains millions of tiny photodiodes that measure light intensity at discrete
locations. This process is the initial sampling, determining the image resolution. The
detected intensities are analog values, so an Analog-to-Digital Converter (ADC)
assigns them discrete intensity levels based on bit depth (e.g., 256 levels for 8-bit
images).
Even after this initial conversion, sampling and quantization are applied again in
digital image processing for various purposes. Resampling is needed when resizing
images, re-quantization occurs when changing bit depth (e.g., converting 16-bit to 8-
bit), and compression techniques like JPEG further quantize data to reduce file size.
These processes help optimize storage, transmission, and analysis while balancing
detail preservation.
1.1 Sampling
Sampling is the process of selecting discrete pixel values from a continuous image to
create a digital representation. It determines the spatial resolution of an image by
specifying how frequently samples (pixels) are taken. A higher sampling rate retains
more details, making the digital image closer to the original. Conversely, a lower
sampling rate results in a loss of detail but reduces data size.
How Sampling Works:
1. High Sampling Rate: More pixels are captured per unit area, preserving fine
details.
2. Low Sampling Rate: Fewer pixels are taken, which can lead to loss of
information and pixelation.
For example, in a 1024×1024 image, each pixel represents a small portion of the image.
Reducing it to 256×256 means each pixel now represents a larger portion, leading to a
loss of detail.
Up-Sampling (Increasing Spatial Resolution)
Up-sampling is the process of increasing the spatial resolution of an image by
interpolating new pixel values. The common methods for up-sampling include:
Nearest Neighbor Interpolation: Copies the closest pixel value to fill the new
pixels. Fast but results in blocky images.
Bilinear Interpolation: Uses the weighted average of the four nearest pixels to
compute new pixel values, giving a smoother result.
Bicubic Interpolation: Uses the weighted average of 16 nearest pixels,
producing even smoother images but computationally expensive.
% Read a low-resolution image
low_res = imread('ca.jpg');
% Nearest Neighbor Interpolation
up_nn = imresize(low_res, 2, 'nearest');
% Bilinear Interpolation
up_bilinear = imresize(low_res, 2, 'bilinear');
% Bicubic Interpolation
up_bicubic = imresize(low_res, 2, 'bicubic');
figure;
subplot(2,2,1), imshow(low_res), title('Original Low-Resolution Image');
subplot(2,2,2), imshow(up_nn), title('Up-Sampling (Nearest Neighbor)');
subplot(2,2,3), imshow(up_bilinear), title('Up-Sampling (Bilinear)');
subplot(2,2,4), imshow(up_bicubic), title('Up-Sampling (Bicubic)');
1.2 Quantization
Quantization is the process of mapping continuous intensity values (grayscale or color
levels) to a limited set of discrete values. This step reduces the number of possible
intensity levels while approximating the original image’s appearance.
How Quantization Works:
1. High Quantization Levels: More intensity levels (e.g., 256 shades in an 8-bit
grayscale image) lead to smooth transitions.
2. Low Quantization Levels: Fewer intensity levels (e.g., 16 or 4 shades) cause
noticeable banding e ects and loss of detail.
For example, a grayscale image with 256 levels (8-bit) may be reduced to 16 levels (4-
bit), leading to a more pixelated appearance but saving memory.
SAMPLING:
img = imread('blur.jpg');
% Downsampling by factors of 2, 4, and 8
img2 = img(1:2:end, 1:2:end);
img4 = img(1:4:end, 1:4:end);
img8 = img(1:8:end, 1:8:end);
% Display results
figure, subplot(2,2,1), imshow(img), title('Original Image');
subplot(2,2,2), imshow(img2), title('Downsampled x2');
subplot(2,2,3), imshow(img4), title('Downsampled x4');
subplot(2,2,4), imshow(img8), title('Downsampled x8');
Observation
As we increase the down sampling factor, the image loses detail, resulting in
pixelation.
Quantization:
levels = [2, 4, 8, 16, 32, 64, 128, 256];
figure;
for i = 1:length(levels)
quantized_img = uint8(round(double(img) / 256 * levels(i)) * (256 / levels(i)));
subplot(2,4,i),
imshow(quantized_img),
title([num2str(levels(i)), ' levels']);
end
For levels = 4:
1. Convert to double
150/256=0.586
2. Scale to 4 levels
0.586×4=2.34
3. Round
round (2.34) =2
4. Scale back to 256 rang
2× (256/4)=128
5. Final value: 128 (Gray)
Observation
With fewer intensity levels, images appear more posterized.
Higher quantization levels preserve more detail.
Bit-Depth Expansion (Inverse Quantization)
Quantization reduces the number of intensity levels (bit-depth) in an image, causing
loss of details. Inverse quantization is an attempt to restore the lost details, though it
cannot fully recover original precision.
Some approaches include:
Simple Scaling: If an 8-bit image was quantized to 4-bit, we can scale the values
back.
Histogram Equalization: Enhances contrast and redistributes pixel intensities.
% Read an image and convert to grayscale
img = imread('img.jpg');
% Simulate Quantization: Convert to 4-bit (16 levels)
quantized_img = uint8(floor(double(img) / 256) * 16);
% Bit-Depth Expansion (Scaling Back)
expanded_img = uint8(double(quantized_img) * (255/240)); % Adjust for 8-bit range
% Histogram Equalization for Enhancement
equalized_img = histeq(expanded_img);
% Display Results
figure;
subplot(2,2,1), imshow(img), title('Original Image');
subplot(2,2,2), imshow(quantized_img), title('4-bit Quantized Image');
subplot(2,2,3), imshow(expanded_img), title('Bit-Depth Expanded Image');
Neighbours
subplot(2,2,4), and Connectivity
imshow(equalized_img), title('After Histogram Equalization');
Lab 04: Spatial Domain Image Enhancement Techniques
Objective:
The objective of this lab is to explore spatial domain image enhancement techniques,
including point processing and neighbourhood processing in MATLAB. Students will
learn how to manipulate pixel values and apply filtering methods to improve image
quality, remove noise, and enhance important features. These techniques are widely
used in medical imaging, satellite image processing, and computer vision
applications.
Theory:
Spatial domain techniques operate directly on pixel values to modify image contrast,
enhance details, or suppress noise. The two major types of spatial domain processing
are:
1. Point Processing Techniques (Pixel-by-Pixel Operations)
These operations modify each pixel value independently based on a transformation
function.
Image Negation: Converts bright regions to dark and vice versa.
Contrast Stretching: Expands intensity range to improve visibility.
Thresholding (Binary Conversion): Converts grayscale images into black &
white for segmentation.
Log & Power-Law Transformations (Gamma Correction): Enhances dark or
bright regions based on non-linear intensity scaling.
2. Neighbourhood Processing (Filtering Operations)
Unlike point processing, neighbourhood processing modifies pixel values based on
their surroundings.
Smoothing (Low-Pass Filtering): Reduces noise by averaging nearby pixels.
Sharpening (High-Pass Filtering): Enhances edges and details.
Edge Detection: Highlights object boundaries.
Lab Tasks
Task 1: Apply Point Processing Techniques
Image Negation: Compute the negative of an image.
Contrast Stretching: Scale pixel values to increase contrast.
Thresholding: Convert an image to binary format.
Log and Power-Law (Gamma) Transformations: Modify intensity distribution.
Task 2: Apply Neighbourhood Processing (Filtering)
Smoothing Filters: Apply average, Gaussian, and median filtering.
Sharpening Filters: Use Laplacian and unsharp masking for detail
enhancement.
Edge Detection: Apply Sobel, Prewitt, and Canny filters.
MATLAB Code
% Task 1: Load and Display Image
imgc = imread('b.jpg');
img=rgb2gray(imgc);
% Point Processing Techniques
neg_img = 255 - img;
figure, imshow(neg_img), title('Negative Image');
% Contrast Stretching
min_val = double(min(img(:)));
max_val = double(max(img(:)));
stretched_img = uint8(255 * (double(img) - min_val) / (max_val - min_val));
figure, imshow(stretched_img), title('Contrast Stretched Image');
% Thresholding
threshold = 128; % Set threshold value
binary_img = img > threshold;
figure, imshow(binary_img), title('Thresholded Image');
% Log & Power-Law Transformations
c = 255 / log(1 + max(double(img(:))));
log_img = uint8(c * log(1 + double(img)));
figure, imshow(log_img), title('Log Transformation');
gamma = 0.5; % Example value for power-law transformation
gamma_img = uint8(255 * (double(img) / 255) .^ gamma);
figure, imshow(gamma_img), title('Gamma Correction (Power-Law)');
% Neighborhood Processing (Filtering)
h_avg = fspecial('average', [5 5]); % Averaging filter
smoothed_avg = imfilter(img, h_avg);
figure, imshow(smoothed_avg), title('Averaging Filter');
h_gauss = fspecial('gaussian', [5 5], 1); % Gaussian filter
smoothed_gauss = imfilter(img, h_gauss);
figure, imshow(smoothed_gauss), title('Gaussian Filter');
smoothed_median = medfilt2(img, [5 5]); % Median filter
figure, imshow(smoothed_median), title('Median Filter');
% Image Sharpening
h_laplacian = fspecial('laplacian', 0.2);
sharpened_laplacian = imfilter(img, h_laplacian);
figure, imshow(sharpened_laplacian, []), title('Laplacian Filter');
sharpened_unsharp = imsharpen(img); % Unsharp Masking
figure, imshow(sharpened_unsharp), title('Unsharp Masking');
% Edge Detection
sobel_edges = edge(img, 'sobel');
prewitt_edges = edge(img, 'prewitt');
canny_edges = edge(img, 'canny');
% Display Edge Detection Results
figure, imshow(sobel_edges), title('Sobel Edge Detection');
figure, imshow(prewitt_edges), title('Prewitt Edge Detection');
figure, imshow(canny_edges), title('Canny Edge Detection');
Tasks
Load and display a grayscale image.
Apply image negation and thresholding for segmentation.
Implement contrast stretching and gamma correction.
Apply smoothing filters (average, Gaussian, and median) and compare results.
Implement Laplacian filtering and unsharp masking for sharpening.
Perform edge detection using Sobel, Prewitt, and Canny methods.
Compare edge-detection results and discuss their e ectiveness.
Lab 05: Frequency Domain Image Enhancement Techniques
Objective:
The primary goal of this lab is to introduce students to frequency domain image
enhancement techniques, which involve processing an image in the Fourier
Transform domain rather than the spatial domain. This approach allows for the
manipulation of specific frequency components, making it useful for applications such
as noise reduction, image sharpening, and feature extraction. By the end of this lab,
students will understand how to apply Fourier Transform-based filtering techniques
and analyze their e ects on images.
Introduction to Frequency Domain Processing
Unlike spatial domain methods that operate directly on pixel values, frequency domain
processing analyzes an image as a combination of di erent frequency components.
The Fourier Transform (FT) is used to convert an image from the spatial domain to the
frequency domain, where image details such as edges and textures correspond to high-
frequency components, while smooth variations correspond to low-frequency
components.
Image processing in the frequency domain generally follows these steps:
1. Convert the image to grayscale (if not already).
2. Apply the Fourier Transform (FT) to obtain the frequency representation.
3. Shift the zero-frequency component to the center for better visualization.
4. Apply frequency filters (low-pass, high-pass, band-pass, or notch filters).
5. Take the Inverse Fourier Transform (IFT) to convert the processed image back to
the spatial domain.
Key Frequency Domain Filters
1. Low-Pass Filters (LPF): Removes high-frequency components, reducing noise
and smoothing the image.
2. High-Pass Filters (HPF): Removes low-frequency components, enhancing
edges and sharp transitions.
3. Band-Pass Filters (BPF): Preserves only a specific range of frequencies while
filtering out others.
4. Notch Filters: Suppress specific unwanted frequencies, useful for removing
periodic noise.
Lab Tasks
Task 1: Fourier Transform and Frequency Domain Representation
Convert an image to the frequency domain using Fast Fourier Transform (FFT).
Shift the zero frequency component to the center using tshift().
Display the magnitude spectrum to analyze frequency components.
Task 2: Low-Pass and High-Pass Filtering
Apply an Ideal, Gaussian, and Butterworth Low-Pass Filter (LPF) to remove
noise and smooth the image.
Apply an Ideal, Gaussian, and Butterworth High-Pass Filter (HPF) to enhance
edges and details.
Observe how di erent filters a ect the image quality.
Task 3: Band-Pass and Notch Filtering
Design a Band-Pass Filter (BPF) to retain only specific frequency ranges.
Implement a Notch Filter to remove periodic noise from the image.
Compare the e ects of di erent frequency domain filters.
MATLAB Code
% Task 1: Load and Convert Image to Frequency Domain
imgc = imread('b.jpg');
imgb=rgb2gray(imgc)
img = im2double(imgb);
figure, imshow(img), title('Original Image');
F = fft2(img);
F_shift = fftshift(F);
magnitude_spectrum = log(1 + abs(F_shift));
figure, imshow(magnitude_spectrum, []), title('Fourier Magnitude Spectrum');
% Task 2: Low-Pass Filtering
[M, N] = size(img);
[u, v] = meshgrid(-N/2:N/2-1, -M/2:M/2-1);
D = sqrt(u.^2 + v.^2);
D0 = 50; % Cutoff frequency
ideal_LPF = double(D <= D0);
butterworth_LPF = 1 ./ (1 + (D / D0).^4);
gaussian_LPF = exp(-(D.^2) / (2 * (D0^2)));
% Apply Low-Pass Filters
F_LPF_ideal = F_shift .* ideal_LPF;
F_LPF_butter = F_shift .* butterworth_LPF;
F_LPF_gauss = F_shift .* gaussian_LPF;
% Inverse Fourier Transform
img_LPF_ideal = real(ifft2(ifftshift(F_LPF_ideal)));
img_LPF_butter = real(ifft2(ifftshift(F_LPF_butter)));
img_LPF_gauss = real(ifft2(ifftshift(F_LPF_gauss)));
% Display LPF results
figure, imshow(img_LPF_ideal, []), title('Ideal Low-Pass Filter');
figure, imshow(img_LPF_butter, []), title('Butterworth Low-Pass Filter');
figure, imshow(img_LPF_gauss, []), title('Gaussian Low-Pass Filter');
% Task 3: High-Pass Filtering
ideal_HPF = double(D > D0);
butterworth_HPF = 1 - butterworth_LPF;
gaussian_HPF = 1 - gaussian_LPF;
% Apply High-Pass Filters
F_HPF_ideal = F_shift .* ideal_HPF;
F_HPF_butter = F_shift .* butterworth_HPF;
F_HPF_gauss = F_shift .* gaussian_HPF;
% Inverse Fourier Transform
img_HPF_ideal = real(ifft2(ifftshift(F_HPF_ideal)));
img_HPF_butter = real(ifft2(ifftshift(F_HPF_butter)));
img_HPF_gauss = real(ifft2(ifftshift(F_HPF_gauss)));
% Display HPF results
figure, imshow(img_HPF_ideal, []), title('Ideal High-Pass Filter');
figure, imshow(img_HPF_butter, []), title('Butterworth High-Pass Filter');
figure, imshow(img_HPF_gauss, []), title('Gaussian High-Pass Filter');
Tasks
Compute and display the Fourier Transform and magnitude spectrum of an
image.
Apply a Low-Pass Filter (LPF) and analyze its e ect on image smoothness.
Implement a High-Pass Filter (HPF) and compare it with LPF results.
Experiment with Butterworth and Gaussian filters and discuss di erences.
Design and apply a Band-Pass and Notch Filter to remove unwanted
frequencies.
Compare spatial and frequency domain approaches for edge detection.
Lab 6: Image Restoration
1. Introduction
Image restoration aims to reconstruct an original image that has been degraded due to
various factors such as noise, blurring, and distortions. The degradation process can be
mathematically modelled and reversed using di erent filtering and deconvolution
techniques. This lab covers key restoration methods, including spatial filtering,
frequency domain filtering, inverse filtering, Wiener filtering, and blind deconvolution.
2. Image Degradation and Noise Models
When an image undergoes degradation, it is often a ected by noise, which can be of
di erent types. The most common noise models include Gaussian noise, salt &
pepper noise, and speckle noise. Each type of noise a ects images di erently,
requiring specific restoration techniques.
2.1 Gaussian Noise
Gaussian noise is a statistical noise with a normal distribution and occurs due to low-
light conditions or thermal fluctuations in sensors. It appears as random variations in
pixel intensity.
Gaussian noise follows a normal (Gaussian) distribution, which is defined by two
parameters:
1. Mean (μ): This represents the average value of the noise. If the mean is zero, the
noise has no bias in either direction (bright or dark).
2. Variance (σ2): This represents the spread or intensity of the noise. A higher
variance means more extreme variations in noise values.
MATLAB Code for Adding Gaussian Noise:
img = im2double(imread('cameraman.jpg'));
gaussian_noise = imnoise(img, 'gaussian', 0, 0.01);
figure, imshow(gaussian_noise); title('Gaussian Noise');
2.2 Salt & Pepper Noise
Salt & Pepper noise results from transmission errors or bit errors in image processing. It
introduces random black and white pixels in the image. It is a type of impulse noise,
meaning it only a ects some pixels while leaving others unchanged.
MATLAB Code for Adding Salt & Pepper Noise:
salt_pepper_noise = imnoise(img, 'salt & pepper', 0.05);
figure, imshow(salt_pepper_noise); title('Salt & Pepper Noise');
2.3 Speckle Noise
Speckle noise is a type of multiplicative noise that commonly a ects images obtained
from coherent imaging systems, such as radar, ultrasound, and laser imaging. It
appears as grainy spots, reducing image clarity and making it harder to interpret details.
Unlike Gaussian or salt & pepper noise (which are additive), speckle noise is
proportional to the original pixel values. This means brighter areas get more noise,
while darker areas have less.
MATLAB Code for Adding Speckle Noise:
speckle_noise = imnoise(img, 'speckle', 0.04);
figure, imshow(speckle_noise); title('Speckle Noise');
3. Noise Reduction Using Spatial Filtering
Spatial filters process images by modifying pixel values based on neighbouring pixel
intensities. The two commonly used spatial filters are Averaging (Mean) Filter and
Median Filter.
3.1 Averaging Filter (Mean Filter)
The averaging filter computes the mean of neighboring pixel values and replaces the
current pixel with this mean. It helps reduce noise but can also blur image details.
MATLAB Code for Averaging Filter:
avg_filter = fspecial('average', [5 5]);
img_avg = imfilter(gaussian_noise, avg_filter);
figure, imshow(img_avg); title('Averaging Filter Applied');
3.2 Median Filter
Unlike the mean filter, the median filter replaces each pixel with the median value of the
neighbouring pixels. It is particularly e ective for removing salt & pepper noise while
preserving edges.
MATLAB Code for Median Filter:
img_median = medfilt2(salt_pepper_noise, [3 3]);
figure, imshow(img_median); title('Median Filter Applied');
4. Periodic Noise Reduction Using Frequency Domain Filtering
Periodic noise appears as repeating patterns in an image, typically caused by electronic
interference or sensor artifacts. This noise can be reduced using frequency domain
filtering.
Steps for Noise Reduction Using FFT:
1. Apply Fast Fourier Transform (FFT): Converts the image into frequency domain.
2. Shift the Zero Frequency Component: Moves low frequencies to the center for
better visualization.
3. Apply Log Transformation: Enhances the spectrum visualization.
4. Use Notch Filtering: Suppresses periodic noise by removing specific
frequencies.
4.1 Fourier Transform and Notch Filtering
In frequency domain filtering, we transform the image using the Fast Fourier Transform
(FFT), locate periodic noise, and apply a notch filter to remove it.
MATLAB Code for Fourier Transform and Notch Filtering:
F = t2(img);
F_shifted = tshift(F);
log_F = log(1 + abs(F_shifted));
figure, imshow(log_F, []); title('Fourier Spectrum');
5. Image Restoration Techniques
Di erent restoration techniques aim to recover the original image from degradation
caused by blur or noise.
5.1 Inverse Filtering
When an image is degraded by a known blur function, inverse filtering attempts to
restore the original image by reversing the e ect of the degradation function in the
frequency domain.
How Does Inverse Filtering Work?
Since the degradation model in the frequency domain is:
We can recover the original image F(u,v) by applying the inverse of H(u,v):
Then, applying the Inverse Fourier Transform gives:
This theoretically restores the original image. However, a major problem arises if H(u,v)
contains near-zero values, since division by small numbers amplifies noise. This makes
inverse filtering highly sensitive to noise and imperfect degradation models.
MATLAB Code for Inverse Filtering:
H = fspecial('motion', 20, 45);
blurred_img = imfilter(img, H, 'conv');
F_blurred = t2(blurred_img);
H_f = t2(H, size(img,1), size(img,2));
F_restored = F_blurred ./ H_f;
img_restored = real(i t2(F_restored));
figure, imshow(img_restored, []); title('Inverse Filtering');
5.2 Wiener Filtering
Wiener filtering is a powerful image restoration technique that reduces noise and
corrects blur in the frequency domain. Unlike inverse filtering, which only considers the
degradation function, Wiener filtering also accounts for noise, making it more e ective
in real-world scenarios.
By minimizing the mean square error (MSE) between the restored and original image, it
balances noise suppression and detail preservation. The filter adapts based on noise
levels—acting like an inverse filter when noise is low but suppressing high frequencies
when noise is strong to prevent amplification.
Wiener filtering is widely used in medical imaging, satellite image processing, and
video restoration, especially for images degraded by motion blur, atmospheric
interference, or sensor noise. Its e ectiveness depends on accurate estimation of noise
and image power, making it a superior alternative to inverse filtering, which is highly
sensitive to noise.
In Wiener filtering, the Noise-to-Signal Ratio (NSR) is manually provided by the user as
a parameter to control noise suppression. It is the inverse of the Signal-to-Noise Ratio
(SNR), meaning a high SNR results in a low NSR and vice versa. The NSR value directly
a ects the filtering process—lower NSR (e.g., 0.001–0.01) is used for cleaner images to
preserve details, while higher NSR (e.g., 0.05–0.1) is used for noisy images to suppress
noise at the cost of losing fine details. Choosing the right NSR requires estimating noise
power and experimenting with di erent values to balance deblurring and noise
reduction e ectively.
MATLAB Code for Wiener Filtering:
img_wiener = deconvwnr(blurred_img, H, 0.01);
figure, imshow(img_wiener, []); title('Wiener Filter Restored');
5.3 Blind Deconvolution
Blind deconvolution is used when the degradation function (blur) is unknown. It
estimates the blur function and restores the image iteratively. Unlike inverse or Wiener
filtering, which require a known blur function, blind deconvolution estimates both the
original image and the blur function simultaneously.
MATLAB Code for Blind Deconvolution:
PSF = fspecial('motion', 20, 45);
[J, P] = deconvblind(blurred_img, PSF);
figure, imshow(J, []); title('Blind Deconvolution');
6. Geometric Transformations and Image Registration
Geometric transformations correct distortions such as rotation, scaling, and translation
in images. Image registration aligns multiple images of the same scene taken from
di erent perspectives.
6.1 Image Registration
Image registration is the process of aligning an image with a reference image by
estimating transformation parameters such as translation, rotation, scaling, and
distortion correction.
MATLAB Code for Image Registration:
moving = imrotate(img, 10, 'bilinear', 'crop');
[tform, ~] = imregcorr(moving, img);
registered_img = imwarp(moving, tform, 'OutputView', imref2d(size(img)));
figure, imshowpair(img, registered_img, 'montage'); title('Image Registration');
Used phase correlation-based registration to estimate the geometric
transformation (tform) needed to align moving with img.
Applies the transformation (tform) to moving using imwarp.
'OutputView', imref2d(size(img)) ensures the registered image matches the size
of img.
Lab 7: Colour Image Processing
Colour Image Representation in MATLAB
Colour images are widely used in digital imaging, computer vision, and various
multimedia applications. Unlike grayscale images, which store only intensity values,
colour images contain additional information about di erent colour components,
allowing for more detailed and realistic visual representation. MATLAB provides multiple
ways to handle and manipulate colour images, primarily through RGB images and
indexed images. Understanding these representations is crucial for tasks such as image
filtering, object detection, and colour correction.
In MATLAB, colour images are stored as multidimensional arrays, where each pixel’s
colour is determined by three primary colour components: Red, Green, and Blue (RGB).
Alternatively, some images use indexed representation, which relies on a colormap to
store colour information e iciently. Each approach has its own advantages and use
cases.
RGB Images
An RGB image is a true-colour representation where each pixel is defined by a
combination of three primary colour intensities: red, green, and blue. The RGB model
closely mimics human vision and is one of the most used colour representations in
digital imaging.
Storage in MATLAB:
RGB images are stored as a three-dimensional matrix of size M × N × 3,
where M and N represent the image height and width, and the third dimension
corresponds to the three colour channels.
Pixel values can be stored in 8-bit unsigned integers (0 to 255) or floating-point
values (0 to 1).
Advantages of RGB Images:
Provides high-fidelity colour representation.
Suitable for photography, medical imaging, and computer graphics.
Disadvantages:
High memory usage due to three values per pixel.
Less e icient for applications requiring optimized storage.
Common Operations in MATLAB:
Extracting individual colour channels:
R = img(:,:,1);
G = img(:,:,2);
B = img(:,:,3);
Indexed Images
An indexed image is a memory-e icient alternative to RGB images. Instead of storing
full RGB values for each pixel, indexed images use a colormap with references (indices)
to define colours.
Components in MATLAB:
1. Index Matrix (M × N): Each value corresponds to an entry in the colormap.
2. Colormap (C × 3): A matrix containing RGB triplets that define available colours.
Advantages of Indexed Images:
Reduced memory usage.
Useful in GIF images, scientific visualizations, and low-power displays.
Disadvantages:
Limited number of colours.
Requires conversion to RGB for full flexibility.
Common Operations in MATLAB:
Converting RGB to Indexed:
[X, map] = rgb2ind(img, 256);
Converting Indexed back to RGB:
RGB_img = ind2rgb(X, map);
IPT Functions for RGB and Indexed Images
MATLAB’s Image Processing Toolbox (IPT) o ers functions to manipulate colour images:
1. Reading and displaying images:
img = imread('filename');
imshow(img);
imwrite(img, 'filename');
2. Extracting and processing colour channels:
R = img(:,:,1);
G = img(:,:,2);
B = img(:,:,3);
3. Converting between colour spaces:
gray = rgb2gray(img);
[X, map] = rgb2ind(img, 256);
RGB_img = ind2rgb(X, map);
MATLAB Code for Colour Image Representation
clc; clear; close all;
% Load an RGB image
img = imread('peppers.png');
% Display the original image
figure; imshow(img); title('Original RGB Image');
% Extract individual R, G, and B channels
R = img(:,:,1); G = img(:,:,2); B = img(:,:,3);
% Display the separate color channels
figure;
subplot(1,3,1), imshow(R), title('Red Channel');
subplot(1,3,2), imshow(G), title('Green Channel');
subplot(1,3,3), imshow(B), title('Blue Channel');
% Convert RGB to Grayscale
gray_img = rgb2gray(img);
% Convert RGB to Indexed with 256 colors
[X, map] = rgb2ind(img, 256);
% Convert Indexed back to RGB
RGB_img = ind2rgb(X, map);
% Display grayscale, indexed, and reconstructed images
figure;
subplot(2,2,1), imshow(img), title('Original RGB Image');
subplot(2,2,2), imshow(gray_img), title('Grayscale Image');
subplot(2,2,3), imshow(X, map), title('Indexed Image');
subplot(2,2,4), imshow(RGB_img), title('Reconstructed RGB from Indexed');
% Display the colormap used
figure; colormap(map); colorbar; title('Colormap Used in Indexed Image');
The YCbCr Colour Space
Used in digital video compression (JPEG, MPEG, H.264), YCbCr separates luminance
and chrominance.
Y (Luminance): Brightness.
Cb (Blue Chrominance): Di erence between blue and luminance.
Cr (Red Chrominance): Di erence between red and luminance.
Conversion in MATLAB:
YCbCr = rgb2ycbcr(img);
RGB_reconstructed = ycbcr2rgb(YCbCr);
The HSV Colour Space
HSV (Hue-Saturation-Value) represents colours based on human perception.
H (Hue): Colour type (0°-360°).
S (Saturation): Colour purity (0 to 1).
V (Value): Brightness (0 to 1).
Conversion in MATLAB:
HSV = rgb2hsv(img);
RGB_reconstructed = hsv2rgb(HSV);