You are on page 1of 37

DIP Lab Assignment

( Programs no. 11 to 20 – Python Program)

By – Gulshan Kumar(22PGMCA36)

Submitted to – Dr. R. S. Hegadi

(1) A11_hit_or_miss

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

# Load the image


t = cv2.imread(‘text.JPG’, cv2.IMREAD_GRAYSCALE)
t = cv2.threshold(t, 128, 255, cv2.THRESH_BINARY)[1]

# Display the original image


plt.imshow(t, cmap='gray')
plt.title('Text image')
plt.show()

# Define structuring elements


b1 = np.ones((1, 6), np.uint8)
b2 = np.array([[1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 1],
[1, 1, 1, 1, 1, 1, 1, 1]], dtype=np.uint8)

# Display structuring elements


plt.imshow(b1, cmap='gray')
plt.title('B1')
plt.show()

plt.imshow(b2, cmap='gray')
plt.title('B2')
plt.show()

# Erode the image with structuring elements


tb1 = cv2.erode(t, b1, iterations=1)
tb2 = cv2.erode(~t, b2, iterations=1)

# Display eroded images


plt.imshow(tb1, cmap='gray')
plt.title('Tb1')
plt.show()

plt.imshow(tb2, cmap='gray')
plt.title('Tb2')
plt.show()

# Perform hit-or-miss transform


hit_or_miss = cv2.bitwise_and(tb1, tb2)

# Find the coordinates of the hit pixels


x, y = np.where(hit_or_miss == 1)

# Display the hit-or-miss result and the original image with detected lines
plt.imshow(hit_or_miss, cmap='gray')
plt.title('Object to detect')
plt.show()

# Display the original image with horizontal lines of minimum length 6 pixels
tb1 = cv2.erode(t, b1, iterations=1)
plt.imshow(tb1, cmap='gray')
plt.title('Horizontal lines with min. 6 pixels length')
plt.show()
(2) A12_Region_filling

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

# Load the image


n = cv2.imread(‘nicework.tif', cv2.IMREAD_GRAYSCALE)
n = cv2.threshold(n, 128, 255, cv2.THRESH_BINARY)[1]

# Display the original image


plt.imshow(n, cmap='gray')
plt.title('Input image')
plt.show()

# Define structuring element


sq = np.ones((3, 3), np.uint8)

# Image boundary
nb = np.bitwise_and(n, ~cv2.erode(n, sq, iterations=1))

# Display the image boundary


plt.imshow(nb, cmap='gray')
plt.title('Image boundary')
plt.show()

# Filling of Character at loc. (30, 20)


nf = cv2.floodFill(nb.copy(), None, (20, 30), 255)[1]

# Display the filling result


plt.imshow(nf, cmap='gray')
plt.title('Filling of Character at loc. (30,20)')
plt.show()

# Combine filled and boundary images


result_image = np.bitwise_or(nf, nb)

# Display the result


plt.imshow(result_image, cmap='gray')
plt.title('N filled')
plt.show()
(3) A13_Skeletonization

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

# Load the image


n = cv2.imread(‘nicework.tif', cv2.IMREAD_GRAYSCALE)

# Display the input image


plt.imshow(n, cmap='gray')
plt.title('Input image')
plt.show()

# Convert the image to binary


n = cv2.threshold(n, 128, 255, cv2.THRESH_BINARY)[1]

# Display the binary image


plt.imshow(n, cmap='gray')
plt.title('Binary image')
plt.show()

# Define structuring elements


sq = np.ones((3, 3), dtype=np.uint8)
cr = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]], dtype=np.uint8)

# Skeletonization using morphological operations


nk = cv2.erode(n, sq, iterations=1)

# Display skeletonization result


plt.imshow(nk, cmap='gray')
plt.title('Skeletonization using morphological operations')
plt.show()

# Skeletonization using cross SE


nk2 = cv2.erode(n, cr, iterations=1)

# Display skeletonization result using cross SE


plt.imshow(nk2, cmap='gray')
plt.title('Skeletonization using cross SE')
plt.show()
(4) A14_Thresholding

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

# Load the rice image


r = cv2.imread(rice.PNG')
r = cv2.cvtColor(r, cv2.COLOR_BGR2GRAY)

# Display the rice image with dark background


plt.imshow(r, cmap='gray')
plt.title('Rice image with dark background')
plt.show()

# Threshold the rice image


thresholded_rice = r > 110
plt.imshow(thresholded_rice, cmap='gray')
plt.title('Thresholded Rice image')
plt.show()

# Load the bacteria image with additional check


b = cv2.imread(r'C:\Users\Sumant\Documents\Data Science
Learning\Class\DIP\DIP Lab Assignments\bacteria.tif')

if b is None:
print("Error: Could not load the bacteria image.")
else:
b = cv2.cvtColor(b, cv2.COLOR_BGR2GRAY)

# Display the bacteria image with light background


plt.imshow(b, cmap='gray')
plt.title('Bacteria image with light background')
plt.show()

# Threshold the bacteria image


thresholded_bacteria = b > 100
plt.imshow(thresholded_bacteria, cmap='gray')
plt.title('Thresholded Bacteria image')
plt.show()

# Load the spine image with corrected unpacking


x = plt.imread(spine.tif')
s = cv2.cvtColor((x * 255).astype(np.uint8), cv2.COLOR_BGR2GRAY)

# Display the spine image


plt.imshow(s, cmap='gray')
plt.title('Spine image')
plt.show()

# Double threshold the spine image


double_thresholded_spine = (s > 115) & (s < 125)
plt.imshow(double_thresholded_spine, cmap='gray')
plt.title('Double thresholded spine image')
plt.show()
(5) A15_Adaptive_thresholding

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

# Load the image


c = cv2.imread(circles_t.png')
c = cv2.cvtColor(c, cv2.COLOR_BGR2GRAY)

# Generate x values
x = np.tile(np.arange(1, 271), (270, 1))

# Display the input image


plt.imshow(c, cmap='gray')
plt.title('Input image')
plt.show()

# Perform the specified operations


c2 = c.astype(float) * (x / 2 + 50) + (1 - c.astype(float)) * (x / 2)
c3 = np.uint8(255 * np.clip((c2 - np.min(c2)) / (np.max(c2) - np.min(c2)), 0, 1))
t, ct = cv2.threshold(c3, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)

# Display the thresholded attempt


plt.imshow(ct, cmap='gray')
plt.title('Thresholding attempt: ct')
plt.show()

# Divide the image into four parts and perform adaptive thresholding
num_splits = 4
split_width = c3.shape[1] // num_splits

# Use a loop to handle the uneven division


split_images = [c3[:, i * split_width : (i + 1) * split_width] for i in
range(num_splits)]

# Apply thresholding to each split


thresholded_splits = [cv2.threshold(split, 0, 255, cv2.THRESH_BINARY +
cv2.THRESH_OTSU)[1] for split in split_images]

# Display the adaptive thresholded image


plt.imshow(np.hstack(thresholded_splits), cmap='gray')
plt.title('Adaptive Thresholded image')
plt.show()

# Adaptive thresholding using blkproc


def adaptive_thresholding(x):
return cv2.threshold(x, 0, 255, cv2.THRESH_BINARY +
cv2.THRESH_OTSU)[1]

c4 = np.zeros_like(c3)
for i in range(num_splits):
start_col = i * split_width
end_col = (i + 1) * split_width
c4[:, start_col:end_col] = adaptive_thresholding(c3[:, start_col:end_col])

# Display the adaptive thresholded image using blkproc


plt.imshow(c4, cmap='gray')
plt.title('Adaptive thresholding using blkproc')
plt.show()
(6) A16_Edge_Detection

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

# Load the image


ic = cv2.imread(circuit.png')
ic = cv2.cvtColor(ic, cv2.COLOR_BGR2GRAY)

# Display the original image


plt.imshow(ic, cmap='gray')
plt.title('Circuit image')
plt.show()

# Prewitt filter for detecting vertical edges


px = np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0, 1]], dtype=float)
icx = cv2.filter2D(ic, -1, px)
plt.imshow(icx / 255, cmap='gray')
plt.title('Prewitt filter for detecting vertical edges')
plt.show()

# Prewitt filter for detecting horizontal edges


py = np.transpose(px)
icy = cv2.filter2D(ic, -1, py)
plt.imshow(icy / 255, cmap='gray')
plt.title('Prewitt filter for detecting horizontal edges')
plt.show()

# Prewitt edge detection using filters


edge_p = np.sqrt(icx**2 + icy**2)
plt.imshow(edge_p / 255, cmap='gray')
plt.title('Prewitt edge detection using filters')
plt.show()

# Binary image from Prewitt edge detection


edge_t = cv2.threshold((edge_p * 255).astype(np.uint8), 0.3 * 255, 255,
cv2.THRESH_BINARY)[1]

# Display the binary image


plt.imshow(edge_t, cmap='gray')
plt.title('Its binary image')
plt.show()

# Prewitt edge using function


edge_p = cv2.Canny(ic, 100, 200)
plt.imshow(edge_p, cmap='gray')
plt.title('Prewitt edge (using function)')
plt.show()

# Roberts edge
edge_r = cv2.filter2D(ic, -1, np.array([[1, 0], [0, -1]], dtype=float))
plt.imshow(edge_r, cmap='gray')
plt.title('Roberts edge')
plt.show()

# Sobel edge
edge_s = cv2.Sobel(ic, -1, 1, 0, ksize=3)
plt.imshow(edge_s, cmap='gray')
plt.title('Sobel edge')
plt.show()

# Canny edge
edge_c = cv2.Canny(ic, 50, 150)
plt.imshow(edge_c, cmap='gray')
plt.title('Canny edge')
plt.show()
(7) A17_Second_order

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

# Load the image


ic = cv2.imread(circuit.png')
ic = cv2.cvtColor(ic, cv2.COLOR_BGR2GRAY)

# Display the original image


plt.imshow(ic, cmap='gray')
plt.title('Circuit image')
plt.show()

# Edge using discrete Laplacian filter


laplacian_filter = np.array([[0, 1, 0], [1, -4, 1], [0, 1, 0]], dtype=float)
ic_l = cv2.filter2D(ic, -1, laplacian_filter)
plt.imshow(cv2.normalize(ic_l, None, 0, 255, cv2.NORM_MINMAX),
cmap='gray')
plt.title('Edge using discrete Laplacian filter')
plt.show()

# Edge using Zerocrossing filter


icz = cv2.Canny(ic, 100, 200)
plt.imshow(icz, cmap='gray')
plt.title('Edge using Zerocrossing filter')
plt.show()

# Edge using Laplacian of Gaussian filter


log_filter = cv2.GaussianBlur(ic, (13, 13), 2)
lge = cv2.Canny(log_filter, 100, 200)
plt.imshow(lge, cmap='gray')
plt.title('Edge using Laplacian of Gaussian filter')
plt.show()
(8) A18_Watershed_seg

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

# Load the image


f = cv2.imread(rice.PNG', cv2.IMREAD_GRAYSCALE)

# Sobel filter
h = cv2.getDerivKernels(1, 0, 3, normalize=True)
g_x = cv2.filter2D(f, cv2.CV_64F, h[0] @ h[1].T)
g_y = cv2.filter2D(f, cv2.CV_64F, h[1] @ h[0].T)
g = np.sqrt(g_x**2 + g_y**2)

# Convert the gradient magnitude image to 8-bit unsigned integer


g_uint8 = cv2.normalize(g, None, 0, 255,
cv2.NORM_MINMAX).astype(np.uint8)

# Watershed segmentation
ret, markers = cv2.threshold(g_uint8, 0, 255, cv2.THRESH_BINARY +
cv2.THRESH_OTSU)
markers = cv2.connectedComponents(markers)[1]

# Convert the grayscale image to 3-channel format


f_rgb = cv2.cvtColor(f, cv2.COLOR_GRAY2BGR)

# Watershed segmentation on the 3-channel image


L = cv2.watershed(f_rgb, markers)
wr = (L == -1)

# Display the watershed segmentation


plt.imshow(L, cmap='jet')
plt.title('Watershed segmentation')
plt.show()

# Display the over-segmented image


f_rgb[wr] = [255, 0, 0] # Mark over-segmented regions in red
plt.imshow(cv2.cvtColor(f_rgb, cv2.COLOR_BGR2RGB))
plt.title('Over-segmented image')
plt.show()
(9) A19_Hough_Transform

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

# Load the image


I = cv2.imread(circuit.png, cv2.IMREAD_GRAYSCALE)

# Rotate the image


rotI = cv2.rotate(I, cv2.ROTATE_90_COUNTERCLOCKWISE)

# Display the rotated image


plt.imshow(rotI, cmap='gray')
plt.show()

# Apply Canny edge detection


BW = cv2.Canny(rotI, 50, 150)

# Display the Canny edge image


plt.imshow(BW, cmap='gray')
plt.show()

# Perform Hough Transform


lines = cv2.HoughLinesP(BW, 1, np.pi / 180, threshold=50, minLineLength=50,
maxLineGap=10)

# Display the original image with detected lines


plt.imshow(rotI, cmap='gray')
plt.title('Detected Lines')
plt.axis('off')

# Plot the detected lines


if lines is not None:
for line in lines:
x1, y1, x2, y2 = line[0]
plt.plot([x1, x2], [y1, y2], linewidth=2, color='green')
plt.plot(x1, y1, 'x', linewidth=2, markersize=8, color='yellow')
plt.plot(x2, y2, 'x', linewidth=2, markersize=8, color='red')

plt.show()
(10) A20_Templete

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

def rot90(mat, k):


return np.rot90(mat, k)

# Load the image


bw = cv2.imread(text.JPG', cv2.IMREAD_GRAYSCALE)

# Extract a region of interest (ROI)


a = bw[31:45, 87:99]

# Display the original image and the ROI


plt.imshow(bw, cmap='gray')
plt.title('Original Image')
plt.show()

plt.imshow(a, cmap='gray')
plt.title('ROI (a)')
plt.show()

# Perform cross-correlation
C = cv2.filter2D(bw.astype(float), -1, rot90(a, 2).astype(float),
borderType=cv2.BORDER_CONSTANT)

# Display the cross-correlation result


plt.imshow(C, cmap='gray')
plt.title('Cross-correlation Result')
plt.show()

# Thresholding
thresh = 60
binary_result = (C > thresh).astype(np.uint8)

# Display pixels over the threshold


plt.imshow(binary_result, cmap='gray')
plt.title('Pixels Over Threshold')
plt.show()

You might also like