Image Processing Matlab Programs
Image Processing Matlab Programs
Definition
Detailed Explanation
A color image stores three separate intensity values for each pixel: red, green, and
blue. However, many image processing algorithms such as edge detection,
segmentation, filtering, and pattern recognition work better with a single intensity
channel.
To convert RGB to grayscale, a weighted sum of the RGB components is used. These
weights correspond to the human eye’s sensitivity to different colors. Humans
perceive green light most strongly, followed by red, and then blue.
Therefore, the green channel contributes the most to brightness perception.
Mathematical Formula
Where
MATLAB PROGRAM:
figure;
Algorithm / Steps
Key Features
Advantages
Disadvantages
Definition
Detailed Explanation
In many images, objects have intensity values that are significantly different from the
background. Thresholding exploits this difference to separate objects.
If the pixel intensity exceeds the threshold value, the pixel is considered part of the
object; otherwise, it belongs to the background.
This results in a binary image consisting only of black and white pixels.
Mathematical Representation
1 𝑓(𝑥, 𝑦) > 𝑇
𝑔(𝑥, 𝑦) = {
0 𝑓(𝑥, 𝑦) ≤ 𝑇
Where
• 𝑇= threshold value
gray = rgb2gray(imread('[Link]'));
bw_auto = imbinarize(gray);
figure;
Input image :
o 0 (black) if intensity ≤ T
Key Features
Advantages
• Easy to implement
Disadvantages
Applications
Definition
Gaussian blur is a linear smoothing filter used to reduce image noise and detail using a
Gaussian distribution function.
Detailed Explanation
Images often contain high-frequency noise, which can interfere with image analysis tasks
such as edge detection.
Gaussian blur smooths the image by averaging pixel values with neighboring pixels using
weights defined by a Gaussian function.
Pixels closer to the center contribute more to the final value than those farther away.
Gaussian Function
1 𝑥 2 +𝑦 2
−
𝐺(𝑥, 𝑦) = 𝑒 2𝜎2
2𝜋𝜎 2
Where
Matlab program:
img = imread('[Link]');
% Or simply:
figure;
Key Features
Advantages
Disadvantages
Applications
• Image preprocessing
• Computer vision pipelines
• Photography post-processing
Definition
Canny edge detection is a multi-stage algorithm used to detect edges in images with high
accuracy and low error rate.
Detailed Explanation
Edges correspond to rapid changes in image intensity, often indicating object boundaries.
The Canny algorithm is considered one of the most effective edge detection methods
because it reduces noise while detecting thin, well-localized edges.
Matlab program:
gray = rgb2gray(imread('[Link]'));
figure;
Input image :
Processed output image:
1. Gaussian smoothing
Remove noise using Gaussian filter.
2. Gradient calculation
Compute gradient magnitude and direction.
3. Non-maximum suppression
Keep only the strongest edges.
4. Double thresholding
Identify strong and weak edges.
Key Features
• Thin edges
Advantages
• High precision
• Excellent localization
Disadvantages
• Computationally expensive
• Requires parameter tuning
Applications
• Robotics navigation
5. Morphological Dilation
Definition
Detailed Explanation
Morphological operations use a structuring element, which is a small matrix that scans the
image.
In dilation, if any pixel in the structuring element overlaps with the object, the output pixel
becomes part of the object.
Matlab program
gray = rgb2gray(imread('[Link]'));
figure;
Output Image:
Algorithm / Steps
Key Features
• Enlarges objects
Advantages
• Repairs broken edges
• Useful in segmentation
Disadvantages
Applications
• Character recognition
• Shape analysis
[Link] Erosion
Definition
Detailed Explanation
The structuring element is moved across the image. If the structuring element does
not completely fit inside the object, the pixel is removed.
This results in smaller objects and removal of small noise.
Matlab Program
ray = rgb2gray(imread('[Link]'));
bw = imbinarize(gray);
SE = strel('square', 5);
eroded = imerode(bw, SE);
figure;
subplot(1,2,1); imshow(bw); title('Original Binary');
subplot(1,2,2); imshow(eroded); title('After Erosion');
% Erosion = shrinks bright regions, removes noise
Input image:
Output image:
Key Features
• Reduces object size
• Removes small noise
• Separates connected objects
Advantages
• Effective noise removal
• Useful for separating objects
Disadvantages
• Small objects may disappear
• Shape distortion possible
Applications
• Noise filtering
• Image segmentation
• Pattern recognition
7. Histogram Equalization
Definition
Detailed Explanation
Low contrast images often have pixel intensities concentrated in a narrow range.
Histogram equalization spreads these intensities across the entire range, making details
more visible.
Mathematical Formula
𝑘
𝑠𝑘 = (𝐿 − 1) ∑ 𝑝𝑟 (𝑟𝑗 )
𝑗=0
Where
Matlab program:
ray = rgb2gray(imread('[Link]'));
figure;
Output image
Algorithm / Steps
Key Features
• Enhances contrast
• Automatic enhancement
Advantages
Disadvantages
Applications
• Medical imaging
• Satellite imagery
• Surveillance systems
Definition
The Sobel edge detection method is a gradient-based edge detection technique used to
identify edges in images by calculating the rate of intensity change in horizontal and vertical
directions.
Detailed Explanation
Edges in an image represent boundaries between objects where pixel intensity changes
rapidly. The Sobel operator detects these edges by computing the first derivative (gradient)
of the image intensity.
The magnitude of the gradient indicates the strength of the edge, while the gradient
direction indicates the orientation of the edge.
Matlab program:
gray = rgb2gray(imread('[Link]'));
Gx = imfilter(double(gray), fspecial('sobel'));
Gy = imfilter(double(gray), fspecial('sobel')');
% Or simply:
figure;
Input image:
Output image
Sobel Operator Kernels
𝐺 = √𝐺𝑥2 + 𝐺𝑦2
Or an approximate version:
𝐺 =∣ 𝐺𝑥 ∣ +∣ 𝐺𝑦 ∣
Algorithm / Steps
Key Features
Advantages
• Simple implementation
Disadvantages
• Sensitive to noise
Applications
• Image segmentation
• Industrial inspection
9. Image Rotation
Definition
Image rotation is a geometric transformation that rotates an image around a fixed point
(usually the image center) by a specified angle.
Detailed Explanation
Rotation changes the orientation of the image while maintaining its original structure. Every
pixel coordinate in the original image is mapped to a new coordinate using a rotation
transformation.
Since rotated coordinates may not fall exactly on integer pixel locations, interpolation
techniques are used to determine pixel values.
Mathematical Transformation
𝑥 ′ = 𝑥cos 𝜃 − 𝑦sin 𝜃
𝑦 ′ = 𝑥sin 𝜃 + 𝑦cos 𝜃
Where
• 𝑥, 𝑦= original coordinates
• 𝑥 ′ , 𝑦 ′ = rotated coordinates
• 𝜃= rotation angle
Matlab program
img = imread('[Link]');
figure;
Input image
Output image
Algorithm / Steps
Key Features
Advantages
Disadvantages
Applications
• Image alignment
Definition
Image resizing (or scaling) is the process of changing the dimensions of an image by
increasing or decreasing the number of pixels.
Detailed Explanation
Scaling modifies the spatial resolution of an image. When increasing size, new pixels must be
estimated using interpolation. When decreasing size, pixels are combined or removed.
Scaling Transformation
𝑥 ′ = 𝑆𝑥 × 𝑥
𝑦 ′ = 𝑆𝑦 × 𝑦
Where
Matlab program
clc;
clear;
close all;
% Read image
[h, w, c] = size(img);
% Display results
figure;
subplot(1,2,1);
imshow(img);
title('Original Image');
subplot(1,2,2);
imshow(canvas);
title('Processed Result');
Algorithm / Steps
Key Features
Advantages
Disadvantages
Applications
• Image compression
• Multimedia applications
11. Adding Gaussian Noise
Definition
Gaussian noise is a type of noise that follows a normal distribution and randomly alters pixel
intensities across an image.
Detailed Explanation
In real-world imaging systems, noise often arises from electronic sensor interference,
thermal fluctuations, or low light conditions.
Gaussian noise affects every pixel slightly and is modeled mathematically using the Gaussian
probability distribution.
Where
• 𝜎= standard deviation
Matlab program
img = imread('[Link]');
% Or use imnoise:
figure;
Algorithm / Steps
Key Features
Advantages
Disadvantages
Applications
Definition
Salt-and-pepper noise is a type of impulse noise where random pixels appear as white (salt)
or black (pepper) in an image.
Detailed Explanation
This noise occurs due to transmission errors, faulty memory locations, or sensor
malfunction. It randomly replaces pixel intensities with extreme values (0 or 255).
The filter replaces each pixel value with the median value of neighboring pixels, effectively
removing isolated noise.
Matlab program
img = imread('[Link]');
for c = 1:3
end
figure;
Outputimage:
Algorithm / Steps
Key Features
Advantages
• Excellent for salt-and-pepper noise removal
Disadvantages
Applications
• Image restoration
Definition
Image flipping is a geometric transformation that mirrors an image along a specified axis,
producing a reflected version.
Detailed Explanation
Horizontal Flip
The image is mirrored along the vertical axis. The left side becomes the right side.
Vertical Flip
The image is mirrored along the horizontal axis. The top becomes the bottom.
Mathematical Representation
Horizontal Flip
(𝑥, 𝑦) → (𝑤𝑖𝑑𝑡ℎ − 𝑥 − 1, 𝑦)
Vertical Flip
img = imread('[Link]');
flipped_h = fliplr(img);
flipped_v = flipud(img);
% Both flips
figure;
Output:
Algorithm / Steps
• Simple transformation
Advantages
Disadvantages
Applications
• Computer graphics
Definition
Detailed Explanation
Unsharp masking is a common sharpening method where a blurred version of the image is
subtracted from the original image to highlight edges.
The difference between the original and blurred image is called the mask.
Sharpening Formula
Where
• 𝑘= sharpening factor
Matlab program
clc;
clear;
close all;
img = imread('[Link]');
figure;
Output:
Algorithm / Steps
Key Features
• Enhances edges
Advantages
• Improves visual clarity
Disadvantages
Applications
• Medical imaging
Definition
Detailed Explanation
A color image in the RGB color model consists of three separate matrices representing the
red, green, and blue intensity components. By manipulating these channels independently,
different visual effects or analytical results can be obtained.
For example:
• Enhancing the red channel highlights objects with strong red components.
Mathematical Representation
Where
Matlab program
img = imread('[Link]');
swapped = img;
figure;
Output:
Algorithm / Steps
Key Features
Advantages
• Simple to implement
Disadvantages
Applications
Definition
RGB to HSV conversion transforms an image from the Red-Green-Blue (RGB) color space to
the Hue-Saturation-Value (HSV) color space, which separates color information from
brightness.
Detailed Explanation
In the RGB model, color and brightness are mixed together, making color analysis difficult.
The HSV model separates these components:
This separation makes HSV more suitable for color segmentation and object detection
tasks.
Mathematical Representation
Hue calculation:
𝐺−𝐵
60∘ × if 𝑚𝑎𝑥 = 𝑅
Δ
𝐵−𝑅
𝐻 = 60∘ × (2 + ) if 𝑚𝑎𝑥 = 𝐺
Δ
∘
𝑅−𝐺
{ 60 × (4 + ) if 𝑚𝑎𝑥 = 𝐵
Δ
Where
Δ = 𝑚𝑎𝑥(𝑅, 𝐺, 𝐵) − 𝑚𝑖𝑛(𝑅, 𝐺, 𝐵)
Matlab program
img = imread('[Link]');
Output:
Algorithm / Steps
Key Features
Advantages
Applications
• Color-based segmentation
Definition
Detailed Explanation
Unlike manual thresholding, Otsu’s method determines the best threshold based on the
image histogram.
It assumes that the image contains two classes of pixels (bimodal histogram):
• Foreground
• Background
The algorithm selects the threshold that maximizes the between-class variance.
Mathematical Formula
Between-class variance:
𝜎𝑏2 = 𝑤1 𝑤2 (𝜇1 − 𝜇2 )2
Where
• 𝜇1 , 𝜇2 = class means
Matlab Program:
gray = rgb2gray(imread('[Link]'));
% Or in one step:
bw2 = imbinarize(gray, 'global'); % Uses Otsu internally
figure;
Output:
Algorithm / Steps
Key Features
• Histogram-based segmentation
Advantages
Disadvantages
• Sensitive to noise
• Performs poorly when histogram is not bimodal
Applications
• Industrial inspection
18. Laplacian Edge Detection
Definition
Laplacian edge detection is a method that identifies edges by calculating the second
derivative of image intensity.
Detailed Explanation
Edges correspond to locations where the image intensity changes rapidly. The Laplacian
operator highlights these changes by measuring the rate of change of the gradient.
Mathematical Formula
∂2 𝑓 ∂2 𝑓
∇2 𝑓 = +
∂𝑥 2 ∂𝑦 2
Matlab Program:
gray = rgb2gray(imread('[Link]'));
h = fspecial('laplacian', 0.2);
edges = uint8(abs(laplacian));
figure;
Output:
Algorithm / Steps
Key Features
Advantages
• Simple implementation
Disadvantages
Applications
• Medical imaging
• Feature extraction
• Image sharpening
Definition
Detailed Explanation
When images are captured from different viewing angles, objects may appear distorted due
to perspective effects.
Mathematical Formula
𝑎𝑥 + 𝑏𝑦 + 𝑐
𝑥′ =
𝑔𝑥 + ℎ𝑦 + 1
𝑑𝑥 + 𝑒𝑦 + 𝑓
𝑦′ =
𝑔𝑥 + ℎ𝑦 + 1
Where
a, b, c, d, e, f, g, h are transformation parameters.
Matlab Program:
% Perspective Transform
img = imread('[Link]');
[h, w, ~] = size(img);
srcPts = [1 1; w 1; w h; 1 h];
% Compute homography
% Apply transform
Output:
Algorithm / Steps
Key Features
Advantages
Disadvantages
• Computationally complex
Applications
• Image stitching
• Augmented reality
• Robotics navigation
Definition
Gamma correction is a nonlinear image processing technique used to adjust brightness and
contrast according to human visual perception.
Detailed Explanation
Display devices do not respond linearly to intensity values. Gamma correction compensates
for this nonlinearity to ensure images appear correctly on screens.
Low gamma values brighten images, while high gamma values darken them.
Matlab Program:
% Gamma Correction
img = imread('[Link]');
corrected = im2uint8(corrected);
figure;
Output:
Algorithm / Steps
Key Features
Advantages
Disadvantages
Applications
• Digital photography
• Display calibration
• Video processing
21. Morphological Opening
Definition
Detailed Explanation
Opening is performed by erosion followed by dilation using the same structuring element.
Erosion removes small objects, and dilation restores the size of the remaining objects.
Matlab Program:
% Morphological Opening
gray = rgb2gray(imread('[Link]'));
bw = imbinarize(gray);
figure;
Input image:
Output:
Algorithm / Steps
Key Features
Advantages
Disadvantages
Applications
• Noise filtering
• Image segmentation
• Shape analysis
22. Morphological Closing
Definition
Morphological closing is an operation used to fill small holes and connect nearby
objects in an image.
Detailed Explanation
Matlab Program:
% Morphological Closing
gray = rgb2gray(imread('[Link]'));
bw = imbinarize(gray);
% Manual closing:
figure;
Input image:
Output image :
Algorithm / Steps
Key Features
Advantages
Disadvantages
Applications
• Pattern recognition
• Object detection
23. Color Image Histogram Equalization
Definition
Histogram
Mathematical Background
• 𝑟𝑘 = intensity level
Algorithm / Steps
Applications
➢ Image enhancement in digital image processing
➢ Medical imaging (improves visibility in X-ray, MRI)
➢ Satellite and remote sensing images
➢ Surveillance and security systems
Advantages
➢ Improves image contrast
➢ Enhances details in dark or low-contrast images
➢ Simple and easy to implement
➢ Works automatically without manual adjustment
Disadvantages
➢ May produce over-enhancement in some regions
➢ Can change original colors in color images
➢ Amplifies noise in low-quality images
➢ Not suitable for all types of images
[Link] (Adaptive Histogram Equalization):
Definition
Detailed Explanation
Mathematical Expression:
Let the image intensity be:
𝐼(𝑥, 𝑦)
Histogram:
ℎ(𝑟𝑘 ) = 𝑛𝑘
Probability distribution:
𝑛𝑘
𝑝(𝑟𝑘 ) =
𝑁
𝐶𝐷𝐹(𝑟𝑘 ) = ∑ 𝑝( 𝑟𝑗 )
𝑗=0
Transformation function:
𝑠𝑘 = (𝐿 − 1) × 𝐶𝐷𝐹(𝑟𝑘 )
Algorithm
PROGRAM:
clc;
clear;
close all;
% Read image
img = imread('[Link]'); % Replace with your image
[h, w, c] = size(img);
% Resize image to smaller size
small = imresize(img, 0.4); % 40% scaling
% Create black canvas same size as original
canvas = zeros(h, w, c, 'uint8'); % Black image
% Get small image size
[hs, ws, ~] = size(small);
% Place small image at top-left corner of canvas
canvas(1:hs, 1:ws, :) = small;
% Display results
figure;
subplot(1,2,1);
imshow(img);
title('Original Image');
subplot(1,2,2);
imshow(canvas);
title('Processed Result');
Applications
Disadvantages
Harris Corner Detection is a technique used in image processing to detect corner points
where image intensity changes in multiple directions.
Detailed Explanation
Mathematical Expression
Image gradients:
∂𝐼 ∂𝐼
𝐼𝑥 = , 𝐼𝑦 =
∂𝑥 ∂𝑦
Structure tensor:
𝐼𝑥2 𝐼𝑥 𝐼𝑦
𝑀=[ ]
𝐼𝑥 𝐼𝑦 𝐼𝑦2
Harris response:
𝑅 = 𝑑𝑒𝑡(𝑀) − 𝑘(𝑡𝑟𝑎𝑐𝑒(𝑀))2
where 𝑘 ≈ 0.04
Interpretation:
R > 0 → Corner
R < 0 → Edge
R ≈ 0 → Flat region
Algorithm
➢ Read the input image.
➢ Convert image to grayscale.
➢ Compute image gradients (Ix, Iy).
➢ Form the structure tensor matrix.
➢ Calculate Harris response (R).
➢ Select pixels with high R values as corners.
➢ Display detected corners.
PROGRAM:
% Harris Corner Detection
img = imread('[Link]');
gray = rgb2gray(img);
% Detect Harris corners corners = detectHarrisFeatures(gray, ... 'MinQuality', 0.01, ...
'FilterSize', 5);
% Visualize corners figure;
imshow(img);
hold on;
plot([Link](50));
% Show 50 strongest corners
title('Harris Corner Detection');
hold off;
Applications
➢ Feature matching
➢ Object recognition
➢ Image stitching
➢ Motion tracking
➢ 3D reconstruction
Advantages
➢ Accurate corner detection
➢ Rotation invariant
➢ Useful for feature extraction
Disadvantages
➢ Not scale invariant
➢ Sensitive to parameter selection
➢ Higher computational cost.
Detailed Definition
Brightness and contrast adjustment modifies the pixel intensity values of an image
using a linear transformation. Brightness shifts all pixel values to make the image lighter or
darker, while contrast scales the intensity difference between pixels. This technique improves
image clarity and is commonly used as a preprocessing step in image processing and computer
vision applications.
Mathematical Expression
𝑔(𝑥, 𝑦) = 𝛼𝑓(𝑥, 𝑦) + 𝛽
Where:
• f(x,y) – Original pixel intensity
• g(x,y) – Output pixel intensity
• α – Contrast factor
• β – Brightness offset
Conditions:
• α > 1 → Increase contrast
• 0 < α < 1 → Decrease contrast
• β > 0 → Increase brightness
• β < 0 → Decrease brightness
Algorithm
PROGRAM:
% Brightness and Contrast Adjustment
img = imread('[Link]');
img_double = im2double(img);
alpha = 1.5; % Contrast multiplier (>1 = more contrast)
beta = -0.1; % Brightness offset (>0 = brighter)
adjusted = alpha * img_double + beta;
adjusted = max(0, min(1, adjusted)); % Clip to valid range
adjusted = im2uint8(adjusted);
figure;
subplot(1,2,1); imshow(img); title('Original');
subplot(1,2,2); imshow(adjusted);
title(['alpha=' num2str(alpha) ' beta=' num2str(beta)])
Applications
➢ Medical image enhancement
➢ Digital photography
➢ Satellite image analysis
➢ Computer vision preprocessing
➢ Security and surveillance systems
Advantages
➢ Simple and easy to implement
➢ Improves image visibility
➢ Computationally efficient
➢ Useful preprocessing technique
Disadvantages
➢ Excess adjustment may cause pixel saturation
➢ Some image details may be lost
➢ Linear adjustment may not work well for all images
27. Log Transformation
Definition
Log transformation is an image enhancement technique used to expand dark
pixel values and compress bright pixel values. It helps improve the visibility of details
in darker regions of an image.
Detailed Definition
Mathematical Expression
𝑠 = 𝑐log(1 + 𝑟)
Where:
r = Input pixel intensity
s = Output pixel intensity
c = Scaling constant
log = Logarithmic function
The constant c controls the scaling of the output image.
Algorithm
➢ Read the input image.
➢ Convert the image to double format.
➢ Choose the scaling constant c.
➢ Apply the logarithmic transformation 𝑠 = 𝑐log(1 + 𝑟).
➢ Normalize the result to keep pixel values in the valid range.
➢ Display the original and processed images.
PROGRAM:
% Log Transformation
img = imread('[Link]');
img_double = im2double(img); c = 1; % Scaling constant
log_img = c * log(1 + img_double); % Apply log transform
log_img = log_img / max(log_img(:)); % Normalize to [0,1]
% This brightens dark regions more than bright ones
% Useful for: HDR images, Fourier spectrum display
figure; subplot(1,2,1);
imshow(img); title('Original');
subplot(1,2,2); imshow(log_img);
title('Log Transformed')
Applications
➢ Enhancement of dark regions in images
➢ High Dynamic Range (HDR) image processing
➢ Display of Fourier transform spectrum
➢ Medical image enhancement
➢ Satellite and remote sensing images
Advantages
➢ Enhances details in dark areas of the image
➢ Reduces intensity of very bright regions
➢ Improves visibility in high dynamic range images
➢ Simple and easy to implement
Disadvantages
➢ Bright regions may lose some details
➢ Not suitable for all types of images
➢ Requires normalization after transformation
➢ Excessive scaling may distort image intensity values
28. Pseudocolor / False Color Mapping
Definition
Detailed Definition
The technique does not change the original data but enhances visualization. Common
colormaps include Jet, Hot, HSV, Parula, Cool, Spring, Summer, Autumn, and Winter. For
example, in the Jet colormap, low intensity values appear blue while high intensity values
appear red.
Mathematical Expression
If I(x,y) is the grayscale intensity value, the pseudocolor mapping can be expressed as:
Where:
I(x,y) = Input grayscale pixel value
M = Colormap function (lookup table)
C(x,y) = Output colored pixel value
Algorithm
➢ Read the input image.
➢ Convert the image to grayscale if necessary.
➢ Select a suitable colormap (Jet, Hot, HSV, etc.).
➢ Map grayscale intensity values to corresponding colors using the colormap.
➢ Display the colored image along with a color scale (colorbar).
PROGRAM:
% Pseudocolor / False Color Mapping
gray = rgb2gray(imread('[Link]'));
% Apply colormap to grayscale image
figure;
subplot(1,3,1);
imshow(gray);
title('Grayscale');
subplot(1,3,2);
imagesc(gray);
colormap(jet);
colorbar;
title('Jet Colormap');
subplot(1,3,3);
imagesc(gray);
colormap(hot);
colorbar;
title('Hot Colormap');
% Other colormaps: parula, hsv, cool, spring, summer, autumn, winter
Applications:
Advantages
Detailed Explanation
• 4-Connectivity: A pixel is connected to its top, bottom, left, and right neighbours.
• 8-Connectivity: A pixel is connected to all eight surrounding pixels, including
diagonal neighbours.
After labeling the components, properties such as area, centroid, and bounding box can be
calculated. This information is useful for object detection, counting, and analysis.
Mathematical Expression
Where:
• B(x,y) = Binary pixel value (0 or 1)
• L(x,y) = Label assigned to the pixel
• k = Unique label for each connected component
All connected pixels with value 1 are assigned the same label.
Algorithm
PROGRAM:
% Connected Component
gray = rgb2gray(imread('[Link]'));
bw = imbinarize(gray);
% Label connected components
[labeled, num_components] = bwlabel(bw, 8); % 8-connectivity
fprintf('Found %d components\n', num_components); % Get properties
stats = regionprops(labeled, 'Area', 'Centroid', 'BoundingBox');
% Visualize with colors
colored = label2rgb(labeled, 'jet', 'k');
figure;
subplot(1,2,1);
imshow(bw);
title('Binary Image');
subplot(1,2,2);
imshow(colored);
title(['CCL: ' num2str(num_components) ' components']);
Applications
➢ Object counting in images
➢ Character recognition (OCR)
➢ Medical image analysis
➢ Vehicle number plate detection
➢ Shape and object detection in computer vision
Advantages
➢ Helps identify and separate objects in an image
➢ Useful for object counting and feature extraction
➢ Simple and effective technique for binary images
➢ Widely used in computer vision applications
Disadvantages
➢ Works mainly on binary images
➢ Sensitive to noise in the image
➢ Requires preprocessing like thresholding
➢ Complex scenes with overlapping objects may reduce accuracy
Detailed Definition
Contour detection is used to find continuous curves that represent the boundaries of
objects in a binary or thresholded image. These curves are formed by connecting pixels that
lie on the edges of an object. Contours help describe the shape and structure of objects in an
image.
In image processing, contour detection is usually performed after converting the image into a
binary image. Algorithms then trace the connected boundary pixels to form a contour.
Functions like bwboundaries() in MATLAB or findContours() in OpenCV are commonly
used to detect these boundaries.
Contours provide useful information such as area, perimeter, centroid, and shape
properties, which can be used for object detection, recognition, and shape analysis.
Mathematical Expression
Let B(x,y) represent a binary image.
Where:
• B(x,y) = Binary pixel value
• C = Set of contour boundary pixels
Algorithm
PROGRAM:
% Contour Detection
img = imread('[Link]');
gray = rgb2gray(img);
bw = imbinarize(gray); % Find boundaries of all objects boundaries =
bwboundaries(bw);
Draw contours on original image figure;
imshow(img);
hold on;
for k = 1:length(boundaries) b = boundaries{k};
plot(b(:,2), b(:,1), 'g-', 'LineWidth', 2);
end title(['Contours: ' num2str(length(boundaries)) ' found']);
hold off;
Applications
➢ Object detection and recognition
➢ Shape analysis in computer vision
➢ Medical image analysis
➢ Handwriting and character recognition
➢ Vehicle and number plate detection
Advantages
➢ Helps identify object boundaries clearly
➢ Useful for shape analysis and feature extraction
➢ Works well for object detection tasks
➢ Provides useful geometric information like area and perimeter
Disadvantages
➢ Sensitive to image noise
➢ Requires preprocessing like thresholding
➢ May fail if object boundaries are unclear
➢ Complex scenes may produce too many contours
Detailed Definition
Mathematical Expression
Where:
• Gx = Gradient in horizontal direction
• Gy = Gradient in vertical direction
• θ = Gradient direction (angle)
Algorithm
➢ Read the input image.
➢ Convert the image to grayscale.
➢ Apply gradient filters (such as Sobel) to compute Gx and Gy.
➢ Calculate gradient magnitude.
➢ Compute gradient direction using
𝜃 = tan−1 (𝐺𝑦/𝐺𝑥).
➢ Normalize direction values if required.
➢ Display or visualize the gradient direction.
PROGRAM:
% Gradient Direction Computation
gray = rgb2gray(imread('[Link]'));
% Compute gradients Gx = imfilter(double(gray), fspecial('sobel'));
Gy = imfilter(double(gray), fspecial('sobel')');
% Gradient magnitude and direction magnitude = sqrt(Gx.^2 + Gy.^2);
direction = atan2d(Gy, Gx); % Direction in degrees [-180, 180]
% Visualize direction as hue (color)
H = (direction + 180) / 360;
% Normalize to [0,1] S = ones(size(H));
V = magnitude / max(magnitude(:));
hsv_vis = cat(3, H, S, V);
dir_vis = hsv2rgb(hsv_vis);
figure;
subplot(1,2,1);
imshow(gray);
title('Grayscale');
subplot(1,2,2);
imshow(dir_vis);
title('Gradient Direction (HSV)');
Advantages
➢ Provides information about edge orientation
➢ Useful for feature extraction in computer vision
➢ Helps improve edge detection accuracy
➢ Useful in object recognition systems
Disadvantages
➢ Sensitive to image noise
➢ Requires gradient computation which increases processing time
➢ Accuracy depends on the quality of the input image
➢ May produce incorrect directions in noisy images
Detailed Definition
Mathematical Expression
Where:
• f(x,y) = Input image in spatial domain
• F(u,v) = Frequency domain representation
• M, N = Image dimensions
• u, v = Frequency coordinates
Algorithm
PROGRAM:
% 2D Fourier Transform
gray = rgb2gray(imread('[Link]'));
% Compute DFT and shift DC to center
F = fft2(double(gray));
Fshift = fftshift(F);
% Compute magnitude spectrum (log scale for visibility)
magnitude = 20 * log(abs(Fshift) + 1);
% Phase spectrum
phase = angle(Fshift);
figure;
subplot(1,3,1);
imshow(gray);
title('Spatial Domain');
subplot(1,3,2);
imshow(magnitude, []);
title('Magnitude Spectrum');
subplot(1,3,3);
imshow(phase, []);
title('Phase Spectrum');
Applications
Advantages
Disadvantages
Detailed Definition
In image processing, frequency domain filtering is performed after converting the
image into the frequency domain using the Fourier Transform. A low-pass filter removes
high-frequency components such as edges, fine details, and noise, while preserving low-
frequency components that represent the general structure of the image.
This filtering is done by multiplying the Fourier transform of the image with a filter mask that
keeps low frequencies near the center and suppresses high frequencies farther from the center.
The filtered image is then converted back to the spatial domain using the Inverse Fourier
Transform.
Low-pass filtering is commonly used for image smoothing and noise reduction.
Mathematical Expression
The filtered image in the frequency domain is given by:
𝐺(𝑢, 𝑣) = 𝐻(𝑢, 𝑣) ⋅ 𝐹(𝑢, 𝑣)
Where:
• F(u,v) = Fourier transform of the input image
• H(u,v) = Low-pass filter function
• G(u,v) = Filtered frequency output
•
The final image is obtained by applying the Inverse Fourier Transform.
Algorithm
PROGRAM:
% Low-Pass Filter in Frequency Domain
gray = rgb2gray(imread('[Link]'));
F = fft2(double(gray));
Fshift = fftshift(F);
% Create circular low-pass mask
[rows, cols] = size(gray);
[X, Y] = meshgrid(1:cols, 1:rows);
D0 = 30;
% Cutoff frequency (pixels) D = sqrt((X - cols/2).^2 + (Y - rows/2).^2);
mask = double(D <= D0); % 1 inside circle, 0 outside
% Apply mask and inverse DFT
filtered = Fshift .* mask;
img_back = ifft2(ifftshift(filtered));
img_back = uint8(real(img_back));
figure;
subplot(1,2,1);
imshow(gray);
title('Original');
subplot(1,2,2);
imshow(img_back);
title(['Low-Pass Filter D0=' num2str(D0)]);
Advantages
Disadvantages
Mathematical Expression
• Ideal HPF:
0, 𝐷(𝑢, 𝑣) ≤ 𝐷0
𝐻(𝑢, 𝑣) = {
1, 𝐷(𝑢, 𝑣) > 𝐷0
Algorithm
2. Apply FFT
5. Inverse FFT
6. Normalize output
Program :
INPUT IMAGE: OUTPUT IMAGE:
Applications
• Edge detection
• Image sharpening
Advantages
• Amplifies noise
Mathematical Expression
∣∣𝑥−𝑥𝑖 ∣∣ 2 ∣𝐼(𝑥)−𝐼(𝑥𝑖 )∣ 2
′
1 −
2𝜎 2 −
2𝜎𝑟2
𝐼 (𝑥) = ∑ 𝐼( 𝑥𝑖 )𝑒 𝑠 𝑒
𝑊𝑝
𝑥𝑖
Algorithm
Program:
INPUT IMAGE: OUTPUT IMAGE:
Applications
• Noise reduction
• Cartoon effect
Advantages
• Preserves edges
• Smooths noise
Disadvantages
• Computationally expensive
• Parameter sensitive
Mathematical Expression
𝑘
𝐽 = ∑ ∑ ∣∣ 𝑥 − 𝜇𝑖 ∣∣2
𝑥∈𝐶𝑖
𝑖=1
Algorithm
1. Choose K clusters
2. Initialize centroids
4. Update centroids
Program:
Applications
• Object segmentation
• Image compression
Advantages
• Simple
• Fast
Disadvantages
• Needs K value
• Sensitive to initialization
Expression
𝐺𝑟𝑎𝑑𝑖𝑒𝑛𝑡 = (𝐴 ⊕ 𝐵) − (𝐴 ⊖ 𝐵)
Algorithm
1. Apply dilation
2. Apply erosion
3. Subtract results
Program:
INPUT IMAGE: OUTPUT IMAGE:
Applications
• Edge detection
Advantages
• Simple
• Highlights boundaries
Disadvantages
Expression
• White:
𝑇𝑜𝑝𝐻𝑎𝑡 = 𝑓 − (𝑓 ∘ 𝑏)
• Black:
𝐵𝑜𝑡𝑡𝑜𝑚𝐻𝑎𝑡 = (𝑓 ∙ 𝑏) − 𝑓
Algorithm
1. Perform opening/closing
Program:
Applications
Advantages
Disadvantages
• Depends on structuring element
Expression
𝐼 = 𝛼𝐴 + (1 − 𝛼)𝐵
Algorithm
1. Resize images
2. Choose alpha
Program:
• Photo editing
• AR
Advantages
• Simple
• Smooth transitions
Disadvantages
• Ghosting if misaligned
Expression
𝐺 = √𝐺𝑥2 + 𝐺𝑦2
Algorithm
3. Compute magnitude
Program:
INPUT IMAGE: OUTPUT IMAGE:
Applications
• Edge detection
Advantages
• Simple to implement
Disadvantages
• Sensitive to noise
Expression
𝜌 = 𝑥cos 𝜃 + 𝑦sin 𝜃
Algorithm
1. Edge detection
3. Find peaks
Program:
Applications
• Lane detection
Advantages
Disadvantages
• Computationally heavy
Detects circles.
Expression
(𝑥 − 𝑎)2 + (𝑦 − 𝑏)2 = 𝑟 2
Algorithm
1. Edge detection
2. Vote in 3D accumulator
3. Detect peaks
Program:
Applications
• Coin detection
Advantages
• Robust
Disadvantages
• High complexity
Expression
𝑥 ′ = 𝑥 + 𝑘𝑦, 𝑦 ′ = 𝑦
Algorithm
Program:
• Image correction
Advantages
• Preserves lines
Disadvantages
• Distorts shape
Expression
Algorithm
1. Slide template
2. Compute similarity
3. Find max
Program:
INPUT IMAGE: OUTPUT IMAGE:
Applications
• Face detection
Advantages
• Easy
Disadvantages
• Sensitive to scale
Expression
∣ 𝐼𝑡 − 𝐵 ∣> 𝑇
Algorithm
1. Store background
3. Threshold
Program:
INPUT IMAGE: OUTPUT IMAGE:
Applications
• Surveillance
Advantages
• Fast
Disadvantages
• Lighting sensitive
Non-parametric clustering.
Expression
∑𝑥𝑖 𝐾(𝑥𝑖 − 𝑥)
𝑚(𝑥) =
∑𝐾(𝑥𝑖 − 𝑥)
Algorithm
1. Choose window
2. Compute mean
3. Shift window
4. Repeat
Program:
Applications
• Segmentation
Advantages
• No K required
Disadvantages
• Slow
47. Watershed Segmentation
Definition
Algorithm
1. Compute gradient
2. Mark seeds
3. Flood regions
Program:
• Medical imaging
Advantages
• Accurate boundaries
Disadvantages
• Over-segmentation
Content-aware resizing.
Expression
𝐸 =∣ ∇𝐼 ∣
Algorithm
3. Remove seam
Program:
INPUT IMAGE: OUTPUT IMAGE:
Applications
• Image resizing
Advantages
Disadvantages
• Distorts objects
Algorithm
3. Iterate
Program:
Applications
• Object removal
Advantages
• Restores images
Disadvantages
• Blurry results
Mathematical Expression
2
2
Algorithm
Program:
INPUT IMAGE: OUTPUT IMAGE:
Applications
• Image compression
• Multi-scale analysis
Advantages
• Reduces noise
Disadvantages
• Loss of details
• Not reversible
Mathematical Expression
𝐿𝑖 = 𝐺𝑖 − 𝐸𝑥𝑝𝑎𝑛𝑑(𝐺𝑖+1 )
Algorithm
4. Store result
Program:
• Image blending
• Compression
Advantages
• Preserves details
• Efficient reconstruction
Disadvantages
• Computationally complex
Mathematical Expression
∂𝐼
= ∇ ⋅ (𝑐(𝑥, 𝑦, 𝑡)∇𝐼)
∂𝑡
Algorithm
1. Compute gradients
• Noise reduction
• Medical imaging
Advantages
• Preserves edges
• Reduces noise
Disadvantages
• Parameter sensitive
• Slow convergence
Mathematical Expression
7
𝐼(𝑥, 𝑦) = ∑ 𝑏𝑘 (𝑥, 𝑦) ⋅ 2𝑘
𝑘=0
Algorithm
3. Analyze or reconstruct
Program:
Applications
• Image compression
• Watermarking
Advantages
• Simple
Disadvantages
Mathematical Expression
Algorithm
4. Normalize
Program:
INPUT IMAGE: OUTPUT IMAGE:
Applications
• Low-light enhancement
• Image correction
Advantages
• Improves contrast
• Handles illumination
Disadvantages
• Halo artifacts
• Computational cost
Kernel
−2 −1 0
[−1 1 1]
0 1 2
Algorithm
1. Define kernel
Program:
• Image effects
• Feature enhancement
Advantages
• Simple
• Highlights edges
Disadvantages
Mathematical Concept
𝑆 = ⋂ 𝑋𝑘
𝑘=0
Algorithm
1. Convert to binary
4. Repeat
Program:
Applications
• OCR
• Shape analysis
Advantages
• Reduces data
• Preserves topology
Disadvantages
• Sensitive to noise
57. Integral Image (Summed Area Table)
Definition
Mathematical Expression
Algorithm
Program:
INPUT IMAGE: OUTPUT IMAGE:
Applications
Advantages
Disadvantages
• Extra memory
Mathematical Expression
Algorithm
1. Rotate image
Program:
Applications
• CT scan reconstruction
Advantages
• Useful in tomography
Disadvantages
• Computationally intensive
Mathematical Idea
Minimize error:
𝐸 = ∑ ∣∣ 𝐼 − 𝑄(𝐼) ∣∣2
Algorithm
1. Choose K colors
2. Assign pixels
3. Update palette
Program:
Applications
• Image compression
Advantages
• Reduces storage
Disadvantages
Mathematical Expression
Algorithm
1. Convert to binary
2. Initialize distances
Applications
• Shape analysis
Advantages
• Sensitive to noise
𝑀𝐴𝑋 2
𝑃𝑆𝑁𝑅 = 10log10 ( )
𝑀𝑆𝐸
SSIM
(2𝜇𝑥 𝜇𝑦 + 𝐶1 )(2𝜎𝑥𝑦 + 𝐶2 )
𝑆𝑆𝐼𝑀 =
(𝜇𝑥2 + 𝜇𝑦2 + 𝐶1 )(𝜎𝑥2 + 𝜎𝑦2 + 𝐶2 )
program:
INPUT IMAGE: OUTPUT IMAGE:
Applications
• Image comparison
Advantages
• Quantitative evaluation
Disadvantages
Expression
𝑃−1
𝐿𝐵𝑃 = ∑ 𝑠( 𝑔𝑝 − 𝑔𝑐 )2𝑝
𝑝=0
Algorithm
1. Compare neighbors with center
3. Convert to decimal
Program:
INPUT IMAGE: OUTPUT IMAGE:
Applications
• Face recognition
Advantages
• Simple
• Fast
Disadvantages
• Sensitive to noise
Mathematical Expression
Algorithm
1. Compare patches
2. Compute weights
3. Weighted averaging
Program:
INPUT IMAGE: OUTPUT IMAGE:
Applications
• Medical images
Advantages
• High-quality denoising
Disadvantages
• Very slow
Mathematical Concept
Homography:
𝑥 ′ = 𝐻𝑥
Algorithm
2. Match features
3. Estimate homography
4. Warp images
5. Blend images
Program:
Applications
• Panorama photography
• Satellite imaging
Advantages
Disadvantages
• Requires overlap
• Sensitive to mismatches