Image Processing-Lab (Course Content)
Image Processing-Lab (Course Content)
3
LAB 1
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
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
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
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.
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 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.
8
return reduced_img
[Link](1, 2, 2) [Link](output_img,
cmap='gray')
[Link](f"Reduced to {gray_levels} Gray Levels") [Link]("off")
[Link]()
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.
10
return img, low_res, restored
# 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)
[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 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.
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
# 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:
Task 2
Write a Python program to:
******************************************************************
15
LAB 4
Lab Objectives
This lab aims to introduce the concepts of histogram processing in digital image processing,
including:
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
# Compute histograms
src_hist = [Link]([source], [0], None, [256], [0, 256])
ref_hist = [Link]([reference], [0], None, [256], [0, 256])
# 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:
******************************************************************
18
LAB 5
LAB OBJECTIVE:
The objective of this lab is to understand & implement
BACKGROUND MATERIAL:
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.
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 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
PYTHON CODE
Import CV2
Import numpy as np
Import [Link] as plt
# Read the image
image = [Link]('[Link]', cv2.IMREAD_GRAYSCALE)
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 Objective:
The Objective of this lab is to understand & implement
a) Median Filter
The Median Filter selects the middle value from the sorted neighborhood.
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
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 Objectives
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.
Key Concepts:
29
Edge Enhancement – Accentuates transitions between regions.
Contrast Boosting – Makes details stand out.
Noise Sensitivity – Sharpening can amplify noise; apply cautiously.
0 -1 0
-1 4 -1
0 -1 0
Python Example:
import cv2
import numpy as np
import [Link] as plt
# 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]()
[Link](sharpened, cmap='gray')
[Link]("Laplacian Sharpening")
[Link]()
Formula:
Sharpened = A × Original − Blurred, where A > 1
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
TASK 2
******************************************************************
32
LAB 9
1. Dilation
What is it?
Mathematical Representation
A ⊕ B = { z | (B)z ∩ A ≠ ∅ }
Where:
A = Input image
B = Structuring element
z = Position of B over image
# 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?
Mathematical Representation
A ⊖ B = { z | (B)z ⊆ A }
# 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.
Mathematical Representation
A ∘ B = (A ⊖ B) ⊕ B
# 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.
Mathematical Representation
A • B = (A ⊕ B) ⊖ B
# 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:
TASK 2
Write a Python code to:
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]()
[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]()
[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]()
[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
The Fourier Transform converts a spatial domain image into its frequency domain
representation, where:
Mathematical Formula
Where:
40
Python Example: Fourier Transform
import cv2
import numpy as np
import [Link] as plt
# Display
[Link](1, 2, 1)
[Link](img, cmap='gray')
[Link]("Original")
[Link](1, 2, 2)
[Link](magnitude_spectrum, cmap='gray')
[Link]("Magnitude Spectrum")
[Link]()
Mathematical Formula
41
Python Example: DCT and Inverse DCT
import cv2
import numpy as np
import [Link] as plt
# Apply DCT
dct = [Link](img)
# 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:
TASK 2
Implement DCT and IDCT:
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.
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:
# Load image
img = [Link]('[Link]')
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:
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.
******************************************************************
45
LAB 13
A color model is a mathematical representation of colors in a format that makes them easier to
manipulate and interpret in digital systems.
3. YCbCr
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.
# 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]()
TASK 1
Write Python code to:
X-rays
MRI scans
CT scans
Ultrasound images
Applications
Tumor detection
Bone fracture analysis
Blood vessel segmentation
Brain image analysis (MRI)
Organ segmentation and measurement
# Display
[Link](img, cmap='gray')
[Link]('Original Medical Image')
[Link]('off')
[Link]()
# Display both
[Link](1, 2, 1)
[Link](img, cmap='gray')
[Link]("Original")
[Link](1, 2, 2)
[Link](equalized, cmap='gray')
[Link]("Contrast Enhanced")
[Link]()
[Link](blurred, cmap='gray')
[Link]('Blurred Image (Noise Removed)')
[Link]('off')
[Link]()
[Link](edges, cmap='gray')
[Link]('Edge Detection')
[Link]('off')
[Link]()
49
3. Tasks
TASK 1
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
******************************************************************
50
LAB 15
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:
Architecture of R-CNN
Insert the R-CNN diagram here (or draw it on paper and paste in your final report).
51
Code
import torch
import torchvision
import cv2
import numpy as np
import [Link] as plt
# Load an image
image_path = "[Link]"
image = [Link](image_path)
# Get predictions
with torch.no_grad():
predictions = model([image_tensor])
# Show result
[Link]([Link](image, cv2.COLOR_BGR2RGB))
[Link]("Detected Objects")
[Link]('off')
[Link]()
52
Output
labels = predictions[0]['labels'].numpy()
# Show result
[Link](figsize=(8, 6))
[Link]([Link](image, cv2.COLOR_BGR2RGB))
[Link]("Detected Classes with Labels")
[Link]('off')
[Link]()
Output
******************************************************************
53