0% found this document useful (0 votes)
2 views

Digital Image Processing Lab Manual

The document provides a series of Python programs using the Pillow and OpenCV libraries for various image processing tasks, including extracting image attributes, converting images to grayscale, resizing, flipping, and applying transformations. It also covers advanced techniques like Power Law Transformation, Histogram Equalization, and image smoothing and sharpening. Each program includes explanations of the code and expected outputs, making it a comprehensive guide for image processing in Python.

Uploaded by

Sia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Digital Image Processing Lab Manual

The document provides a series of Python programs using the Pillow and OpenCV libraries for various image processing tasks, including extracting image attributes, converting images to grayscale, resizing, flipping, and applying transformations. It also covers advanced techniques like Power Law Transformation, Histogram Equalization, and image smoothing and sharpening. Each program includes explanations of the code and expected outputs, making it a comprehensive guide for image processing in Python.

Uploaded by

Sia
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

Q. 1. Write a program to extract different Attributes of an Image.

You can use the Python library Pillow (PIL) to extract different attributes of an image, such as:

 Image format (JPEG, PNG, etc.)


 Mode (RGB, grayscale, etc.)
 Size (Width × Height)
 Color Palette (for mode P)
 EXIF Data (for me

from PIL import Image

from PIL.ExifTags import TAGS

# Load an image

image_path = "sample.jpg" # Change to your image file

img = Image.open(image_path)

# Extract basic attributes

print(f"Filename: {img.filename}")

print(f"Format: {img.format}")

print(f"Mode: {img.mode}")

print(f"Size: {img.size}") # (width, height)

print(f"Color Palette: {img.palette}")

# Extract EXIF metadata (if available)

exif_data = img._getexif()

if exif_data:

print("\nEXIF Data:")

for tag_id, value in exif_data.items():

tag_name = TAGS.get(tag_id, tag_id)

print(f"{tag_name}: {value}")

1
else:

print("\nNo EXIF metadata found.")

Explanation

1. Image.open(image_path): Loads the image.


2. Basic attributes like filename, format, mode, size, and color palette are extracted.
3. EXIF metadata extraction: If available, the program prints metadata such as camera model,
date taken, exposure, etc.

Sample Output

Filename: sample.jpg

Format: JPEG

Mode: RGB

Size: (1920, 1080)

Color Palette: None

EXIF Data:

Make: Canon

Model: EOS 80D

DateTime: 2024:03:10 14:30:05

ExposureTime: 1/250

FNumber: 2.8

...

This program helps analyze an image's properties efficiently!

2
2. Write a program to display gray scale image, resize image, transform image.
You can use the Pillow (PIL) library in Python to:

1. Convert an image to grayscale


2. Resize the image
3. Apply transformations (rotate, flip, etc.)

Python Program

from PIL import Image

# Load an image

image_path = "sample.jpg" # Change to your image file

img = Image.open(image_path)

# Convert to grayscale

gray_img = img.convert("L")

gray_img.show(title="Grayscale Image")

# Resize the image

new_size = (300, 300) # (width, height)

resized_img = img.resize(new_size)

resized_img.show(title="Resized Image")

# Apply transformations

rotated_img = img.rotate(45) # Rotate 45 degrees

rotated_img.show(title="Rotated Image")

flipped_img = img.transpose(Image.FLIP_LEFT_RIGHT) # Flip horizontally

flipped_img.show(title="Flipped Image")

3
# Save modified images

gray_img.save("gray_image.jpg")

resized_img.save("resized_image.jpg")

rotated_img.save("rotated_image.jpg")

flipped_img.save("flipped_image.jpg")

print("Image processing completed!")

Explanation

1. convert("L") → Converts the image to grayscale.


2. resize(new_size) → Resizes the image to (300×300).
3. rotate(45) → Rotates the image by 45 degrees.
4. transpose(Image.FLIP_LEFT_RIGHT) → Flips the image horizontally.
5. show() → Displays the modified images.
6. save() → Saves the images for future use.

Expected Output

 A grayscale image
 A resized image (300×300 pixels)
 A rotated image (45° rotation)
 A flipped image (mirrored horizontally)

This program is great for basic image processing tasks!

4
3. Write a program to convert color image to gray scale image, Color image into
Binary Image, Separate color image into three separate R, G, B planes, combine
three separate R, G, B planes to create color image.
Here’s a Python program that performs the following operations using the OpenCV (cv2) library:

1. Convert a color image to grayscale


2. Convert a color image to a binary image
3. Separate a color image into R, G, B planes
4. Combine the R, G, B planes back into a color image

Python Program

import cv2

import numpy as np

# Load the color image

image_path = "sample.jpg" # Change to your image file

img = cv2.imread(image_path)

# Convert to grayscale

gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Convert to binary (Thresholding)

_, binary_img = cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY)

# Split image into R, G, B channels

B, G, R = cv2.split(img)

# Merge R, G, B channels to recreate the original image

merged_img = cv2.merge([B, G, R])

5
# Display images
cv2.imshow("Original Image", img)
cv2.imshow("Grayscale Image", gray_img)
cv2.imshow("Binary Image", binary_img)
cv2.imshow("Red Channel", R)
cv2.imshow("Green Channel", G)
cv2.imshow("Blue Channel", B)
cv2.imshow("Merged Image", merged_img)

# Save processed images

cv2.imwrite("gray_image.jpg", gray_img)
cv2.imwrite("binary_image.jpg", binary_img)
cv2.imwrite("red_channel.jpg", R)
cv2.imwrite("green_channel.jpg", G)
cv2.imwrite("blue_channel.jpg", B)
cv2.imwrite("merged_image.jpg", merged_img)

# Wait for a key press and close windows

cv2.waitKey(0)

cv2.destroyAllWindows()

Explanation

1. Convert to Grayscale:
o cv2.cvtColor(img, cv2.COLOR_BGR2GRAY): Converts the color image to grayscale.
2. Convert to Binary:
o cv2.threshold(gray_img, 127, 255, cv2.THRESH_BINARY): Converts grayscale
to binary using a threshold of 127.
3. Split RGB Channels:
o cv2.split(img): Splits the image into Red, Green, and Blue channels.
4. Merge RGB Channels Back:
o cv2.merge([B, G, R]): Combines the separate color planes to reconstruct the
original image.
5. Display and Save Images:
o cv2.imshow() → Displays images.
o cv2.imwrite() → Saves images for later use.

Expected Output

 Grayscale Image
 Binary (Black & White) Image
 Red, Green, and Blue Channel Images
 Reconstructed (Merged) Image
6
4. Write a program for Flip given image horizontally, modify program of
horizontal flipping for getting vertical flipping, Perform image arithmetic
operation.
Here’s a Python program that performs the following operations using OpenCV (cv2):

1. Flip an image horizontally


2. Flip an image vertically
3. Perform image arithmetic operations (Addition & Subtraction)

Python Program

import cv2

import numpy as np

# Load the image

image_path = "sample.jpg" # Change this to your image file

img = cv2.imread(image_path)

# Flip image horizontally

horizontal_flip = cv2.flip(img, 1)

# Flip image vertically

vertical_flip = cv2.flip(img, 0)

# Create a white image of the same size for arithmetic operations

white_img = np.ones(img.shape, dtype=np.uint8) * 50 # Brightness level 50

# Image Addition (Brightening)

brightened_img = cv2.add(img, white_img)

7
# Image Subtraction (Darkening)

darkened_img = cv2.subtract(img, white_img)

# Display images
cv2.imshow("Original Image", img)
cv2.imshow("Horizontally Flipped Image", horizontal_flip)
cv2.imshow("Vertically Flipped Image", vertical_flip)
cv2.imshow("Brightened Image (Addition)", brightened_img)
cv2.imshow("Darkened Image (Subtraction)", darkened_img)

# Save processed images

cv2.imwrite("horizontal_flip.jpg", horizontal_flip)
cv2.imwrite("vertical_flip.jpg", vertical_flip)
cv2.imwrite("brightened_image.jpg", brightened_img)
cv2.imwrite("darkened_image.jpg", darkened_img)

# Wait for a key press and close windows

cv2.waitKey(0)

cv2.destroyAllWindows()

Explanation

1. Flip Horizontally
o cv2.flip(img, 1): Flips the image left-right (mirroring).
2. Flip Vertically
o cv2.flip(img, 0):
Flips the image upside-down.
3. Image Addition (Brightening Effect)
o cv2.add(img, white_img): Increases pixel values to make the image brighter.
4. Image Subtraction (Darkening Effect)
o cv2.subtract(img, white_img): Decreases pixel values to make the image
darker.
5. Displaying & Saving Images
o cv2.imshow() → Displays images.
o cv2.imwrite() → Saves images to disk.

Expected Output

 Horizontally Flipped Image


 Vertically Flipped Image
 Brightened Image
 Darkened Image
8
5. Write a program for Power Law Transformation.

Power Law (Gamma) Transformation in Image Processing

Power Law Transformation is used to enhance images by adjusting brightness and contrast. It
follows the formula:

s=c⋅rγs = c \cdot r^\gammas=c⋅rγ

where:

 sss is the output pixel value


 rrr is the input pixel value (normalized)
 ccc is a scaling constant
 γ\gammaγ (Gamma) controls brightness/contrast. If:
o γ<1\gamma < 1γ<1 → Image gets brighter
o γ>1\gamma > 1γ>1 → Image gets darker

Python Program for Power Law (Gamma) Transformation

import cv2

import numpy as np

def power_law_transformation(image, gamma):

# Normalize image to range [0,1]

normalized_img = image / 255.0

# Apply Power Law Transformation

transformed_img = np.power(normalized_img, gamma)

# Scale back to [0,255]

transformed_img = np.uint8(transformed_img * 255)

return transformed_img

# Load the image


9
image_path = "sample.jpg" # Replace with your image

img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE) # Convert to grayscale

# Apply Gamma Transformation

gamma_low = power_law_transformation(img, 0.5) # Brightens the image

gamma_high = power_law_transformation(img, 2.0) # Darkens the image

# Display results

cv2.imshow("Original Image", img)


cv2.imshow("Gamma 0.5 (Brightened)", gamma_low)
cv2.imshow("Gamma 2.0 (Darkened)", gamma_high)

# Save transformed images

cv2.imwrite("gamma_0.5.jpg", gamma_low)
cv2.imwrite("gamma_2.0.jpg", gamma_high)

cv2.waitKey(0)

cv2.destroyAllWindows()

Explanation

1. Normalize the Image


o Convert pixel values to range [0,1] for correct transformation.
2. Apply Power Law
o Compute s=rγs = r^\gammas=rγ element-wise using np.power().
3. Rescale Back to [0,255]
o Multiply by 255 and convert to uint8.
4. Different Gamma Values
o γ=0.5\gamma = 0.5γ=0.5 → Brightens the image.
o γ=2.0\gamma = 2.0γ=2.0 → Darkens the image.

Expected Output

 Gamma 0.5 Image: Brighter than the original.


 Gamma 2.0 Image: Darker than the original.

10
6. Write a program for Histogram Mapping and Equalization.

Histogram Mapping and Equalization in Image Processing

Histogram Equalization is a technique to improve the contrast of an image by redistributing pixel


intensity values. It is particularly useful for enhancing images with poor contrast.

Python Program for Histogram Equalization

import cv2

import numpy as np

import matplotlib.pyplot as plt

# Load the image in grayscale

image_path = "sample.jpg" # Replace with your image

img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

# Apply Histogram Equalization

equalized_img = cv2.equalizeHist(img)

# Plot histograms before and after equalization

plt.figure(figsize=(10, 5))

# Original Histogram

plt.subplot(2, 2, 1)

plt.imshow(img, cmap='gray')

plt.title("Original Image")

plt.axis("off")

plt.subplot(2, 2, 2)

plt.hist(img.ravel(), 256, [0, 256])


11
plt.title("Histogram of Original Image")

# Equalized Histogram

plt.subplot(2, 2, 3)
plt.imshow(equalized_img, cmap='gray')
plt.title("Equalized Image")
plt.axis("off")

plt.subplot(2, 2, 4)

plt.hist(equalized_img.ravel(), 256, [0, 256])

plt.title("Histogram of Equalized Image")

plt.tight_layout()

plt.show()

# Save the Equalized Image

cv2.imwrite("equalized_image.jpg", equalized_img)

Explanation

1. Load the Image


o Convert it to grayscale for equalization.
2. Apply cv2.equalizeHist()
o Redistributes pixel intensities for improved contrast.
3. Plot Histograms
o Before Equalization: The histogram may be concentrated in a specific range.
o After Equalization: The histogram becomes more spread out, increasing contrast.
4. Save the Equalized Image
o The improved image is saved for comparison.

Expected Output

 Original Image: May have poor contrast.


 Equalized Image: Improved contrast.
 Histograms:
o Before Equalization: Pixel values are clustered.
o After Equalization: Spread across full intensity range [0,255][0, 255][0,255].

12
7. Write a program for Image Smoothening and Sharpening.

Image Smoothing and Sharpening in Python

Image smoothing helps reduce noise, while sharpening enhances the edges in an image.

Python Program for Image Smoothing and Sharpening

import cv2

import numpy as np

import matplotlib.pyplot as plt

# Load the image

image_path = "sample.jpg" # Replace with your image path

img = cv2.imread(image_path)

img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # Convert BGR to RGB for correct visualization

# **1. Image Smoothing (Blurring)**

# Apply Gaussian Blur

gaussian_blur = cv2.GaussianBlur(img, (5, 5), 0)

# Apply Median Blur

median_blur = cv2.medianBlur(img, 5)

# Apply Bilateral Filter (Preserves edges)

bilateral_blur = cv2.bilateralFilter(img, 9, 75, 75)

# **2. Image Sharpening**

# Sharpening Kernel

sharpening_kernel = np.array([[-1, -1, -1],

13
[-1, 9, -1],

[-1, -1, -1]])

sharpened_img = cv2.filter2D(img, -1, sharpening_kernel)

# **3. Display the Results**

plt.figure(figsize=(12, 8))

# Original Image

plt.subplot(2, 3, 1)

plt.imshow(img)

plt.title("Original Image")

plt.axis("off")

# Gaussian Blurred Image

plt.subplot(2, 3, 2)

plt.imshow(gaussian_blur)

plt.title("Gaussian Blur")

plt.axis("off")

# Median Blurred Image

plt.subplot(2, 3, 3)

plt.imshow(median_blur)

plt.title("Median Blur")

plt.axis("off")

14
# Bilateral Filtered Image
plt.subplot(2, 3, 4)
plt.imshow(bilateral_blur)
plt.title("Bilateral Filter")
plt.axis("off")

# Sharpened Image
plt.subplot(2, 3, 5)
plt.imshow(sharpened_img)
plt.title("Sharpened Image")
plt.axis("off")

plt.tight_layout()

plt.show()

# Save the processed images


cv2.imwrite("gaussian_blur.jpg", cv2.cvtColor(gaussian_blur, cv2.COLOR_RGB2BGR))
cv2.imwrite("median_blur.jpg", cv2.cvtColor(median_blur, cv2.COLOR_RGB2BGR))
cv2.imwrite("bilateral_blur.jpg", cv2.cvtColor(bilateral_blur, cv2.COLOR_RGB2BGR))
cv2.imwrite("sharpened_image.jpg", cv2.cvtColor(sharpened_img, cv2.COLOR_RGB2BGR))

Explanation

1. Image Smoothing (Blurring)

 Gaussian Blur: Uses a Gaussian kernel to blur the image and remove noise.
 Median Blur: Replaces each pixel with the median of its surrounding pixels; effective against "salt
and pepper" noise.
 Bilateral Filter: Reduces noise while preserving edges.

2. Image Sharpening

 Uses a high-pass filter to emphasize edges and enhance details.

Expected Output

The program will display:

1. Original Image
2. Gaussian Blurred Image
3. Median Blurred Image
4. Bilateral Filtered Image
5. Sharpened Image
15
8. Write a program for Edge Detection using

Edge Detection Using Sobel, Prewitt, and Roberts Operators in Python

Edge detection is used to identify boundaries within an image. This program applies three different
operators:

 Sobel Operator: Detects edges in horizontal and vertical directions using gradient-based
detection.
 Prewitt Operator: Similar to Sobel but uses a different kernel for calculating gradients.
 Roberts Operator: Uses small 2×2 kernels for detecting edges.

Python Program for Edge Detection

import cv2

import numpy as np

import matplotlib.pyplot as plt

# Load the image in grayscale

image_path = "sample.jpg" # Replace with your image path

img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

# **1. Sobel Operator**

sobel_x = cv2.Sobel(img, cv2.CV_64F, 1, 0, ksize=3) # Gradient in X direction

sobel_y = cv2.Sobel(img, cv2.CV_64F, 0, 1, ksize=3) # Gradient in Y direction

sobel_combined = cv2.magnitude(sobel_x, sobel_y) # Magnitude of gradients

# **2. Prewitt Operator**

prewitt_x = cv2.filter2D(img, -1, np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])) # X-direction

16
prewitt_y = cv2.filter2D(img, -1, np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])) # Y-direction

prewitt_combined = cv2.magnitude(prewitt_x.astype(np.float32), prewitt_y.astype(np.float32))

# **3. Roberts Operator**

roberts_x = cv2.filter2D(img, -1, np.array([[1, 0], [0, -1]])) # X-direction

roberts_y = cv2.filter2D(img, -1, np.array([[0, 1], [-1, 0]])) # Y-direction

roberts_combined = cv2.magnitude(roberts_x.astype(np.float32), roberts_y.astype(np.float32))

# **4. Display the Results**

plt.figure(figsize=(12, 8))

# Original Image

plt.subplot(2, 3, 1)

plt.imshow(img, cmap="gray")

plt.title("Original Image")

plt.axis("off")

# Sobel Edge Detection

plt.subplot(2, 3, 2)

plt.imshow(sobel_combined, cmap="gray")

plt.title("Sobel Edge Detection")

plt.axis("off")

# Prewitt Edge Detection

plt.subplot(2, 3, 3)

17
plt.imshow(prewitt_combined, cmap="gray")

plt.title("Prewitt Edge Detection")

plt.axis("off")

# Roberts Edge Detection


plt.subplot(2, 3, 4)
plt.imshow(roberts_combined, cmap="gray")
plt.title("Roberts Edge Detection")
plt.axis("off")

plt.tight_layout()

plt.show()

# Save the processed images


cv2.imwrite("sobel_edge.jpg", sobel_combined)
cv2.imwrite("prewitt_edge.jpg", prewitt_combined)
cv2.imwrite("roberts_edge.jpg", roberts_combined)

Explanation

1. Sobel Operator
o Uses 3×3 kernels to detect edges.
o Computes gradients in X and Y directions separately.
o Magnitude is calculated to combine the two gradient components.
2. Prewitt Operator
o Similar to Sobel but with a different filter matrix.
o Less sensitive to noise compared to Sobel.
3. Roberts Operator
o Uses 2×2 kernels, making it computationally less expensive.
o Detects edges at diagonal orientations.

Expected Output

The program will display:

 Original Image
 Sobel Edge Detection Result
 Prewitt Edge Detection Result
 Roberts Edge Detection Result

18
9. Write a program to implement segmentation using Global threshold method.

Image Segmentation Using Global Thresholding in Python

Global thresholding is a simple image segmentation technique that converts a grayscale image into a
binary image based on a threshold value. All pixel values above the threshold are set to white (255),
and all values below are set to black (0).

Python Program for Global Thresholding


import cv2

import numpy as np

import matplotlib.pyplot as plt

# Load the image in grayscale

image_path = "sample.jpg" # Replace with your image path

img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

# Apply Global Thresholding

threshold_value = 127 # You can adjust this value

_, binary_img = cv2.threshold(img, threshold_value, 255, cv2.THRESH_BINARY)

# Display the original and thresholded images

plt.figure(figsize=(10, 5))

# Original Image

plt.subplot(1, 2, 1)

plt.imshow(img, cmap="gray")

plt.title("Original Grayscale Image")

plt.axis("off")

19
# Thresholded Image

plt.subplot(1, 2, 2)

plt.imshow(binary_img, cmap="gray")

plt.title(f"Thresholded Image (T = {threshold_value})")

plt.axis("off")

plt.tight_layout()

plt.show()

# Save the thresholded image

cv2.imwrite("global_threshold.jpg", binary_img)

Explanation

1. Read the Image: The image is loaded in grayscale mode.


2. Apply Global Thresholding:
o A threshold value T is chosen (e.g., 127).
o Pixels ≥ T are set to 255 (white).
o Pixels < T are set to 0 (black).
3. Display and Save the Results:
o The original and segmented images are displayed side by side.
o The binary image is saved as "global_threshold.jpg".

Expected Output

 Original Image (Grayscale)


 Thresholded Image (Black & White, segmented using the threshold value)

Next Steps

 Use Otsu’s method (cv2.THRESH_OTSU) to automatically determine the optimal threshold:

_, otsu_threshold = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

 Apply adaptive thresholding for non-uniform lighting conditions:

adaptive_threshold = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C,

cv2.THRESH_BINARY, 11, 2)

20
10. Write a program to implement segmentation using local thresholding
method.

Image Segmentation Using Local Thresholding in Python

Local (or Adaptive) thresholding is useful when the image has varying lighting conditions. Instead
of using a single threshold value for the entire image, it calculates the threshold for small regions.

Python Program for Local Thresholding

import cv2

import numpy as np

import matplotlib.pyplot as plt

# Load the image in grayscale

image_path = "sample.jpg" # Replace with your image path

img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

# Apply Adaptive Mean Thresholding

adaptive_mean = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_MEAN_C,

cv2.THRESH_BINARY, 11, 2)

# Apply Adaptive Gaussian Thresholding

adaptive_gaussian = cv2.adaptiveThreshold(img, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,

cv2.THRESH_BINARY, 11, 2)

# Display the results

plt.figure(figsize=(15, 5))

# Original Image

plt.subplot(1, 3, 1)
21
plt.imshow(img, cmap="gray")

plt.title("Original Grayscale Image")

plt.axis("off")

# Adaptive Mean Thresholding

plt.subplot(1, 3, 2)

plt.imshow(adaptive_mean, cmap="gray")

plt.title("Adaptive Mean Thresholding")

plt.axis("off")

# Adaptive Gaussian Thresholding

plt.subplot(1, 3, 3)

plt.imshow(adaptive_gaussian, cmap="gray")

plt.title("Adaptive Gaussian Thresholding")

plt.axis("off")

plt.tight_layout()

plt.show()

# Save the thresholded images

cv2.imwrite("adaptive_mean_threshold.jpg", adaptive_mean)

cv2.imwrite("adaptive_gaussian_threshold.jpg", adaptive_gaussian)

Explanation

1. Read the Image: The image is loaded in grayscale.


2. Apply Local Thresholding:
o Adaptive Mean Thresholding: The threshold is the mean of pixel values in a
neighborhood.
o Adaptive Gaussian Thresholding: The threshold is a weighted sum of neighboring
pixels (Gaussian window).
22
3. Display and Save the Results:
o The original and thresholded images are displayed side by side.
o The results are saved as "adaptive_mean_threshold.jpg" and
"adaptive_gaussian_threshold.jpg".

Expected Output

 Original Image (Grayscale)


 Adaptive Mean Thresholding (Better for uniform lighting)
 Adaptive Gaussian Thresholding (Better for images with gradients)

Next Steps

 Try different block sizes (e.g., cv2.adaptiveThreshold(..., 15, 5)) to fine-tune the
segmentation.
 Use Otsu’s thresholding for a hybrid approach:

_, otsu_threshold = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

23
11. Write a program for Morphological Operations on Binary Images.

Program for Morphological Operations on Binary Images using OpenCV

Morphological operations are used for image preprocessing, noise removal, and object shape
analysis. The most common operations include:

1. Erosion - Shrinks the white regions (removes noise).


2. Dilation - Expands white regions.
3. Opening - Erosion followed by Dilation (removes small noise).
4. Closing - Dilation followed by Erosion (fills small holes).
5. Gradient - Difference between dilation and erosion (outlines objects).

Python Code for Morphological Operations

import cv2

import numpy as np

import matplotlib.pyplot as plt

# Load binary image

image_path = "binary_image.jpg" # Replace with your image path

img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)

# Convert to binary using thresholding if needed

_, binary_img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)

# Define kernel (structuring element)

kernel = np.ones((5,5), np.uint8) # 5x5 square kernel

# Apply morphological operations

erosion = cv2.erode(binary_img, kernel, iterations=1)

dilation = cv2.dilate(binary_img, kernel, iterations=1)


24
opening = cv2.morphologyEx(binary_img, cv2.MORPH_OPEN, kernel)

closing = cv2.morphologyEx(binary_img, cv2.MORPH_CLOSE, kernel)

gradient = cv2.morphologyEx(binary_img, cv2.MORPH_GRADIENT, kernel)

# Display results

titles = ["Original", "Erosion", "Dilation", "Opening", "Closing", "Gradient"]

images = [binary_img, erosion, dilation, opening, closing, gradient]

plt.figure(figsize=(15, 8))

for i in range(6):

plt.subplot(2, 3, i+1)

plt.imshow(images[i], cmap="gray")

plt.title(titles[i])

plt.axis("off")

plt.tight_layout()

plt.show()

# Save the output images

cv2.imwrite("erosion.jpg", erosion)

cv2.imwrite("dilation.jpg", dilation)

cv2.imwrite("opening.jpg", opening)

cv2.imwrite("closing.jpg", closing)

cv2.imwrite("gradient.jpg", gradient)

Explanation
25
1. Load the Image: Reads a binary image (black and white).
2. Thresholding: Ensures the image is binary (if not already).
3. Define Kernel: A 5×5 structuring element for operations.
4. Apply Morphological Operations:
o Erosion: Removes small white pixels.
o Dilation: Expands white regions.
o Opening: Removes small noise.
o Closing: Fills small holes.
o Gradient: Highlights edges of objects.
5. Display & Save Results: Shows the original and processed images.

Expected Output

 Original Image (Binary)


 Eroded Image (Shrinks objects)
 Dilated Image (Expands objects)
 Opened Image (Noise removal)
 Closed Image (Hole filling)
 Gradient Image (Object boundaries)

Next Steps

 Experiment with differe

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5,5))

26

You might also like