0% found this document useful (0 votes)
8 views54 pages

Image Processing-Lab (Course Content)

The document outlines a comprehensive guide on image processing fundamentals, covering various labs that include reading, displaying, and manipulating images using Python. It details techniques such as point processing, histogram processing, intensity transformations, spatial filtering, and morphological operations, along with practical applications and projects. Each lab includes objectives, example codes, and tasks for hands-on practice in image processing concepts.

Uploaded by

Muhammad Ishfaq
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views54 pages

Image Processing-Lab (Course Content)

The document outlines a comprehensive guide on image processing fundamentals, covering various labs that include reading, displaying, and manipulating images using Python. It details techniques such as point processing, histogram processing, intensity transformations, spatial filtering, and morphological operations, along with practical applications and projects. Each lab includes objectives, example codes, and tasks for hands-on practice in image processing concepts.

Uploaded by

Muhammad Ishfaq
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Table of Contents

LAB 1 : Image Processing Fundamentals .............................................................................................4


Reading an Image...................................................................................................................................... 4
Display An Image....................................................................................................................................... 4
Writing Image Data ................................................................................................................................... 5
How to get no. of rows and columns of image ......................................................................................... 5
Accessing the Pixel data ............................................................................................................................ 6
Mirror Image Generation .......................................................................................................................... 6
LAB 2 : Image Processing Fundamentals .............................................................................................8
Changing the number of gray Levels ........................................................................................................ 8
Nearest Neighbor Interpolation:......................................................................................................... 10
Bilinear Interpolation: ......................................................................................................................... 10
Some Useful PYTHON Functions .............................................................................................................. 12
LAB 3 : Point Processing Operations and Histogram Processing ......................................................... 13
Point Processing Operations ................................................................................................................... 13
Brightness Adjustment........................................................................................................................ 13
Contrast Adjustment ........................................................................................................................... 14
LAB 4: The Histogram Processing ...................................................................................................... 16
Histogram Processing.............................................................................................................................. 16
Histogram Equalization ....................................................................................................................... 16
Histogram Matching (Specification) ................................................................................................... 17
LAB 5: Intensity Transformations (part 1) .......................................................................................... 19
Image Negation ....................................................................................................................................... 20
LAB 6: Intensity Transformations (part 2) .......................................................................................... 22
Log Transformations ............................................................................................................................... 22
Power-Law Transformations ................................................................................................................... 22
Power Law Transform ............................................................................................................................. 23
LAB 7: Spatial Filtering ..................................................................................................................... 25
Smoothing Spatial Filters ........................................................................................................................ 25
1
Order Statistics Filters ............................................................................................................................. 25
a) Median Filter ................................................................................................................................... 25
b) Max Filter ........................................................................................................................................ 25
c) Min Filter ......................................................................................................................................... 26
........................................................................................................................................................ 28
LAB 8: Spatial Features In Image Processing ...................................................................................... 29
1. What Are Spatial Features? ................................................................................................................ 29
2. Applications Of Spatial Features ......................................................................................................... 29
3. Sharpening Spatial Features ............................................................................................................... 29
4. Methods For Sharpening..................................................................................................................... 30
(a) High-Pass Filtering ......................................................................................................................... 30
(b) Unsharp Masking (USM) ................................................................................................................ 31
(c) Laplacian Sharpening ..................................................................................................................... 31
(d) High-Boost Filtering ....................................................................................................................... 31
5. Understanding Convolution And Kernels............................................................................................ 31
LAB 9: Morphological Operations ..................................................................................................... 33
1. Dilation ................................................................................................................................................ 33
2. Erosion ................................................................................................................................................ 34
3. Opening ............................................................................................................................................... 35
4. Closing ................................................................................................................................................. 36
LAB 10: Edge Detection .................................................................................................................... 37
Introduction: ........................................................................................................................................... 37
Sobel Edge Detection: ......................................................................................................................... 37
Prewitt Edge Detection:....................................................................................................................... 37
Canny Edge Detection: ........................................................................................................................ 37
Implementation in Python:...................................................................................................................... 37
LAB 11: Fourier and Cosine Transforms in Image Processing .............................................................. 40
1. Fourier Transform In Image Processing .............................................................................................. 40
2. Discrete Cosine Transform (Dct) ......................................................................................................... 41
LAB 12: Image Compression ............................................................................................................. 43
1. Image Compression Basics .................................................................................................................. 43
2
2. Types Of Image Compression.............................................................................................................. 43
A. Lossless Compression ..................................................................................................................... 43
B. Lossy Compression .......................................................................................................................... 44
LAB 13: Color Models and Color Transformations.............................................................................. 46
1. Color Models In Image Processing ...................................................................................................... 46
Common Color Models ....................................................................................................................... 46
2. Color Transformations ........................................................................................................................ 46
3. When To Use Which Model? .............................................................................................................. 47
LAB 14: Practical Applications and Projects ....................................................................................... 48
1. Introduction To Medical Image Processing......................................................................................... 48
2. Basic Operations In Python ................................................................................................................. 48
3. Tasks .................................................................................................................................................... 50
4. Optional Extension .............................................................................................................................. 50
LAB 15: Practical Applications and Projects ....................................................................................... 51
Object Detection Using R-CNN in PyTorch.............................................................................................. 51
1. Introduction To R-Cnn ..................................................................................................................... 51
2. Implementation Using Pytorch ....................................................................................................... 51
Output ................................................................................................................................................. 53
Output ................................................................................................................................................. 53

3
LAB 1

LAB 1 : Image Processing Fundamentals

Lab Objectives
This objective of this lab is to understand
1. How to read an image in PYTHON.
2. How to show an image in PYTHON.
3. How to access Image Pixels in PYTHON.
4. How to write Image in PYTHON.
5. Mirror Image generation.
6. Flipped Image generation.

Reading an Image
To import an image from any supported graphics image file format, in any of the supported bit
depths, use the imread function.
Syntax

A = imread(filename,fmt)

Description
A = imread(filename,fmt) reads a greyscale or color image from the file specified by the string
filename, where the string fmt specifies the format of the file. If the file is not in the current
directory or in a directory in the MATLAB path, specify the full pathname of the location on
your system.

Display An Image
To display image, use the imshow function.

Syntax
4
imshow(A)

Description

imshow(A) displays the image stored in array A.

Writing Image Data


Imwrite

Write image to graphics file


Syntax
[Link](filename, image)
Example:

import cv2
# Load an image in grayscale
image = [Link]("[Link]", cv2.IMREAD_GRAYSCALE) # Save the image to a new file
[Link]("[Link]", image)
# Saves in PNG format is used to display image

How to get no. of rows and columns of image


Function size gives the rows and columns dimension of image
import cv2
# Load image

5
a = [Link]("[Link]", cv2.IMREAD_GRAYSCALE) # Load as grayscale
# Get rows and columns r, c = [Link]
print("r =", r)
print("c =", c)
Accessing the Pixel data
There is a one-to-one correspondence between pixel coordinates and the coordinates
MATLAB® uses for matrix subscripting. This correspondence makes the relationship
between an image's data matrix and the way the image is displayed easy to understand. For
example, the data for the pixel in the fifth row, second column is stored in the matrix element
(5,2). You use normal MATLAB matrix subscripting to access values of individual pixels. For
example, the MATLAB code

A(2,15)
returns the value of the pixel at row 2, column 15 of the image A.
Mirror Image Generation
this program produces mirror image of the image passed to it n also displays both the original and
mirror image
import cv2
import numpy as np

import [Link] as plt

# Read image in grayscale


a = [Link]("[Link]", cv2.IMREAD_GRAYSCALE)

# Get rows and columns


r, c = [Link]

# Generate mirror image using NumPy


slicing result = a[:, ::-1] # Flip horizontally
# Display images
[Link](figsize=(10, 5))
[Link](1, 2, 1)
[Link](a, cmap='gray')
[Link]("Original Image")
[Link]("off")

6
[Link](1, 2, 2)
[Link](result, cmap='gray')
[Link]("Mirror Image")
[Link]("off")
[Link]()

TASK 1
Write a PYTHON code that reads a gray scale image and generates the flipped image of original
image.

Your output should be like the one given below

TASK 2
Write a PYTHON code that will do the following
1. Read any gray scale image.
2. Display that image.
3. Again display the image such that the pixels having intensity values below than 50 will
display as black and pixels having intensity values above than 150 will display as white. And
the pixels between these will display as it is.
******************************************************************

7
LAB 2

LAB 2 : Image Processing Fundamentals

Lab Objectives
This objective of this lab is to understand
1. The effect of changing the number of gray levels on the quality of images.
2. The effect of changing spatial resolution on the quality of images, using two
methods:
3. Nearest neighbor interpolation.
4. Bilinear interpolation.

Changing the number of gray Levels


The quality of a gray-level image is significantly affected by its gray-level resolution. Other
words, increasing the number of bits per pixel has a great effect in improving the quality of gray-
level images. This is because that a higher number of gray levels would give a smooth transition
along the details of the image and hence improving its quality to the human eye.

Example :Changing the number of gray Levels


import cv2
import numpy as np
import [Link] as plt

def reduce_gray_levels(image_path, levels):


# Read the image in grayscale
img = [Link](image_path, cv2.IMREAD_GRAYSCALE)

# Compute the quantization step step =


256 // levels

# Reduce the number of gray levels


reduced_img = (img // step) * step

8
return reduced_img

# Load and process the image


image_path = "your_image.jpg" # Replace with your image path gray_levels = 8 #
Change this to set the desired number of gray levels output_img =
reduce_gray_levels(image_path, gray_levels)

# Display the original and reduced images


[Link](figsize=(10, 5))
[Link](1, 2, 1)
[Link]([Link](image_path, cv2.IMREAD_GRAYSCALE), cmap='gray') [Link]("Original
Image")
[Link]("off")

[Link](1, 2, 2) [Link](output_img,
cmap='gray')
[Link](f"Reduced to {gray_levels} Gray Levels") [Link]("off")

[Link]()

Changing the number of gray Levels


Changing the spatial resolution of a digital image, by zooming or shrinking, is an operation of
great importance in a wide range of applications (i.e. in digital cameras, biomedical image
9
processing and astronomical images). Simply, zooming and shrinking are the operations of
oversampling and undersampling a digital image, respectively. Zooming a digital image requires
two steps: the creation of new pixel locations, and assignment of gray levels to those new
locations. The assignment of gray levels to the new pixel locations is an operation of great
challenge. It can be performed using two approaches:

Nearest Neighbor Interpolation:


each pixel in the zoomed image is assigned the gray level value of its closest pixein the
original image.

Bilinear Interpolation:
the value of each pixel in the zoomed image is a weighted average of the gray level values
of the pixels in the nearest 2-by-2 neighborhood, in the original image.

Example : Reducing the Spatial Resolution


import cv2
import [Link] as plt

def reduce_spatial_resolution(image_path, scale_factor):


# Read the image in grayscale
img = [Link](image_path, cv2.IMREAD_GRAYSCALE)

# Get original dimensions


h, w = [Link]
# Compute new dimensions
new_h, new_w = int(h * scale_factor), int(w * scale_factor)

# Resize to lower resolution


low_res = [Link](img, (new_w, new_h), interpolation=cv2.INTER_AREA)
# Resize back to original size to see pixelation effect
restored = [Link](low_res, (w, h), interpolation=cv2.INTER_NEAREST)

10
return img, low_res, restored

# Load and process the image


image_path = "your_image.jpg" # Replace with your image path
scale_factor = 0.2

# Change this to control the resolution reduction (0.2 means 20% of the original size)
original, low_res, restored = reduce_spatial_resolution(image_path, scale_factor)

# Display images [Link](figsize=(12, 4))

[Link](1, 3, 1)
[Link](original, cmap='gray')
[Link]("Original Image")
[Link]("off")
[Link](1, 3, 2)
[Link](low_res, cmap='gray')
[Link](f"Low-Res Image
({int([Link][1]*scale_factor)}x{int([Link][0]*scale_factor)})") [Link]("off")
[Link](1, 3, 3)
[Link](restored, cmap='gray')
[Link]("Restored to Original Size (Pixelated)") [Link]("off")
[Link]()

11
Some Useful PYTHON Functions
 read_file
 write_file
 capitalize_each_word
 reverse_string
 remove_duplicates
 flatten_list
 is_prime
 factorial
 invert_dict
 merge_dicts
 get_current_time
 days_between
 random_number
 shuffle_list
 get_page_title
 list_files
 get_file_size
 read_json
 write_json
Task 1
Reducing the Number of Gray Levels in an Image :
Write a computer program capable of reducing the number of gray levels in a image from 256
to 2, in integer powers of 2. The desired number of gray levels needs to be a variable input to
your program.

Task 2
Zooming and Shrinking Images by Nearest Neighbour :
Write a computer program capable of zooming and shrinking an image by nearest neighbor
algorithm. Assume that the desired zoom/shrink factors are integers. You may ignore aliasing
effects.

Task 3
Zooming and Shrinking Images by Bilinear Interpolation
Write a computer program capable of zooming and shrinking an image by bilinear interpolation.
The input to your program is the desired size of the resulting image in the horizontal and vertical
direction. You may ignore aliasing effects.
12
LAB 3

LAB 3 : Point Processing Operations and Histogram Processing

Lab Objectives
This lab aims to introduce the concepts of point processing and histogram processing in digital
image processing, including:
1. Adjusting image brightness and contrast.
2. Understanding histogram equalization and matching.
3. Implementing these techniques using Python.

Point Processing Operations

Brightness Adjustment
Brightness adjustment involves increasing or decreasing the intensity values of all pixels in an
image.

Example Code

import cv2
import numpy as np
import [Link] as plt

# Read the image in grayscale


img = [Link]("[Link]", cv2.IMREAD_GRAYSCALE)

# Increase brightness
bright_img = [Link](img, 50)

# Decrease brightness
dark_img = [Link](img, 50)

# Display results
[Link](figsize=(12, 4))
[Link](1, 3, 1)

13
[Link](img, cmap='gray')
[Link]("Original Image")
[Link]("off")

[Link](1, 3, 2)
[Link](bright_img, cmap='gray')
[Link]("Brightened Image")
[Link]("off")

[Link](1, 3, 3)
[Link](dark_img, cmap='gray')
[Link]("Darkened Image")
[Link]("off")
[Link]()

Contrast Adjustment
Contrast adjustment involves scaling the intensity values to expand or compress the range of
intensities

Example Code

# Increase contrast
alpha = 1.5 # Contrast control (1.0-3.0)
beta = 0 # Brightness control (0-100)
contrasted_img = [Link](img, alpha=alpha, beta=beta)

# Display results
[Link](figsize=(10, 5))
[Link](1, 2, 1)
[Link](img, cmap='gray')
[Link]("Original Image")
[Link]("off")

[Link](1, 2, 2)
[Link](contrasted_img, cmap='gray')
[Link]("Contrast Enhanced Image")
[Link]("off")
[Link]()

14
Task 1
Write a Python program to:

1. Read a grayscale image.


2. Increase and decrease the brightness by 50 units.
3. Display the original and modified images

Task 2
Write a Python program to:

1. Read a grayscale image.


2. Increase the contrast by a factor of 1.5.
3. Display the original and contrast-enhanced images.

******************************************************************

15
LAB 4

LAB 4: The Histogram Processing

Lab Objectives
This lab aims to introduce the concepts of histogram processing in digital image processing,
including:

1. Understanding histogram equalization and matching.


2. Implementing these techniques using Python.

Histogram Processing

Histogram Equalization
Histogram equalization is a technique to improve image contrast by redistributing the
intensity values.

Example Code
# Apply histogram equalization
equalized = [Link](img)

# Display results
[Link](figsize=(10, 5))
[Link](1, 2, 1)
[Link](img, cmap='gray')
[Link]("Original Image")
[Link]("off")

[Link](1, 2, 2)
[Link](equalized, cmap='gray')
[Link]("Equalized Image")
[Link]("off")
[Link]()

16
Histogram Matching (Specification)
Histogram matching adjusts the histogram of an image to match a specified histogram.

Example Code
import cv2
import numpy as np
import [Link] as plt

# Read the source and reference images


source = [Link]("[Link]", cv2.IMREAD_GRAYSCALE)
reference = [Link]("[Link]", cv2.IMREAD_GRAYSCALE)

# Compute histograms
src_hist = [Link]([source], [0], None, [256], [0, 256])
ref_hist = [Link]([reference], [0], None, [256], [0, 256])

# Perform histogram matching


matched = [Link](source)

# Display results
[Link](figsize=(12, 4))
[Link](1, 3, 1)
[Link](source, cmap='gray')
[Link]("Source Image")
[Link]("off")

[Link](1, 3, 2)
[Link](reference, cmap='gray')
[Link]("Reference Image")
[Link]("off")

[Link](1, 3, 3)
[Link](matched, cmap='gray')
[Link]("Matched Image")
[Link]("off")
[Link]()

Task 1
Write a Python program to:

17
1. Read a grayscale image.
2. Apply histogram equalization.
3. Display the original and equalized images.
4. Plot the histograms of both images.

Task 2
Write a Python program to:

1. Read a source image and a reference image.


2. Perform histogram matching.
3. Display the source, reference, and matched images.
4. Plot the histograms of all three images.

******************************************************************

18
LAB 5

LAB 5: Intensity Transformations (part 1)

LAB OBJECTIVE:
The objective of this lab is to understand & implement

1 Image enhancement in spatial domain through Gray level Transformation function


2 Linear Transformation
 Image Negation function
 Identity function
3 Logarithmic Transformation
4 Power Law Transformation
5 Piece Wise Linear Transformation

BACKGROUND MATERIAL:

Image Enhancement in Spatial Domain -Basic Grey Level Transformations


Image enhancement is a very basic image processing task that defines us to have a better
subjective judgement over the images. And Image Enhancement in spatial domain (that is,
performing operations directly on pixel values) is the very simplistic approach. Enhanced images
provide better contrast of the details that images contain. Image enhancement is applied in
every field where images are ought to be understood and analysed. For example, Medical Image
Analysis, Analysis of images from satellites, etc.

Image enhancement simply means, transforming an image f into image g using T. Where T is
the transformation. The values of pixels in images f and g are denoted by r and s, respectively.
As
said, the pixel values r and s are related by the expression,

s = T(r)

where T is a transformation that maps a pixel value r into a pixel value s. The results of this
19
transformation are mapped into the grey sclale range as we are dealing here only with grey
scale
k
digital images. So, the results are mapped back into the range [0, L-1], where L=2 , k being the
number of bits in the image being considered. So, for instance, for an 8-bit image the range of
pixel values will be [0, 255].

There are three basic types of functions (transformations) that are used frequently in image
enhancement. They are,

 Linear,
 Logarithmic,
 Power-Law.

The transformation map plot shown below depicts various curves that fall into the above three
types of enhancement techniques.

Figure A: Plot of various transformation functions

The Identity and Negative curves fall under the category of linear functions. Identity curve
simply indicates that input image is equal to the output image. The Log and Inverse-Log curves
fall under the
category of Logarithmic functions and nth root and nth power transformations fall under the
category of Power-Law functions.

Image Negation

20
The negative of an image with grey levels in the range [0, L-1] is obtained by the negative
transformation shown in figure above, which is given by the expression,

s=L-1–r

This expression results in reversing of the grey level intensities of the image thereby producing
a negative like image. The output of this function can be directly mapped into the grey scale
look- up table consisting values from 0 to L-1.

TASK 1
Implement negation transform.

******************************************************************

21
LAB 6

LAB 6: Intensity Transformations (part 2)

LAB OBJECTIVE:
The objective of this lab is to understand & implement

1. Logarithmic Transformation
2. Power Law Transformation
3. Piece Wise Linear Transformation
Log Transformations
The log transformation curve shown in fig. A, is given by the expression,

s = c log(1 + r)

where c is a constant and it is assumed that r≥0. The shape of the log curve in fig. A tells that
this transformation maps a narrow range of low-level grey scale intensities into a wider range
of output values. And similarly maps the wide range of high-level grey scale intensities into a
narrow range of high level output values. The opposite of this applies for inverse-log transform.
This transform is used to expand values of dark pixels and compress values of bright pixels.

Power-Law Transformations
The nth power and nth root curves shown in fig. A can be given by the expression
s = cr γ

This transformation function is also called as gamma correction. For various values of γ
different levels of enhancements can be obtained. This technique is quite commonly called as
Gamma Correction. If you notice, different display monitors display images at different
intensities and clarity. That means, every monitor has built-in gamma correction in it with
certain gamma ranges and so a good monitor automatically corrects all the images displayed
on it for the best contrast to give user the best experience.

22
The difference between the log-transformation function and the power-law functions is that
using the power-law function a family of possible transformation curves can be obtained just
by varying the λ.

These are the three basic image enhancement functions for grey scale images that can be applied
easily for any type of image for better contrast and highlighting. Using the image negation
formula given above, it is not necessary for the results to be mapped into the grey scale range [0,
L-1]. Output of L-1-r automatically falls in the range of [0, L-1]. But for the Log and Power-Law
transformations resulting values are often quite distinctive, depending upon control parameters
like λ and logarithmic scales. So the results of these values should be mapped back to the grey
scale range to get a meaningful output image. For example, Log function s = c log(1 + r) results in
0 and 2.41 for r varying between 0 and 255, keeping c=1. So, the range [0, 2.41] should be mapped
to [0, L-1] for getting a meaningful image

Power Law Transform

PYTHON CODE
Import CV2
Import numpy as np
Import [Link] as plt
# Read the image
image = [Link]('[Link]', cv2.IMREAD_GRAYSCALE)

# Convert image to double (normalized between 0 and 1)


image_double = [Link](np.float32) / 255.0

# Get user input for c and gamma


c = float(input("Enter the value for c: "))
gamma = float(input("Enter the value for gamma: "))

# Apply gamma correction: imout = c * (image ^ gamma)


imout = c * [Link](image_double, gamma)

# Normalize to [0, 255] and convert back to uint8


imout = [Link](imout * 255, 0, 255).astype(np.uint8)

# Display images using Matplotlib


[Link](figsize=(10, 5))

23
[Link](1, 2, 1)
[Link](image, cmap='gray')
[Link]('Original Image')
[Link]('off')

[Link](1, 2, 2)
[Link](imout, cmap='gray')
[Link](f'Gamma Corrected (c={c}, γ={gamma})')
[Link]('off')

[Link]()

OUTPUT
Enter the value for c==>1 Enter the value for gamma==>.2 % for gamma value
less than 1 u gets Bright image

TASK 1
Implement Logarithmic transform.

TASK 2
Implement Piece wise linear transform.

24
LAB 7

LAB 7: Spatial Filtering

Lab Objective:
The Objective of this lab is to understand & implement

1) Smoothing Spatial Filters


2) Order Statistics Filters
a) Median
b) Max
c) Min

Smoothing Spatial Filters


Smoothing spatial filters are image processing techniques used to reduce noise and blur in an
image. They work by averaging the pixel values within a small region (a kernel or mask) around
each pixel, making the image smoother.

Order Statistics Filters


Order statistics filters are a type of non-linear spatial filter used in image processing. They work
by sorting pixel values in a given neighborhood and selecting a specific value based on ranking.

a) Median Filter

The Median Filter selects the middle value from the sorted neighborhood.

 Kernel Size: Typically 3x3, 5x5, or larger.


 Example:
o Neighborhood pixel values: [10, 20, 30, 40, 50, 60, 70, 80, 90]
o Sorted values: [10, 20, 30, 40, 50, 60, 70, 80, 90]
o Median value: 50

b) Max Filter

The Max Filter selects the highest (maximum) value from the neighborhood.

25
 Example:
o Neighborhood pixel values: [10, 20, 30, 40, 50, 60, 70, 80, 90]
o Maximum value: 90

c) Min Filter

The Min Filter selects the lowest (minimum) value from the neighborhood.

 Example:
o Neighborhood pixel values: [10, 20, 30, 40, 50, 60, 70, 80, 90]
o Minimum value: 10

Task 1:
Write a program to implement smoothing spatial filter and note the effects on given images.

import cv2
import numpy as np
import [Link] as plt
# Load the image
image = [Link]('[Link]')
image = [Link](image, cv2.COLOR_BGR2RGB) # Convert BGR to RGB for correct color
display
# Apply smoothing (Averaging Filter)
kernel_size = (5, 5) # Defines the filter size (3x3, 5x5, etc.)
smoothed_image = [Link](image, kernel_size)
# Display the images
[Link](figsize=(10,5))
[Link](1,2,1)
[Link](image)
[Link]("Original Image")
[Link]('off')
[Link](1,2,2)
[Link](smoothed_image)
[Link]("Smoothed Image (Blurred)")
[Link]('off')
[Link]()

Output:
26
Task 2:
Write a program to implement order statistics filters and write down your observations.
import cv2
import numpy as np
import [Link] as plt
import os

# Load the image


image_path = '[Link]'

image = [Link](image_path, cv2.IMREAD_GRAYSCALE) # Convert to grayscale


[Link][0] # This will raise an AttributeError if the image is None

# Apply Median Filter


median_filtered = [Link](image, 5)

# Apply Max Filter (Dilation)


kernel = [Link]((5, 5), np.uint8) # Define a 5x5 kernel

max_filtered = [Link](image, kernel)

# Apply Min Filter (Erosion)


min_filtered = [Link](image, kernel)

# Display the results


[Link](figsize=(10, 8))

27
[Link](2, 2, 1)
[Link](image, cmap='gray')
[Link]("Original Image")
[Link]('off')

[Link](2, 2, 2)
[Link](median_filtered, cmap='gray')
[Link]("Median Filter (Noise Removal)")
[Link]('off')

[Link](2, 2, 3)
[Link](max_filtered, cmap='gray')
[Link]("Max Filter (Brightening)")
[Link]('off')

[Link](2, 2, 4)
[Link](min_filtered, cmap='gray')
[Link]("Min Filter (Darkening)")
[Link]('off')

[Link]()

Output:

28
LAB 8

LAB 8: Spatial Features In Image Processing

Lab Objectives

 Understand different types of spatial features in images.


 Learn sharpening techniques for enhancing edges and fine details.
 Implement high-pass filtering, unsharp masking, and Laplacian methods.
 Understand the concept of convolution and kernels.

1. What Are Spatial Features?


Spatial features refer to the structure and patterns in an image, such as:

 Edges and Contours: Boundaries between regions, detected using filters like Sobel,
Canny, Laplacian.
 Textures: Variations in intensity, measured using Gabor filters, LBP, GLCM.
 Corners & Keypoints: Used in object tracking and matching (e.g., Harris, SIFT, ORB).
 Regions & Blobs: Groups of similar pixels via thresholding or segmentation.
 Geometric Shapes: Detected using Hough Transform.

2. Applications Of Spatial Features


 Edge Detection
 Texture Analysis
 Object Recognition
 Motion Tracking
 Image Segmentation

3. Sharpening Spatial Features


What is it?

Sharpening enhances image details by emphasizing edges and textures (high-frequency


components) while suppressing smooth areas (low-frequency components).

Key Concepts:
29
 Edge Enhancement – Accentuates transitions between regions.
 Contrast Boosting – Makes details stand out.
 Noise Sensitivity – Sharpening can amplify noise; apply cautiously.

4. Methods For Sharpening


(a) High-Pass Filtering

 Retains high-frequency (edges, details), removes low-frequency.


 Uses convolution with a kernel like:

0 -1 0
-1 4 -1
0 -1 0

Python Example:
import cv2
import numpy as np
import [Link] as plt

# Read grayscale image


img = [Link]('[Link]', 0)

# Define high-pass filter kernel (Laplacian)


kernel = [Link]([[0, -1, 0],
[-1, 4, -1],
[0, -1, 0]])

# Apply filter
sharpened = cv2.filter2D(img, -1, kernel)

# Display
[Link](1,2,1)
[Link](img, cmap='gray')
[Link]("Original")

[Link](1,2,2)
[Link](sharpened, cmap='gray')
[Link]("High-Pass Sharpened")
[Link]()

30
(b) Unsharp Masking (USM)

Formula:
Sharpened = Original + k × (Original − Blurred)

Python Example:
blurred = [Link](img, (5, 5), 0)
sharpened = [Link](img, 1.5, blurred, -0.5, 0)

[Link](sharpened, cmap='gray')
[Link]("Unsharp Masking")
[Link]()

(c) Laplacian Sharpening

Uses the Laplacian operator to highlight areas of rapid intensity change.

laplacian = [Link](img, cv2.CV_64F)


sharpened = img - laplacian

[Link](sharpened, cmap='gray')
[Link]("Laplacian Sharpening")
[Link]()

(d) High-Boost Filtering

More aggressive sharpening than USM.

Formula:
Sharpened = A × Original − Blurred, where A > 1

5. Understanding Convolution And Kernels


A kernel (filter or mask) is a matrix applied to an image using convolution.

Convolution slides the kernel over the image, calculating a weighted sum of pixel values:

Mathematically:
If I(x, y) is the image, K(i, j) is the kernel:
G(x, y) = Σ Σ I(x+i, y+j) × K(i, j)
31
This operation enhances certain features like edges or blurs.

TASK 1

Write Python code to:

1. Load a grayscale image.


2. Apply and display High-Pass filtering.
3. Apply and display Laplacian Sharpening

TASK 2

Implement Unsharp Masking:

1. Blur the original image.


2. Create the sharpened version.
3. Display all three (original, blurred, sharpened).

******************************************************************

32
LAB 9

LAB 9: Morphological Operations


Lab Objectives
The objectives of this lab are to understand:

1. What morphological operations are in image processing.


2. How to perform:
o Dilation
o Erosion
o Opening
o Closing
3. Application of structuring elements.
4. Use of morphological operations for noise removal and structure enhancement.

1. Dilation
What is it?

Dilation causes white (foreground) areas in a binary image to grow.

Why use it?

 To fill small holes


 To connect broken parts of objects
 To make objects thicker

Mathematical Representation

A ⊕ B = { z | (B)z ∩ A ≠ ∅ }

Where:

 A = Input image
 B = Structuring element
 z = Position of B over image

Python Code Example


33
import cv2
import numpy as np
import [Link] as plt

# Load binary image


img = [Link]('binary_image.png', 0)

# Define kernel
kernel = [Link]((3, 3), np.uint8)

# Apply dilation
dilated = [Link](img, kernel, iterations=1)

# Display images
[Link](1, 2, 1)
[Link](img, cmap='gray')
[Link]("Original")

[Link](1, 2, 2)
[Link](dilated, cmap='gray')
[Link]("Dilated")

[Link]()

2. Erosion
What is it?

Erosion causes white areas in a binary image to shrink.

Why use it?

 To remove white noise


 To separate connected objects
 To make objects thinner

Mathematical Representation

A ⊖ B = { z | (B)z ⊆ A }

Python Code Example


34
# Apply erosion
eroded = [Link](img, kernel, iterations=1)

# Display images
[Link](1, 2, 1)
[Link](img, cmap='gray')
[Link]("Original")

[Link](1, 2, 2)
[Link](eroded, cmap='gray')
[Link]("Eroded")
[Link]()

3. Opening
What is it?
Opening is erosion followed by dilation.

Why use it?


 To remove small white noise
 To smooth object contours

Mathematical Representation
A ∘ B = (A ⊖ B) ⊕ B

Python Code Example


# Apply opening
opening = [Link](img, cv2.MORPH_OPEN, kernel)

# Display
[Link](1, 2, 1)
[Link](img, cmap='gray')
[Link]("Original")

[Link](1, 2, 2)
[Link](opening, cmap='gray')
[Link]("Opening")
[Link]()

35
4. Closing
What is it?
Closing is dilation followed by erosion.

Why use it?


 To fill black holes
 To connect small gaps

Mathematical Representation

A • B = (A ⊕ B) ⊖ B

Python Code Example


# Apply closing
closing = [Link](img, cv2.MORPH_CLOSE, kernel)

# Display
[Link](1, 2, 1)
[Link](img, cmap='gray')
[Link]("Original")

[Link](1, 2, 2)
[Link](closing, cmap='gray')
[Link]("Closing")
[Link]()
TASK 1
Write a Python program that:

1. Reads a binary image.


2. Applies Dilation and displays the result.
3. Applies Erosion and displays the result.

TASK 2
Write a Python code to:

1. Read a binary image.


2. Apply Opening and Closing operations.

3. Display all results (original, opened, closed) side by side.


36
LAB 10

LAB 10: Edge Detection

LAB OBJECTIVE:
1. To understand the concept of edge detection in digital image processing.
2. To implement and compare different edge detection techniques (Sobel,
Prewitt, and Canny).
3. To analyze the effectiveness of each method in detecting edges in an image.
4. To develop practical skills in using OpenCV for edge detection.

Introduction:
Edge detection is a crucial step in image processing used to identify object boundaries. It
highlights the sharp intensity changes in an image, which usually correspond to object
edges.
Sobel Edge Detection:
 Sobel operator applies two 3x3 convolution kernels (one for horizontal
changes and another for vertical changes).
 It enhances edges by computing the gradient magnitude.
Prewitt Edge Detection:
 Similar to Sobel, but uses a different kernel to approximate the derivatives.
 Less sensitive to noise compared to Sobel but produces slightly weaker edges.
Canny Edge Detection:
 A multi-stage algorithm involving Gaussian filtering, gradient computation, non-
maximum suppression, and edge tracking using hysteresis.
 Produces highly accurate edges and reduces noise significantly.

Implementation in Python:
Required Libraries:
import cv2
import numpy as np
import [Link] as plt
37
Step 1: Load and Convert Image to Grayscale
image = [Link]('[Link]', cv2.IMREAD_GRAYSCALE)
[Link](figsize=(6,6))
[Link](image, cmap='gray')
[Link]('Original Image')
[Link]('off')
[Link]()

Step 2: Apply Sobel Edge Detection


sobel_x = [Link](image, cv2.CV_64F, 1, 0, ksize=3)
sobel_y = [Link](image, cv2.CV_64F, 0, 1, ksize=3)
sobel_combined = [Link](sobel_x, sobel_y)

[Link](figsize=(12,4))
[Link](1,3,1)
[Link](sobel_x, cmap='gray')
[Link]('Sobel X') [Link](1,3,2)
[Link](sobel_y, cmap='gray')
[Link]('Sobel Y') [Link](1,3,3)
[Link](sobel_combined, cmap='gray')
[Link]('Sobel Combined')
[Link]()

Step 3: Apply Prewitt Edge Detection


prewitt_x = cv2.filter2D(image, -1, [Link]([[-1,0,1],[-1,0,1],[-1,0,1]]))
prewitt_y = cv2.filter2D(image, -1
[Link]([[-1,-1,-1],[0,0,0],[1,1,1]])) prewitt_combined = [Link](prewitt_x, prewitt_y)

[Link](figsize=(12,4))
[Link](1,3,1)
[Link](prewitt_x, cmap='gray')
[Link]('Prewitt X') [Link](1,3,2)
[Link](prewitt_y, cmap='gray')
[Link]('Prewitt Y') [Link](1,3,3)
[Link](prewitt_combined, cmap='gray')
[Link]('Prewitt Combined')
[Link]()

Step 4: Apply Canny Edge Detection


38
canny_edges = [Link](image, 100, 200)

[Link](figsize=(6,6))
[Link](canny_edges, cmap='gray')
[Link]('Canny Edge Detection')
[Link]('off')
[Link]()
How Image Edge Detection Works?

The image shows three different grayscale images processed with edge detection techniques.
 Left Column: Original grayscale images (flower, car, baboon).
 Middle Column: Edge detection using the Prewitt operator, which
highlights edges using simple gradient calculations.
 Right Column: Edge detection using the Canny operator, which provides more
refined edges by applying noise reduction, gradient calculation, and edge tracking.

39
LAB 11

LAB 11: Fourier and Cosine Transforms in Image Processing


Lab Objectives
 Understand the role of the Fourier Transform in frequency analysis of images.
 Learn how to visualize and manipulate frequency components.
 Apply FFT for image filtering in Python.

1. Fourier Transform In Image Processing


What is Fourier Transform?

The Fourier Transform converts a spatial domain image into its frequency domain
representation, where:

 Low frequencies represent smooth regions.


 High frequencies represent edges and details.

Why Use It?


 Analyze periodic patterns.
 Filter specific frequency ranges.
 Enhance or suppress image details.

Mathematical Formula

For 2D Discrete Fourier Transform:

Where:

 f(x,y)f(x, y) is the input image


 F(u,v)F(u, v) is the frequency-domain output

40
Python Example: Fourier Transform
import cv2
import numpy as np
import [Link] as plt

# Load grayscale image


img = [Link]('[Link]', 0)

# Compute FFT and shift


f = [Link].fft2(img)
fshift = [Link](f)

# Get magnitude spectrum


magnitude_spectrum = 20 * [Link]([Link](fshift))

# Display
[Link](1, 2, 1)
[Link](img, cmap='gray')
[Link]("Original")

[Link](1, 2, 2)
[Link](magnitude_spectrum, cmap='gray')
[Link]("Magnitude Spectrum")
[Link]()

2. Discrete Cosine Transform (Dct)


What is DCT?
The Discrete Cosine Transform expresses an image as a sum of cosine functions oscillating at different
frequencies. It is widely used in compression algorithms like JPEG.

Why Use DCT?


 Energy compaction: Most important info is concentrated in a few coefficients.
 Excellent for image compression and noise reduction.

Mathematical Formula

41
Python Example: DCT and Inverse DCT
import cv2
import numpy as np
import [Link] as plt

# Load grayscale image


img = [Link]('[Link]', 0)
img = np.float32(img) / 255.0

# Apply DCT
dct = [Link](img)

# Apply inverse DCT


idct = [Link](dct)

# Display
[Link](1, 3, 1)
[Link](img, cmap='gray')
[Link]("Original")

[Link](1, 3, 2)
[Link]([Link](abs(dct)), cmap='gray')
[Link]("DCT")
[Link](1, 3, 3)
[Link](idct, cmap='gray')
[Link]("Reconstructed")
[Link]()

TASK 1
Write Python code to:

1. Load a grayscale image.


2. Apply Fourier Transform.
3. Display the original and magnitude spectrum side-by-side.

TASK 2
Implement DCT and IDCT:

1. Convert the image to float.


2. Apply DCT and then inverse DCT.
3. Display the original, DCT spectrum, and reconstructed image.
42
LAB 12

LAB 12: Image Compression

1. Image Compression Basics

Lab Objectives
 Understand the need for image compression.
 Learn the difference between lossless and lossy compression techniques.
 Explore basic implementations in Python using standard libraries.
 Evaluate the effect of compression on image quality and size.

What is Image Compression?


Image compression is the process of reducing the size of an image file without excessively
degrading its quality. It is done to:

 Save storage space


 Speed up transmission
 Optimize performance for web and mobile devices

2. Types Of Image Compression

A. Lossless Compression
Definition:

Compresses image data without any loss of information. The original image can be perfectly
reconstructed from the compressed version.

Examples:

 PNG
 BMP
 TIFF (uncompressed)
 ZIP

43
Common Techniques:

 Run-Length Encoding (RLE)


 Huffman Coding
 Lempel-Ziv-Welch (LZW)

Python Example (Saving as PNG)


import cv2

# Load image
img = [Link]('[Link]')

# Save with lossless compression


[Link]('lossless_output.png', img, [cv2.IMWRITE_PNG_COMPRESSION, 9])

B. Lossy Compression
Definition:
Compresses image data by removing less important information. Some quality is lost, and it may
not be recoverable.

Examples:
 JPEG
 WebP (configurable for lossy/lossless)

Common Techniques:

 Transform coding (e.g., DCT in JPEG)


 Quantization
 Entropy encoding

Python Example (Saving as JPEG)


# Save with lossy compression (JPEG)
[Link]('lossy_output.jpg', img, [cv2.IMWRITE_JPEG_QUALITY, 50])

Note: JPEG quality ranges from 0 (worst) to 100 (best). Lower quality → higher compression.

44
3. COMPARISON TABLE
Feature Lossless Compression Lossy Compression
Quality Perfect Slightly to highly degraded
File Size Larger Smaller
Use Cases Medical, Legal Docs Web images, Photography
Reversible Yes No

TASK 1
Write Python code to:

1. Load an image.
2. Compress and save it using lossless PNG.
3. Display original and compressed image.
4. Compare file sizes.

TASK 2

Repeat the above using lossy JPEG compression at quality levels 90, 50, and 20.

1. Compare the file sizes and image quality.


2. Display all versions side-by-side.

******************************************************************

45
LAB 13

LAB 13: Color Models and Color Transformations

1. Color Models In Image Processing


Lab Objectives

 Understand different color models used in digital imaging.


 Learn to convert between RGB, HSV, and YCbCr color spaces.
 Perform color transformations using OpenCV in Python.

What is a Color Model?

A color model is a mathematical representation of colors in a format that makes them easier to
manipulate and interpret in digital systems.

Common Color Models


1. RGB (Red, Green, Blue)

 The most basic and widely used model.


 Additive color model (used in screens).
 Each pixel has R, G, and B values (0–255).

2. HSV (Hue, Saturation, Value)

 Represents colors more like humans perceive.


 Hue: color type (0–179 in OpenCV)
 Saturation: vibrancy (0–255)
 Value: brightness (0–255)

3. YCbCr

 Luminance (Y) and Chrominance (Cb, Cr)


 Used in video compression (JPEG, MPEG)

2. Color Transformations
What Are They?
46
Color transformations involve converting an image from one color space to another to enhance,
analyze, or segment color features.

Python Example: Color Space Conversion


import cv2
import [Link] as plt

# Load image in RGB


img = [Link]('[Link]')
img_rgb = [Link](img, cv2.COLOR_BGR2RGB)

# Convert to HSV
img_hsv = [Link](img, cv2.COLOR_BGR2HSV)

# Convert to YCbCr
img_ycbcr = [Link](img, cv2.COLOR_BGR2YCrCb)

# Display images
titles = ['RGB', 'HSV', 'YCbCr']
images = [img_rgb, img_hsv, img_ycbcr]

for i in range(3):
[Link](1, 3, i+1)
[Link](images[i])
[Link](titles[i])
[Link]('off')
[Link]()

3. When To Use Which Model?


Model Used For
RGB Display and general imaging
HSV Color segmentation and filtering
YCbCr Compression and broadcast

TASK 1
Write Python code to:

1. Load a color image.


2. Convert and display it in HSV and YCbCr color spaces.
3. Display all models (RGB, HSV, YCbCr) in one window.
47
LAB 14

LAB 14: Practical Applications and Projects

1. Introduction To Medical Image Processing


Lab Objectives

 Understand the significance of image processing in the medical field.


 Learn to read, enhance, and analyze medical images using Python.
 Apply basic techniques to medical images such as X-rays, MRIs, and CT scans.

What is Medical Image Processing?


Medical Image Processing involves the application of image processing techniques to enhance,
analyze, and extract useful information from medical images like:

 X-rays
 MRI scans
 CT scans
 Ultrasound images

This enables better diagnosis, treatment planning, and research.

Applications

 Tumor detection
 Bone fracture analysis
 Blood vessel segmentation
 Brain image analysis (MRI)
 Organ segmentation and measurement

2. Basic Operations In Python


Reading and Displaying a Medical Image
import cv2
import [Link] as plt

# Read grayscale medical image (e.g., MRI)


48
img = [Link]('mri_scan.png', 0)

# Display
[Link](img, cmap='gray')
[Link]('Original Medical Image')
[Link]('off')
[Link]()

Applying Contrast Enhancement


# Histogram Equalization to enhance contrast
equalized = [Link](img)

# Display both
[Link](1, 2, 1)
[Link](img, cmap='gray')
[Link]("Original")

[Link](1, 2, 2)
[Link](equalized, cmap='gray')
[Link]("Contrast Enhanced")

[Link]()

Noise Removal Using Gaussian Blur


# Apply Gaussian Blur
blurred = [Link](img, (5, 5), 0)

[Link](blurred, cmap='gray')
[Link]('Blurred Image (Noise Removed)')
[Link]('off')
[Link]()

Edge Detection (Tumor/Structure Highlighting)


edges = [Link](img, 100, 200)

[Link](edges, cmap='gray')
[Link]('Edge Detection')
[Link]('off')
[Link]()
49
3. Tasks
TASK 1

Load a medical image (X-ray/MRI/CT).


Apply histogram equalization and Gaussian blur, and display the results.

TASK 2

Use Canny Edge Detection to highlight major structures or possible regions of interest.

4. Optional Extension
Explore pydicom to load DICOM (.dcm) format images:

import pydicom
import [Link] as plt

# Load DICOM file


ds = [Link]('[Link]')
[Link](ds.pixel_array, cmap='gray')
[Link]("DICOM Image")
[Link]('off')
[Link]()

******************************************************************

50
LAB 15

LAB 15: Practical Applications and Projects


Object Detection Using R-CNN in PyTorch
1. Introduction To R-Cnn
Lab Objectives

 Understand what R-CNN is.


 Learn how R-CNN works for object detection.
 Implement R-CNN using PyTorch and detect objects in images.

What is R-CNN?

R-CNN (Region-based Convolutional Neural Network) is a deep learning model used for object
detection in images. Instead of scanning the entire image pixel by pixel, it:

 Proposes regions where objects may exist.


 Extracts features using a CNN.
 Classifies objects using SVM.
 Refines bounding boxes using regression.

How R-CNN Works

1. Region Proposal: Select regions likely to contain objects (Selective Search).


2. Feature Extraction: Use CNN to extract features from each region.
3. Classification: Classify each region using an SVM.
4. Bounding Box Regression: Adjust the box to more accurately surround the object.

Architecture of R-CNN

Insert the R-CNN diagram here (or draw it on paper and paste in your final report).

2. Implementation Using Pytorch

Task 1: Load and Detect Objects in an Image

51
Code
import torch
import torchvision
import cv2
import numpy as np
import [Link] as plt

# Load Faster R-CNN model


model = [Link].fasterrcnn_resnet50_fpn(pretrained=True)
[Link]()

# Load an image
image_path = "[Link]"
image = [Link](image_path)

# Convert image to tensor


image_tensor = [Link]()(image)

# Get predictions
with torch.no_grad():
predictions = model([image_tensor])

# Extract bounding boxes and scores


boxes = predictions[0]['boxes'].numpy()
scores = predictions[0]['scores'].numpy()

# Set confidence threshold


threshold = 0.8

# Draw bounding boxes


for i, box in enumerate(boxes):
if scores[i] > threshold:
x1, y1, x2, y2 = map(int, box)
[Link](image, (x1, y1), (x2, y2), (0, 255, 0), 2)

# Show result
[Link]([Link](image, cv2.COLOR_BGR2RGB))
[Link]("Detected Objects")
[Link]('off')
[Link]()

52
Output

A sample output image with bounding boxes should be added here.

Task 2: Detect and Count Specific Object Classes


Code
COCO_LABELS = [
"N/A", "person", "bicycle", "car", "motorcycle", "airplane", "bus",
"train", "truck", "boat", "traffic light", "fire hydrant", "N/A", "stop sign",
"parking meter", "bench", "bird", "cat", "dog", "horse", "sheep", "cow",
"elephant", "bear", "zebra", "giraffe", "N/A", "N/A", "sports ball", "kite",
"baseball bat", "baseball glove", "skateboard", "surfboard", "tennis racket",
"bottle", "N/A", "wine glass"
]

labels = predictions[0]['labels'].numpy()

# Draw and count specific objects


for i, box in enumerate(boxes):
if scores[i] > threshold:
x1, y1, x2, y2 = map(int, box)
label_name = COCO_LABELS[labels[i]]
[Link](image, (x1, y1), (x2, y2), (0, 255, 0), 2)
[Link](image, label_name, (x1, y1 - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 255, 0), 2)

# Show result
[Link](figsize=(8, 6))
[Link]([Link](image, cv2.COLOR_BGR2RGB))
[Link]("Detected Classes with Labels")
[Link]('off')
[Link]()

Output

A final image showing labeled detected object

******************************************************************

53

You might also like