Assignment - 09
1. Implementing Dilation and Erosion:
● Write code to perform dilation and erosion operations on a noisy grayscale image using Python.
● Experiment with different structuring elements (e.g., square, disk, diamond) and compare how they affect the
output of dilation and erosion.
Ans:
import cv2
import numpy as np
import matplotlib.pyplot as plt
import urllib.request
from skimage.morphology import disk, square, diamond
# Function to download and read the image from a URL
def read_image_from_url(url):
resp = urllib.request.urlopen(url)
image_array = np.asarray(bytearray(resp.read()), dtype=np.uint8)
image = cv2.imdecode(image_array, cv2.IMREAD_GRAYSCALE) # Read as grayscale
return image
# Function to perform dilation and erosion
def dilation_erosion_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Square": square(5),
"Disk": disk(5),
"Diamond": diamond(5)
# Step 3: Perform dilation and erosion with each structuring element
results = {}
for name, element in structuring_elements.items():
dilated = cv2.dilate(image, element.astype(np.uint8))
eroded = cv2.erode(image, element.astype(np.uint8))
results[name] = (dilated, eroded)
# Step 4: Visualize the results
plt.figure(figsize=(18, 12))
plt.subplot(4, 3, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, (dilated, eroded) in results.items():
plt.subplot(4, 3, idx)
plt.title(f"Dilation - {name}")
plt.imshow(dilated, cmap='gray')
plt.axis('off')
idx += 1
plt.subplot(4, 3, idx)
plt.title(f"Erosion - {name}")
plt.imshow(eroded, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Example usage
image_url = "https://example.com/sample-image.jpg" # Replace with your image URL
dilation_erosion_operations(image_url)
2. Opening Operation:
● Implement the opening operation using OpenCV and logic.
● Apply the opening operation on a grayscale image using different structuring
elements such as rectangles, circles, and crosses.
● Compare the results obtained with different structuring elements.
import cv2
import numpy as np
import matplotlib.pyplot as plt
import urllib.request
from skimage.morphology import disk, square, diamond
# Function to download and read the image from a URL
def read_image_from_url(url):
resp = urllib.request.urlopen(url)
image_array = np.asarray(bytearray(resp.read()), dtype=np.uint8)
image = cv2.imdecode(image_array, cv2.IMREAD_GRAYSCALE) # Read as grayscale
return image
# Function to perform dilation and erosion
def dilation_erosion_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Square": square(5),
"Disk": disk(5),
"Diamond": diamond(5)
# Step 3: Perform dilation and erosion with each structuring element
results = {}
for name, element in structuring_elements.items():
dilated = cv2.dilate(image, element.astype(np.uint8))
eroded = cv2.erode(image, element.astype(np.uint8))
results[name] = (dilated, eroded)
# Step 4: Visualize the results
plt.figure(figsize=(18, 12))
plt.subplot(4, 3, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, (dilated, eroded) in results.items():
plt.subplot(4, 3, idx)
plt.title(f"Dilation - {name}")
plt.imshow(dilated, cmap='gray')
plt.axis('off')
idx += 1
plt.subplot(4, 3, idx)
plt.title(f"Erosion - {name}")
plt.imshow(eroded, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Function to perform opening operation
def opening_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Rectangle": cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)),
"Circle": cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
"Cross": cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
# Step 3: Perform opening with each structuring element
results = {}
for name, element in structuring_elements.items():
opened = cv2.morphologyEx(image, cv2.MORPH_OPEN, element)
results[name] = opened
# Step 4: Visualize the results
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, opened in results.items():
plt.subplot(2, 2, idx)
plt.title(f"Opening - {name}")
plt.imshow(opened, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Example usage
image_url = "https://example.com/sample-image.jpg" # Replace with your image URL
opening_operations(image_url)
3. Closing Operation:
● Implement the closing operation using OpenCV and logic.
● Apply the closing operation on a grayscale image using different structuring
elements such as rectangles, circles, and crosses.
● Compare the results obtained with different structuring elements.
ANS:
import cv2
import numpy as np
import matplotlib.pyplot as plt
import urllib.request
from skimage.morphology import disk, square, diamond
# Function to download and read the image from a URL
def read_image_from_url(url):
resp = urllib.request.urlopen(url)
image_array = np.asarray(bytearray(resp.read()), dtype=np.uint8)
image = cv2.imdecode(image_array, cv2.IMREAD_GRAYSCALE) # Read as grayscale
return image
# Function to perform dilation and erosion
def dilation_erosion_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Square": square(5),
"Disk": disk(5),
"Diamond": diamond(5)
# Step 3: Perform dilation and erosion with each structuring element
results = {}
for name, element in structuring_elements.items():
dilated = cv2.dilate(image, element.astype(np.uint8))
eroded = cv2.erode(image, element.astype(np.uint8))
results[name] = (dilated, eroded)
# Step 4: Visualize the results
plt.figure(figsize=(18, 12))
plt.subplot(4, 3, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, (dilated, eroded) in results.items():
plt.subplot(4, 3, idx)
plt.title(f"Dilation - {name}")
plt.imshow(dilated, cmap='gray')
plt.axis('off')
idx += 1
plt.subplot(4, 3, idx)
plt.title(f"Erosion - {name}")
plt.imshow(eroded, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Function to perform opening operation
def opening_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Rectangle": cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)),
"Circle": cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
"Cross": cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
# Step 3: Perform opening with each structuring element
results = {}
for name, element in structuring_elements.items():
opened = cv2.morphologyEx(image, cv2.MORPH_OPEN, element)
results[name] = opened
# Step 4: Visualize the results
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, opened in results.items():
plt.subplot(2, 2, idx)
plt.title(f"Opening - {name}")
plt.imshow(opened, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Function to perform closing operation
def closing_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Rectangle": cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)),
"Circle": cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
"Cross": cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
# Step 3: Perform closing with each structuring element
results = {}
for name, element in structuring_elements.items():
closed = cv2.morphologyEx(image, cv2.MORPH_CLOSE, element)
results[name] = closed
# Step 4: Visualize the results
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, closed in results.items():
plt.subplot(2, 2, idx)
plt.title(f"Closing - {name}")
plt.imshow(closed, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Example usage
image_url = "https://example.com/sample-image.jpg" # Replace with your image URL
closing_operations(image_url)
4. Morphological Gradient:
● Implement the morphological gradient operation using OpenCV and logic.
● Apply the morphological gradient operation on a grayscale image using different structuring elements such as
rectangles, circles, and crosses.
● Visualize and analyze the differences in results obtained with different structuring elements.
ANS:
import cv2
import numpy as np
import matplotlib.pyplot as plt
import urllib.request
from skimage.morphology import disk, square, diamond
# Function to download and read the image from a URL
def read_image_from_url(url):
resp = urllib.request.urlopen(url)
image_array = np.asarray(bytearray(resp.read()), dtype=np.uint8)
image = cv2.imdecode(image_array, cv2.IMREAD_GRAYSCALE) # Read as grayscale
return image
# Function to perform dilation and erosion
def dilation_erosion_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Square": square(5),
"Disk": disk(5),
"Diamond": diamond(5)
# Step 3: Perform dilation and erosion with each structuring element
results = {}
for name, element in structuring_elements.items():
dilated = cv2.dilate(image, element.astype(np.uint8))
eroded = cv2.erode(image, element.astype(np.uint8))
results[name] = (dilated, eroded)
# Step 4: Visualize the results
plt.figure(figsize=(18, 12))
plt.subplot(4, 3, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, (dilated, eroded) in results.items():
plt.subplot(4, 3, idx)
plt.title(f"Dilation - {name}")
plt.imshow(dilated, cmap='gray')
plt.axis('off')
idx += 1
plt.subplot(4, 3, idx)
plt.title(f"Erosion - {name}")
plt.imshow(eroded, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Function to perform opening operation
def opening_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Rectangle": cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)),
"Circle": cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
"Cross": cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
# Step 3: Perform opening with each structuring element
results = {}
for name, element in structuring_elements.items():
opened = cv2.morphologyEx(image, cv2.MORPH_OPEN, element)
results[name] = opened
# Step 4: Visualize the results
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, opened in results.items():
plt.subplot(2, 2, idx)
plt.title(f"Opening - {name}")
plt.imshow(opened, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Function to perform closing operation
def closing_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Rectangle": cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)),
"Circle": cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
"Cross": cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
# Step 3: Perform closing with each structuring element
results = {}
for name, element in structuring_elements.items():
closed = cv2.morphologyEx(image, cv2.MORPH_CLOSE, element)
results[name] = closed
# Step 4: Visualize the results
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, closed in results.items():
plt.subplot(2, 2, idx)
plt.title(f"Closing - {name}")
plt.imshow(closed, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Function to perform morphological gradient operation
def morphological_gradient_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Rectangle": cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)),
"Circle": cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
"Cross": cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
# Step 3: Perform morphological gradient with each structuring element
results = {}
for name, element in structuring_elements.items():
gradient = cv2.morphologyEx(image, cv2.MORPH_GRADIENT, element)
results[name] = gradient
# Step 4: Visualize the results
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, gradient in results.items():
plt.subplot(2, 2, idx)
plt.title(f"Gradient - {name}")
plt.imshow(gradient, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Example usage
image_url = "https://example.com/sample-image.jpg" # Replace with your image URL
morphological_gradient_operations(image_url)
5. Top Hat Operation:
● Implement the top hat operation using OpenCV and logic.
● Apply the top hat operation on a grayscale image using different structuring elements such as rectangles, circles,
and crosses.
● Examine the output images and discuss the effects of different structuring elements on the results.
import cv2
import numpy as np
import matplotlib.pyplot as plt
import urllib.request
from skimage.morphology import disk, square, diamond
# Function to download and read the image from a URL
def read_image_from_url(url):
resp = urllib.request.urlopen(url)
image_array = np.asarray(bytearray(resp.read()), dtype=np.uint8)
image = cv2.imdecode(image_array, cv2.IMREAD_GRAYSCALE) # Read as grayscale
return image
# Function to perform dilation and erosion
def dilation_erosion_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Square": square(5),
"Disk": disk(5),
"Diamond": diamond(5)
# Step 3: Perform dilation and erosion with each structuring element
results = {}
for name, element in structuring_elements.items():
dilated = cv2.dilate(image, element.astype(np.uint8))
eroded = cv2.erode(image, element.astype(np.uint8))
results[name] = (dilated, eroded)
# Step 4: Visualize the results
plt.figure(figsize=(18, 12))
plt.subplot(4, 3, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, (dilated, eroded) in results.items():
plt.subplot(4, 3, idx)
plt.title(f"Dilation - {name}")
plt.imshow(dilated, cmap='gray')
plt.axis('off')
idx += 1
plt.subplot(4, 3, idx)
plt.title(f"Erosion - {name}")
plt.imshow(eroded, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Function to perform opening operation
def opening_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Rectangle": cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)),
"Circle": cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
"Cross": cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
# Step 3: Perform opening with each structuring element
results = {}
for name, element in structuring_elements.items():
opened = cv2.morphologyEx(image, cv2.MORPH_OPEN, element)
results[name] = opened
# Step 4: Visualize the results
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, opened in results.items():
plt.subplot(2, 2, idx)
plt.title(f"Opening - {name}")
plt.imshow(opened, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Function to perform closing operation
def closing_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Rectangle": cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)),
"Circle": cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
"Cross": cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
# Step 3: Perform closing with each structuring element
results = {}
for name, element in structuring_elements.items():
closed = cv2.morphologyEx(image, cv2.MORPH_CLOSE, element)
results[name] = closed
# Step 4: Visualize the results
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, closed in results.items():
plt.subplot(2, 2, idx)
plt.title(f"Closing - {name}")
plt.imshow(closed, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Function to perform morphological gradient operation
def morphological_gradient_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Rectangle": cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)),
"Circle": cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
"Cross": cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
# Step 3: Perform morphological gradient with each structuring element
results = {}
for name, element in structuring_elements.items():
gradient = cv2.morphologyEx(image, cv2.MORPH_GRADIENT, element)
results[name] = gradient
# Step 4: Visualize the results
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, gradient in results.items():
plt.subplot(2, 2, idx)
plt.title(f"Gradient - {name}")
plt.imshow(gradient, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Function to perform top hat operation
def top_hat_operations(image_url):
# Step 1: Read the image from the URL
image = read_image_from_url(image_url)
# Step 2: Define structuring elements
structuring_elements = {
"Rectangle": cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)),
"Circle": cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)),
"Cross": cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5))
# Step 3: Perform top hat operation with each structuring element
results = {}
for name, element in structuring_elements.items():
top_hat = cv2.morphologyEx(image, cv2.MORPH_TOPHAT, element)
results[name] = top_hat
# Step 4: Visualize the results
plt.figure(figsize=(12, 8))
plt.subplot(2, 2, 1)
plt.title("Original Image")
plt.imshow(image, cmap='gray')
plt.axis('off')
idx = 2
for name, top_hat in results.items():
plt.subplot(2, 2, idx)
plt.title(f"Top Hat - {name}")
plt.imshow(top_hat, cmap='gray')
plt.axis('off')
idx += 1
plt.tight_layout()
plt.show()
# Example usage
image_url = "https://example.com/sample-image.jpg" # Replace with your image URL
top_hat_operations(image_url)
6. Black Hat Operation:
● Implement the black hat operation using OpenCV and logic.
● Apply the black hat operation on a grayscale image using different structuring
elements such as rectangles, circles, and crosses.
import cv2
import numpy as np
import requests
from io import BytesIO
import matplotlib.pyplot as plt
# Function to download and load an image from URL
def load_image_from_url(url):
response = requests.get(url)
img_array = np.array(bytearray(response.content), dtype=np.uint8)
image = cv2.imdecode(img_array, -1) # Decode the image to grayscale
return image
# Image URL (replace this with your image URL)
image_url = 'https://encrypted-
tbn0.gstatic.com/images?q=tbn:ANd9GcQ3VeYXSb6lCYDJJwi2XFj7Mtn3dmR9QdHafA&s'
# Load the grayscale image
image = load_image_from_url(image_url)
# Check if the image was loaded properly
if image is None:
print("Error loading image!")
else:
# Define structuring elements
kernel_rect = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5)) # Rectangle
kernel_circle = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)) # Circle
kernel_cross = cv2.getStructuringElement(cv2.MORPH_CROSS, (5, 5)) # Cross
# Apply black hat operation using different structuring elements
black_hat_rect = cv2.dilate(image, kernel_rect) - image
black_hat_circle = cv2.dilate(image, kernel_circle) - image
black_hat_cross = cv2.dilate(image, kernel_cross) - image
# Plot the original image and the results
plt.figure(figsize=(10, 10))
plt.subplot(2, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')
plt.axis('off')
plt.subplot(2, 2, 2)
plt.imshow(black_hat_rect, cmap='gray')
plt.title('Black Hat (Rectangle)')
plt.axis('off')
plt.subplot(2, 2, 3)
plt.imshow(black_hat_circle, cmap='gray')
plt.title('Black Hat (Circle)')
plt.axis('off')
plt.subplot(2, 2, 4)
plt.imshow(black_hat_cross, cmap='gray')
plt.title('Black Hat (Cross)')
plt.axis('off')
plt.tight_layout()
plt.show()