Exp No.
6:
a.)
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Provide the path to your grayscale image
image_path = 'point_image.bmp' # <-- Replace with actual path
# Read the image in grayscale
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Check if image is loaded correctly
if image is None:
print(f"❌ Error: Could not load image from '{image_path}'")
else:
# Define Laplacian kernel for point detection
laplacian_kernel = np.array([
[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]
], dtype=np.float32)
# Apply the Laplacian filter
point_detected = cv2.filter2D(image, -1, laplacian_kernel)
# Display results
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title("Original Image")
plt.xlabel("Width")
plt.ylabel("Height")
plt.subplot(1, 2, 2)
plt.imshow(point_detected, cmap='gray')
plt.title("Point Detected Image (Laplacian Filter)")
plt.xlabel("Width")
plt.ylabel("Height")
plt.tight_layout()
plt.show()
// w/o inbuilt function
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Provide the path to your grayscale image
image_path = 'point_image.bmp' # <-- Replace with actual path
# Read the image in grayscale
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Check if image is loaded correctly
if image is None:
print(f"❌ Error: Could not load image from '{image_path}'")
else:
# Define Laplacian kernel for point detection
laplacian_kernel = np.array([
[-1, -1, -1],
[-1, 8, -1],
[-1, -1, -1]
], dtype=np.float32)
# Get image dimensions
height, width = image.shape
# Pad the image with zeros (same padding as kernel size 3x3)
padded_image = np.pad(image, pad_width=1, mode='constant', constant_values=0)
# Create an empty output image
point_detected = np.zeros_like(image)
# Apply the Laplacian filter manually (convolution)
for i in range(1, height + 1): # Start from 1 to avoid padding
for j in range(1, width + 1): # Start from 1 to avoid padding
# Extract the region of interest (ROI)
roi = padded_image[i-1:i+2, j-1:j+2] # 3x3 region centered at (i,j)
# Perform the convolution (element-wise multiplication and sum)
point_detected[i-1, j-1] = np.sum(roi * laplacian_kernel)
# Display results
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title("Original Image")
plt.xlabel("Width")
plt.ylabel("Height")
plt.subplot(1, 2, 2)
plt.imshow(point_detected, cmap='gray')
plt.title("Point Detected Image (Manual Laplacian Filter)")
plt.xlabel("Width")
plt.ylabel("Height")
plt.tight_layout()
plt.show()
b.)
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load your grayscale image from path
image_path = 'line_image.bmp' # 🔁 Replace with your actual image path
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Check if image is loaded
if image is None:
print(f"❌ Error: Could not load image from '{image_path}'")
else:
# Define directional kernels
vertical_kernel = np.array([
[-1, 2, -1],
[-1, 2, -1],
[-1, 2, -1]
], dtype=np.float32)
horizontal_kernel = np.array([
[-1, -1, -1],
[ 2, 2, 2],
[-1, -1, -1]
], dtype=np.float32)
diag_45_kernel = np.array([
[-1, -1, 2],
[-1, 2, -1],
[ 2, -1, -1]
], dtype=np.float32)
diag_minus_45_kernel = np.array([
[ 2, -1, -1],
[-1, 2, -1],
[-1, -1, 2]
], dtype=np.float32)
# Apply the filters
vertical_lines = cv2.filter2D(image, -1, vertical_kernel)
horizontal_lines = cv2.filter2D(image, -1, horizontal_kernel)
diag_45_lines = cv2.filter2D(image, -1, diag_45_kernel)
diag_minus_45_lines = cv2.filter2D(image, -1, diag_minus_45_kernel)
# Plot results
plt.figure(figsize=(12, 8))
plt.subplot(2, 3, 1)
plt.imshow(image, cmap='gray')
plt.title("Original Image")
plt.axis("off")
plt.subplot(2, 3, 2)
plt.imshow(vertical_lines, cmap='gray')
plt.title("Vertical Line Detection")
plt.axis("off")
plt.subplot(2, 3, 3)
plt.imshow(horizontal_lines, cmap='gray')
plt.title("Horizontal Line Detection")
plt.axis("off")
plt.subplot(2, 3, 4)
plt.imshow(diag_45_lines, cmap='gray')
plt.title("Diagonal 45° Line Detection")
plt.axis("off")
plt.subplot(2, 3, 5)
plt.imshow(diag_minus_45_lines, cmap='gray')
plt.title("Diagonal -45° Line Detection")
plt.axis("off")
plt.tight_layout()
plt.show()
// w/o inbuilt function
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load your grayscale image from path
image_path = 'line_image.bmp' # 🔁 Replace with your actual image path
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
# Check if image is loaded
if image is None:
print(f"❌ Error: Could not load image from '{image_path}'")
else:
# Define directional kernels
vertical_kernel = np.array([
[-1, 2, -1],
[-1, 2, -1],
[-1, 2, -1]
], dtype=np.float32)
horizontal_kernel = np.array([
[-1, -1, -1],
[ 2, 2, 2],
[-1, -1, -1]
], dtype=np.float32)
diag_45_kernel = np.array([
[-1, -1, 2],
[-1, 2, -1],
[ 2, -1, -1]
], dtype=np.float32)
diag_minus_45_kernel = np.array([
[ 2, -1, -1],
[-1, 2, -1],
[-1, -1, 2]
], dtype=np.float32)
# Function to apply kernel manually (convolution)
def apply_kernel(image, kernel):
# Get image dimensions
height, width = image.shape
# Pad the image with zeros (same padding as kernel size 3x3)
padded_image = np.pad(image, pad_width=1, mode='constant',
constant_values=0)
# Create an empty output image
output_image = np.zeros_like(image)
# Apply the kernel manually (convolution)
for i in range(1, height + 1): # Start from 1 to avoid padding
for j in range(1, width + 1): # Start from 1 to avoid padding
# Extract the region of interest (ROI)
roi = padded_image[i-1:i+2, j-1:j+2] # 3x3 region centered at
(i,j)
# Perform the convolution (element-wise multiplication and sum)
output_image[i-1, j-1] = np.sum(roi * kernel)
return output_image
# Apply the filters manually
vertical_lines = apply_kernel(image, vertical_kernel)
horizontal_lines = apply_kernel(image, horizontal_kernel)
diag_45_lines = apply_kernel(image, diag_45_kernel)
diag_minus_45_lines = apply_kernel(image, diag_minus_45_kernel)
# Plot results
plt.figure(figsize=(12, 8))
plt.subplot(2, 3, 1)
plt.imshow(image, cmap='gray')
plt.title("Original Image")
plt.axis("off")
plt.subplot(2, 3, 2)
plt.imshow(vertical_lines, cmap='gray')
plt.title("Vertical Line Detection")
plt.axis("off")
plt.subplot(2, 3, 3)
plt.imshow(horizontal_lines, cmap='gray')
plt.title("Horizontal Line Detection")
plt.axis("off")
plt.subplot(2, 3, 4)
plt.imshow(diag_45_lines, cmap='gray')
plt.title("Diagonal 45° Line Detection")
plt.axis("off")
plt.subplot(2, 3, 5)
plt.imshow(diag_minus_45_lines, cmap='gray')
plt.title("Diagonal -45° Line Detection")
plt.axis("off")
plt.tight_layout()
plt.show()
c.)
import cv2
import numpy as np
import matplotlib.pyplot as plt
image_path = 'thresh_img.bmp' # Replace with actual path
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
T = np.mean(image)
delta_T = 1
max_iterations = 100
iteration = 0
while True:
G1 = image[image > T]
G2 = image[image <= T]
m1 = np.mean(G1) if len(G1) > 0 else 0
m2 = np.mean(G2) if len(G2) > 0 else 0
new_T = (m1 + m2) / 2
if abs(new_T - T) < delta_T or iteration >= max_iterations:
break
T = new_T
iteration += 1
_, thresholded_image = cv2.threshold(image, int(T), 255, cv2.THRESH_BINARY)
plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title("Original Image")
plt.axis("off")
plt.subplot(1, 2, 2)
plt.imshow(thresholded_image, cmap='gray')
plt.title(f"Thresholded Image (T = {int(T)})")
plt.axis("off")
plt.tight_layout()
plt.show()
print(f"Final Threshold Value: {int(T)}")