DIP Manual
DIP Manual
March 7, 2025
1.Program to display an image as grayscale image, RED, BLUE, GREEN image and also display
the 1D convolution and 2D convolution on an image.
[ ]: import cv2
import numpy as np
import matplotlib.pyplot as plt
# Apply convolutions
conv_1d = cv2.filter2D(gray, -1, kernel_1d)
conv_2d = cv2.filter2D(gray, -1, kernel_2d)
# Display images
plt.figure(figsize=(10, 6))
for i, (img, title, cmap) in enumerate(zip(images, titles, cmaps), 1):
plt.subplot(3, 3, i) # Arrange in 3x3 grid
plt.imshow(img, cmap=cmap) # Apply respective colormap
plt.title(title), plt.axis('off') # Add title & remove axes
plt.tight_layout()
1
plt.show()
2.Program to perform the basic arithmetic and logical operations on the images.
[ ]: import cv2
import numpy as np
from matplotlib import pyplot as plt
2
# Convert images to float32 for division operation
img1 = img1.astype(np.float32)
img2 = img2.astype(np.float32)
plt.figure(figsize=(12, 12))
for i in range(len(images)):
plt.subplot(4, 3, i+1) # Changed grid to fit original images
plt.imshow(cv2.cvtColor(images[i], cv2.COLOR_BGR2RGB))
plt.title(titles[i])
plt.xticks([]), plt.yticks([])
plt.tight_layout()
plt.show()
3
3.Execute the following Gray Scale Transformations on the given image:Negative Transformation,
Log Transformation,Power-Log Transformation and contraststrecting.
# Define transformations
c, gamma = 255 / np.log(1 + 255), 0.5 # Log and gamma correction constants
r_values = np.arange(256, dtype=np.uint8)
4
# Contrast Stretching - Piecewise Linear
r1, s1, r2, s2 = 50, 0, 200, 255
contrast_map = np.array([s1 / r1 * r if r < r1 else
(s2 - s1) / (r2 - r1) * (r - r1) + s1 if r <= r2 else
(255 - s2) / (255 - r2) * (r - r2) + s2 for r in␣
↪range(256)], dtype=np.uint8)
contrast_stretched = contrast_map[image]
plt.tight_layout()
plt.show()
5
4.Program to perform Bit-Plane Slicing.
[ ]: import cv2
import numpy as np
import matplotlib.pyplot as plt
6
# Load image & convert to grayscale
gray = cv2.cvtColor(cv2.imread('/content/uvce.jpeg'), cv2.COLOR_BGR2GRAY)
# Extract bit planes (0-7) using bitwise AND & normalize for visualization
bit_planes = [(np.bitwise_and(gray, 2**i) > 0) * 255 for i in range(8)] #␣
↪Convert bits to 0 or 255
plt.tight_layout()
plt.show() # Display the images
7
[68]: import cv2
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(8, 8))
plt.tight_layout()
plt.show()
8
6.Program for smoothing an image using low pass filter and high pass filter in frequency domain.
9
1 / (1 + (D / cutoff)**(2 * order)) # Butterworth
return np.abs(np.fft.ifft2(np.fft.ifftshift(np.fft.fftshift(np.fft.
↪fft2(img)) * (1 - H if f_type == 'highpass' else H))))
plt.figure(figsize=(12, 22))
plt.tight_layout()
plt.show()
10
7.Write a program to perform low pass filtering and high pass filtering on an image in spacial
domain.
11
# Define filters
kernel = np.ones((3, 3), np.uint8)
filters = [
("Original", img),
("Mean Filter (AF/MF)", cv2.blur(img, (5, 5))),
("Weighted Avg Filter (WAF)", cv2.filter2D(img, -1, np.array([[1, 2, 1],␣
↪[2, 4, 2], [1, 2, 1]]) / 16)),
for i in range(6):
name, filtered = filters[i]
# Image
plt.subplot(3, 4, 2 * i + 1)
plt.imshow(filtered, cmap='gray')
plt.title(name)
plt.axis('off')
# Histogram
plt.subplot(3, 4, 2 * i + 2)
plt.hist(filtered.ravel(), bins=100, range=[0, 256], color='black')
plt.title(f"Histogram - {name}")
plt.xlim([0, 256])
plt.tight_layout()
plt.show()
12
8.Program to observe the effect of median filter on an image corrupted by salt and pepper.
[ ]: import cv2
import matplotlib.pyplot as plt
# Image
plt.subplot(1, 2, 1)
plt.imshow(images[i], cmap='gray')
13
plt.title(titles[i])
plt.axis('off')
# Histogram
plt.subplot(1, 2, 2)
plt.hist(images[i].ravel(), bins=256, range=[0, 256], color='black')
plt.title(f"Histogram of {titles[i]}")
plt.xlabel("Pixel Intensity")
plt.ylabel("Frequency")
plt.show()
14
9.Program to show image Enhancement using various filters like ‘SOBEL’, ‘PREWITT’ and
‘LAPLACIAN’.
plt.subplot(10, 4, 2 * i + 2)
15
plt.hist(img.ravel(), bins=50, range=(0, 255), color='black')
plt.title(f"Histogram of {title}", fontsize=10)
plt.xlim([0, 255])
16
17
10.Program to sharpen an image using 2D Laplacian high pass filter in spacial domain.
for i in range(2):
plt.figure(figsize=(10, 5))
for j, data in enumerate([images[i], images[i].ravel()]):
plt.subplot(1, 2, j + 1)
plt.imshow(data, cmap='gray') if j == 0 else plt.hist(data, bins=256,␣
↪color='black')
18
11.Program for morphological image operations: erosion, dilation, opening and closing.
import cv2
import numpy as np
import matplotlib.pyplot as plt
plt.figure(figsize=(12, 6))
19
for i, (img, title) in enumerate(zip(images, titles), 1):
plt.subplot(2, 3, i)
if img is None: # Display structuring element as a table
plt.axis("off")
plt.table(cellText=kernel.tolist(), cellLoc='center', loc='center')
else:
plt.imshow(img, cmap='gray')
plt.axis("off")
plt.title(title)
plt.tight_layout()
plt.show()
20
# 2. Discontinuities Based Segmentation (Point, Line & Edge Detection)
sobel_x = cv2.convertScaleAbs(cv2.Sobel(image, cv2.CV_16S, 1, 0, ksize=3))
sobel_y = cv2.convertScaleAbs(cv2.Sobel(image, cv2.CV_16S, 0, 1, ksize=3))
prewitt_x = cv2.filter2D(image, -1, np.array([[-1, 0, 1], [-1, 0, 1], [-1, 0,␣
↪1]]))
prewitt_y = cv2.filter2D(image, -1, np.array([[-1, -1, -1], [0, 0, 0], [1, 1,␣
↪1]]))
21
"Sobel Vertical Edges", "Sobel Horizontal Edges",
"Prewitt Vertical Edges", "Prewitt Horizontal Edges",
"Laplacian (All Edges)",
"Laplacian (Vertical Lines)", "Laplacian (Horizontal Lines)",
"Laplacian (Diagonal +45°)", "Laplacian (Diagonal -45°)",
"Canny Edge-Line Based", "Harris Corner-Point Based",
"Region Growing", "Region Splitting"
]
images = [image, global_thresh, sobel_x, sobel_y, prewitt_x, prewitt_y,␣
↪laplacian] + laplacians + [canny_edges, harris_corners, region_growing,␣
↪region_splitting]
# Display Results
plt.figure(figsize=(14, 45))
for i, (img, title) in enumerate(zip(images, titles)):
plt.subplot(len(images), 4, 2*i+1), plt.imshow(img, cmap="gray"), plt.
↪title(title), plt.axis("off")
plt.tight_layout()
plt.show()
22
23
13.Program for image Watermarking.
# Example usage
add_text_watermark("/content/uvce.jpeg", "watermarked.jpeg", "UVCE")
24
14.Program for Image Restoration.
[ ]: import cv2
import matplotlib.pyplot as plt
plt.show()
# Example usage
restore_image("/content/sp_img_gray_noise_white.png", ksize=3)
25
[ ]: import cv2
import numpy as np
import matplotlib.pyplot as plt
h, w = img.shape
comp = np.zeros_like(img)
# Display results
titles = [f"Original ({orig_size:.2f} KB)", f"BTC Compressed ({comp_size:.
↪2f} KB)"]
# Example Usage
btc_compress(r'/content/uvce.jpeg')
[ ]: import cv2
import matplotlib.pyplot as plt
26
def edge_detection(image_path, low, high):
img = cv2.imread(image_path, 0) # Load the image in grayscale
edges = cv2.Canny(cv2.GaussianBlur(img, (5, 5), 1.4), low, high) # Apply␣
↪Gaussian blur & then Canny edge detection
plt.show()
27