0% found this document useful (0 votes)
0 views33 pages

Updated Lab Manual 9 DIP

The document is a lab manual for Digital Image Processing at the University of Engineering and Technology, Taxila, focusing on implementing image processing techniques using Python and OpenCV. It includes setup instructions for Python and VS Code, installation of OpenCV, and various image processing operations such as resizing, rotation, and data augmentation. The manual provides Python code examples for practical implementation of these techniques.

Uploaded by

Basat Maqsood
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)
0 views33 pages

Updated Lab Manual 9 DIP

The document is a lab manual for Digital Image Processing at the University of Engineering and Technology, Taxila, focusing on implementing image processing techniques using Python and OpenCV. It includes setup instructions for Python and VS Code, installation of OpenCV, and various image processing operations such as resizing, rotation, and data augmentation. The manual provides Python code examples for practical implementation of these techniques.

Uploaded by

Basat Maqsood
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
You are on page 1/ 33

UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA

FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

DIGITAL IMAGE PROCESSING

LAB MANUAL 9
Implementation of Image Processing techniques in Python

1. Getting Started with Python in VS Code


2. installing OpenCV for Visual Studio Code and Python
3. Image Processing in Python
4. Image Processing Using OpenCV

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

LAB OBJECTIVE:

The objective of this lab is to understand & implement Image Processing techniques in Python

 Getting Started with Python in VS Code

 installing OpenCV for Visual Studio Code and Python

 Image Processing in Python

 Image Processing Using OpenCV

1. Getting Started with Python in VS Code


First set up your Python development environment. Specifically, this requires installing:

 Python 3
 VS Code
 VS Code Python extension

Install a Python interpreter


Along with the Python extension, you need to install a Python interpreter. Which interpreter you
use is dependent on your specific needs, but some guidance is provided below.

Windows
Install Python from python.org. Use the Download Python button that appears first on the page to
download the latest version.

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Note:
To verify that you've installed Python successfully on your machine, run one of the following
commands (depending on your operating system):

 Windows: open a command prompt and run the following command:

py -3 --versionCopy

 If the installation was successful, the output window should show the version of Python that
you installed. Alternatively, you can use the py -0 command in the VS Code integrated
terminal to view the versions of python installed on your machine.

Start VS Code in a workspace folder


 By starting VS Code in a folder, that folder becomes your "workspace".

 Using a command prompt or terminal, create an empty folder called "hello", navigate into it,

and open VS Code (code) in that folder (.) by entering the following commands:

mkdir hellocd hellocode .Copy

Note:

 Alternately, you can create a folder through the operating system UI, then use VS Code's File >

Open Folder to open the project folder.

Create a virtual environment


 A best practice among Python developers is to use a project-specific virtual environment.

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

 Once you activate that environment, any packages you then install are isolated from other

environments, including the global interpreter environment, reducing many complications that

can arise from conflicting package versions.

 You can create non-global environments in VS Code using Venv or Anaconda with Python:

Create Environment.

 Open the Command Palette (Ctrl+Shift+P), start typing the Python: Create

Environment command to search, and then select the command.

 The command presents a list of environment types, Venv or Conda. For this example,

select Venv.

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

2. Installing OpenCV for Visual Studio Code and Python


 OpenCV is a powerful computer vision library widely used for image and video processing
tasks.

 Integrating OpenCV with Visual Studio Code (VS Code) allows developers to leverage their
capabilities within a familiar development environment.

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Steps to Install OpenCV for Visual Studio Code and Python

Below are some of the steps by which we can install OpenCV for Visual Studio Code

and Python:

1. Install Visual Studio Code

2. Install OpenCV Using pip

Open your terminal or command prompt and install OpenCV using pip, the Python
package manager:

pip install opencv-python

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Image Processing in Python


Image processing in Python is a rapidly growing field with a wide range of applications. It is used

in a variety of industries, including Computer vision, medical imaging, security, etc.

Image Processing Using OpenCV


 OpenCV (Open Source Computer Vision) is a powerful and widely-used library for image

processing and computer vision tasks.

 It provides a comprehensive set of functions and tools that facilitate the development of

applications dealing with images and videos.

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

 While taking photographs is as simple as pressing a button, processing and improving those

images sometimes takes more than a few lines of code.

 That’s where image processing libraries like OpenCV come into play.

 OpenCV is a popular open-source package that covers a wide range of image processing and

computer vision capabilities and methods.

 It supports multiple programming languages including Python, C++, and Java.

 OpenCV is highly tuned for real-time applications and has a wide range of capabilities.

Data Augmentation

 Data augmentation is the process of copying the original dataset with some slight

modifications to the original data, increasing the number of training samples to the dataset for

the model to train efficiently.

 We can improve the model's performance by slightly changing the dataset and introducing

more training samples.

 Data Augmentation for Image has:

 Random Rotation

 Random Flip

 Random Zoom

 Cropping and Resizing

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

 These techniques will improve the training samples for the model to train efficiently.

Image Processing with Python


We will make the following operations most commonly uses for data augmentation task which

training the model in computer Vision.

 Image Resizing

 Image Rotation

 Image Translation

 Image Normalization

 Edge detection of Image

 Image Blurring

 Morphological Image Processing

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Image Re-sizing using Open-CV in Python


 Scaling operations increase or reduce the size of an image.

 The cv2.resize() function is used to resize an python image in OpenCV.

 It takes the following arguments:

Python implementation in VS-Code


# Import the necessary libraries
import cv2 # OpenCV for image processing
import numpy as np # NumPy for numerical operations
import matplotlib.pyplot as plt # Matplotlib for displaying images

# Load the image from the file


image = cv2.imread('1.jpg')

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

# Check if the image is loaded successfully


if image is None:
print("Error: Image not found. Check the file path.")
exit()

# Convert the image from BGR (OpenCV default) to RGB (for proper color display
in Matplotlib)
image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Define scale factors for resizing


scale_factor_1 = 3.0 # Increase the size by 3 times
scale_factor_2 = 1 / 3.0 # Decrease the size by 3 times

# Get the original image dimensions (height and width, ignoring the third
dimension, which is color)
height, width = image_rgb.shape[:2]

# Calculate new dimensions for zoomed (enlarged) image


new_height = int(height * scale_factor_1)
new_width = int(width * scale_factor_1)

# Resize the image (Zoomed-in version) using cubic interpolation for better
quality
zoomed_image = cv2.resize(
src=image_rgb,
dsize=(new_width, new_height),
interpolation=cv2.INTER_CUBIC # INTER_CUBIC provides smooth scaling for
enlargement
)

# Calculate new dimensions for scaled-down image


Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

new_height1 = int(height * scale_factor_2)


new_width1 = int(width * scale_factor_2)

# Ensure new dimensions are not zero


new_height1 = max(1, new_height1)
new_width1 = max(1, new_width1)

# Resize the image (Scaled-down version) using INTER_AREA for better quality
when shrinking
scaled_image = cv2.resize(
src=image_rgb,
dsize=(new_width1, new_height1),
interpolation=cv2.INTER_AREA # INTER_AREA is recommended for downscaling
)

# Create a figure with 1 row and 3 columns to display images side by side
fig, axs = plt.subplots(1, 3, figsize=(12, 5))

# Display the original image


axs[0].imshow(image_rgb)
axs[0].set_title(f'Original Image Shape: {image_rgb.shape}')

# Display the zoomed-in image


axs[1].imshow(zoomed_image)
axs[1].set_title(f'Zoomed Image Shape: {zoomed_image.shape}')

# Display the scaled-down image


axs[2].imshow(scaled_image)
axs[2].set_title(f'Scaled Image Shape: {scaled_image.shape}')

# Remove axis ticks (numbers) from all images for a cleaner display
Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

for ax in axs:
ax.set_xticks([])
ax.set_yticks([])

# Adjust layout to prevent overlapping of titles


plt.tight_layout()

# Show the images


plt.show()

Output:

Python Image Rotation


 Images can be rotated to any degree clockwise or otherwise.

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

 We just need to define rotation matrix listing rotation point, degree of rotation and the

scaling factor.

 The cv2.getRotationMatrix2D() function is used to create a rotation matrix for an image. It

takes the following arguments:

 The center of rotation for the image.

 The angle of rotation in degrees.

 The scale factor.

 The cv2.warpAffine() function is used to apply a transformation matrix to an image. It takes

the following arguments:

 The python image to be transformed.

 The transformation matrix.

 The output image size.

 The rotation angle can be positive or negative. A positive angle rotates the image

clockwise, while a negative angle rotates the image counterclockwise.

 The scale factor can be used to scale the image up or down. A scale factor of 1 will keep

the image the same size, while a scale factor of 2 will double the size of the python image.

Python Implementaion in VSCode

# Import the necessary Libraries


import cv2
import matplotlib.pyplot as plt

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

# Read image from disk.


img = cv2.imread('1.jpg')

# Convert BGR image to RGB


image_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Image rotation parameter


# Image_rgb.shape[1] → Width of the image (X-axis).
# Image_rgb.shape[0] → Height of the image (Y-axis).
# 2 → Integer division to get the center point.

center = (image_rgb.shape[1] // 2, image_rgb.shape[0] // 2)


angle = 30
scale = 1

# getRotationMatrix2D creates a matrix needed for transformation.


rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale)

# We want matrix for rotation w.r.t center to 30 degree without scaling.


#img.shape[1] (width) and img.shape[0] (height) to define the output
size of the rotated image.
rotated_image = cv2.warpAffine(image_rgb, rotation_matrix, (img.shape[1],
img.shape[0]))

# Create subplots
fig, axs = plt.subplots(1, 2, figsize=(7, 4))

# Plot the original image


axs[0].imshow(image_rgb)
axs[0].set_title('Original Image')

# Plot the Rotated image


axs[1].imshow(rotated_image)
axs[1].set_title('Image Rotation')

# Remove ticks from the subplots


for ax in axs:
ax.set_xticks([])
ax.set_yticks([])

# Display the subplots


Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

plt.tight_layout()
plt.show()

Output

To Avoid Cropping
 To avoid cropping when rotating an image, you need to calculate the new bounding

dimensions and adjust the transformation matrix accordingly.

 By default, cv2.warpAffine() keeps the output size the same as the input image, leading to

cropping.

Solution: Expand the Canvas Before Rotation

We need to:

1. Compute the new width and height after rotation.

2. Adjust the transformation matrix so the image remains centered.


Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

3. Use cv2.warpAffine() with the expanded canvas to keep the entire rotated image visible.

Updated Code (Rotation Without Cropping)


import cv2
import numpy as np
import matplotlib.pyplot as plt

# Read the image


img = cv2.imread('1.jpg')

# Convert BGR to RGB (for correct Matplotlib display)


image_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Get original image dimensions


(h, w) = image_rgb.shape[:2]

# Define rotation parameters


angle = 30
scale = 1

# Compute the center of the original image


center = (w // 2, h // 2)

# Get the 2×3 rotation matrix


rotation_matrix = cv2.getRotationMatrix2D(center, angle, scale)

# Compute new bounding dimensions (to fit the rotated image without
cropping)
cos_val = abs(rotation_matrix[0, 0])
sin_val = abs(rotation_matrix[0, 1])

new_w = int((h * sin_val) + (w * cos_val))


new_h = int((h * cos_val) + (w * sin_val))

# Adjust the rotation matrix to shift the image to the center of the new
canvas
rotation_matrix[0, 2] += (new_w - w) / 2
rotation_matrix[1, 2] += (new_h - h) / 2

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

# Apply the affine transformation (rotation) with the new dimensions


rotated_image = cv2.warpAffine(image_rgb, rotation_matrix, (new_w,
new_h))

# Display the original and rotated images


fig, axs = plt.subplots(1, 2, figsize=(10, 5))

axs[0].imshow(image_rgb)
axs[0].set_title('Original Image')
axs[0].axis("off")

axs[1].imshow(rotated_image)
axs[1].set_title('Rotated Image (No Cropping)')
axs[1].axis("off")

plt.tight_layout()
plt.show()

Image Translation
 Rotation spins an image around a fixed point (typically the center). It is performed using a

rotation matrix that rotates pixels around the chosen pivot.

 Translation moves an image horizontally and/or vertically without changing its orientation.

 To translate an image using OpenCV, we need to create a transformation matrix. This matrix

is a 2×3 matrix that specifies the amount of translation in each direction.

 The cv2.warpAffine() function is used to apply a transformation matrix to an image. It takes

the following arguments:

 The image to be transformed.

 The transformation matrix.

 The output image size.


Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

 The translation parameters are specified in the transformation matrix as

the tx and ty elements. The tx element specifies the amount of translation in the x-axis, while

the ty element specifies the amount of translation in the y-axis.

Python Implemetaion in VSCode

# Import the necessary Libraries


import cv2 # OpenCV for image processing
import numpy as np # Import NumPy to use np.array()
import matplotlib.pyplot as plt # Matplotlib for displaying images

# Read image from disk


img = cv2.imread('1.jpg')

# Check if the image is loaded correctly


if img is None:
print("Error: Image not found. Check the file path.")
exit()

# Convert BGR image (OpenCV default) to RGB for correct display in


Matplotlib
image_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Get image dimensions (width and height)


width = image_rgb.shape[1]
height = image_rgb.shape[0]

# Translation distances (shift right by tx, down by ty)


tx = 100 # Shift along X-axis
ty = 70 # Shift along Y-axis

# ✅ Ensure NumPy is imported before using np.array()


translation_matrix = np.array([[1, 0, tx], [0, 1, ty]], dtype=np.float32)

# Apply the translation using warpAffine


translated_image = cv2.warpAffine(image_rgb, translation_matrix, (width,
height))

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

# Create subplots to display original and translated images


fig, axs = plt.subplots(1, 2, figsize=(8, 4))

# Display the original image


axs[0].imshow(image_rgb)
axs[0].set_title('Original Image')

# Display the translated image


axs[1].imshow(translated_image)
axs[1].set_title('Translated Image')

# Remove axis ticks for cleaner visualization


for ax in axs:
ax.set_xticks([])
ax.set_yticks([])

# Adjust layout and display images


plt.tight_layout()
plt.show()

Output

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Image Sheering

 Image shearing is a transformation that slants an image in a particular direction, making it


look like it’s being pushed to the side. Instead of straight lines, objects in the image appear
tilted or skewed.
 Imagine you have a rectangle, and you push its top to the right while keeping the bottom in
place—it turns into a slanted parallelogram.

Horizontal Shearing (X-axis Shear)

 The image is stretched or slanted sideways (left or right).


 Vertical lines in the image become slanted.

Vertical Shearing (Y-axis Shear)

 The image is stretched or slanted up or down.


 Horizontal lines in the image become slanted.

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Python Implemetaion in VSCode

# Import the necessary libraries


import cv2
import numpy as np
import matplotlib.pyplot as plt

# Load the image


image = cv2.imread('1.jpg')

# Convert BGR image to RGB


image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Get image dimensions (width and height)


width, height = image_rgb.shape[1], image_rgb.shape[0]

# Define shearing factors


shearX = -0.15 # Shear along X-axis (negative for left slant)
shearY = 0 # No vertical shear

# Define the shearing transformation matrix (2x3 matrix required)


transformation_matrix = np.array(
Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

[[1, shearX, 0],


[shearY, 1, 0]], dtype=np.float32
)

# Apply shearing
sheared_image = cv2.warpAffine(image_rgb, transformation_matrix, (width,
height))

# Create subplots
fig, axs = plt.subplots(1, 2, figsize=(8, 4))

# Display the original image


axs[0].imshow(image_rgb)
axs[0].set_title('Original Image')

# Display the sheared image


axs[1].imshow(sheared_image)
axs[1].set_title('Sheared Image')

# Remove axis ticks for cleaner visualization


for ax in axs:
ax.set_xticks([])
ax.set_yticks([])

# Adjust layout and display the images


plt.tight_layout()
plt.show()

Output

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Image Normalization
 Image normalization is a process of scaling the pixel values in an image to a specific range.

 This is often done to improve the performance of image processing algorithms, as many

algorithms work better when the pixel values are within a certain range.

 In OpenCV, the cv2.normalize() function is used to normalize an image.

 This function takes the following arguments:

 The input image.

 The output image.

 The minimum and maximum values of the normalized image.

 The normalization type.

 The dtype of the output image.

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

 The normalization type specifies how the pixel values are scaled. There are several

different normalization types available, each with its own trade-offs between accuracy and

speed.

 Image normalization is a common preprocessing step in many image processing tasks. It

can help to improve the performance of algorithms such as image classification, object

detection, and image segmentation.

Python Implemetaion in VSCode


This code loads an image, normalizes its color channels, and displays both the original and

normalized images side by side.

# Import necessary libraries


import cv2
import numpy as np
import matplotlib.pyplot as plt

# Load the image


image = cv2.imread('1.jpg')

# Convert BGR image to RGB


image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)

# Split the image into individual color channels


b, g, r = cv2.split(image_rgb)

# Normalization parameters
min_value = 0 # Minimum value after normalization
max_value = 1 # Maximum value after normalization
norm_type = cv2.NORM_MINMAX # Type of normalization

# Normalize each channel independently


b_normalized = cv2.normalize(b.astype(np.float32), None, min_value,
max_value, norm_type)
Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

g_normalized = cv2.normalize(g.astype(np.float32), None, min_value,


max_value, norm_type)
r_normalized = cv2.normalize(r.astype(np.float32), None, min_value,
max_value, norm_type)

# Merge the normalized channels back into an image


normalized_image = np.clip(cv2.merge((b_normalized, g_normalized,
r_normalized)), 0, 1)

# Create subplots for original and normalized images


fig, axs = plt.subplots(1, 2, figsize=(10, 5))

# Display the original image


axs[0].imshow(image_rgb)
axs[0].set_title('Original Image')
axs[0].axis('off') # Hide axis

# Display the normalized image


axs[1].imshow(normalized_image)
axs[1].set_title('Normalized Image')
axs[1].axis('off') # Hide axis

# Adjust layout and show the images


plt.tight_layout()
plt.show()

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Output

Edge detection of Image


 The process of image edge detection involves detecting sharp edges in the image.

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

 This edge detection is essential in the context of image recognition or object

localization/detection. There are several algorithms for detecting edges due to its wide

applicability.

 In image processing and computer vision applications, Canny Edge Detection is a well-

liked edge detection approach.

 In order to detect edges, the Canny edge detector first smoothes the image to reduce noise,

then computes its gradient, and then applies a threshold to the gradient.

 The multi-stage Canny edge detection method includes the following steps::

 Converts the image to grayscale (if not done already).

 Applies Gaussian blur to reduce noise.

 Finds gradients (changes in intensity) in the image.

 Uses non-maximum suppression to thin out edges.

 Applies hysteresis thresholding:

o Strong edges (above threshold2) are kept.

o Weak edges (between threshold1 and threshold2) are kept only if connected to

strong edges.

o Edges below threshold1 are discarded.

Python Implemetaion in VSCode


# Import necessary libraries
import cv2
import numpy as np
import matplotlib.pyplot as plt
Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

# Read the image from disk


img = cv2.imread('1.jpg')

# Convert BGR image to RGB for correct color representation


image_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Convert RGB image to Grayscale for edge detection


gray_image = cv2.cvtColor(image_rgb, cv2.COLOR_RGB2GRAY)

# Apply Canny edge detection with optimized threshold values


edges = cv2.Canny(image=gray_image, threshold1=100, threshold2=200)

# Create subplots to display the original and edge-detected images


fig, axs = plt.subplots(1, 2, figsize=(8, 4))

# Display the original RGB image


axs[0].imshow(image_rgb)
axs[0].set_title('Original Image')
axs[0].axis('off') # Hide axis ticks

# Display the edge-detected image in grayscale


axs[1].imshow(edges, cmap='gray')
axs[1].set_title('Edge Detection')
axs[1].axis('off') # Hide axis ticks

# Adjust layout and display the images


plt.tight_layout()
plt.show()

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Output

Task

 What is Image Blurring.

 Perform Python implementation in VsCode of the following most common

blurring techniques:

 Gaussian blurring:

 Median blurrin

 Bilateral blurring

Digital Image Processing 6th Term-SE UET Taxila

You might also like