Dip Lab File 34
Dip Lab File 34
), भारत
MADHAV INSTITUTE OF TECHNOLOGY & SCIENCE, GWALIOR (M.P.), INDIA
Deemed to be University
(Declared under Distinct Category by Ministry of Education, Government of India)
NAAC ACCREDITED WITH A++ GRADE
Lab report
On
Digital Image Processing (2150601)
Submitted By
Shikhar Gautam
0901CS221125
6th Semester
CSE 3rd Year
Submitted To:
Prof. Jaimala Jha, Assistant Professor
Dr. Rohit Agrawal, Assistant Professor
Jan-June 2025
1

प्रौ
द्यो
गि
की
वि
ज्ञा
स्था
ग्वा
लि
प्र
1
Index
S. No. Name of the Program Date Page No. Signature
1
Experiment-1
Aim: Program to read an image and display it on the screen.
Implementation code:
import cv2
Output:
4


Experiment-2
Aim: Program to determine image negative
Implementation:
The negative of an image is created by inverting the pixel values. For a grayscale image, this
means subtracting each pixel value from the maximum possible value (255 for 8-bit images).
For color images, we invert each channel (R, G, B) separately.
Implementation code:
import cv2
import cv2
import numpy as np
if image is None:
print("Error: Could not read the image.")
else:
# Calculate negative using numpy
negative = np.invert(image)
# Display results
cv2.imshow('Original', image)
cv2.imshow('Negative', negative)
cv2.waitKey(0)
cv2.destroyAllWindows()
Output:
6

Experiment-3
Aim: Read an image and perform different filtering operations (Average, Median etc.)
Implementation code:
import cv2
import numpy as np
from matplotlib import pyplot as plt
def apply_filters(image_path):
# Read the image
img = cv2.imread(image_path)
if img is None:
print("Error: Could not read the image.")
return
7


avg_kernel = np.ones((5,5), np.float32)/25
avg_filtered = cv2.filter2D(img_rgb, -1, avg_kernel)
# 2. Median Filter
median_filtered = cv2.medianBlur(img_rgb, 5)
# 3. Gaussian Filter
gaussian_filtered = cv2.GaussianBlur(img_rgb, (5,5), 0)
8

plt.subplot(2, 3, 4), plt.imshow(gaussian_filtered)
plt.title('Gaussian Filter (5x5)'), plt.axis('off')
plt.tight_layout()
plt.show()
# Usage
image_path = 'your_image.jpg' # Replace with your image path
apply_filters(image_path)
Output:
9


Experiment-4
Implementation code:
import cv2
import numpy as np
10

:param kernel_size: size of the motion kernel (odd number)
:param angle: direction of motion blur in degrees (0=horizontal)
“””
# Read the image
img = cv2.imread(image_path)
if img is None:
print(“Error: Could not read the image.”)
return
for I in range(kernel_size):
offset = round(center * sin_val * (I – center) / center)
j = center + offset
if 0 <= j < kernel_size:
kernel[I, j] = 1
# Example usage
create_motion_blur(‘input.jpg’, ‘motion_blur_output.jpg’, kernel_size=30, angle=45)
angle_rad = np.radians(angle)
dx = np.cos(angle_rad)
12

dy = np.sin(angle_rad)
# Example usage
photographic_motion_blur(‘input.jpg’, ‘photographic_motion_blur.jpg’, intensity=15,
angle=30)
13

import cv2
import numpy as np
cv2.imwrite(output_path, motion_blur)
cv2.imshow(‘Motion Blur’, motion_blur)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Example usage
simple_motion_blur(‘input.jpg’, ‘simple_motion_blur.jpg’, blur_amount=30,
direction=’horizontal’)
14

Output:
Experiment-5
Implementation code:
import cv2
import numpy as np
15


def gray_level_slicing_no_bg(image_path, lower_thresh, upper_thresh, output_path=None):
"""
Perform gray level slicing without background
:param image_path: Path to input image
:param lower_thresh: Lower threshold of intensity range (0-255)
:param upper_thresh: Upper threshold of intensity range (0-255)
:param output_path: Optional path to save output image
"""
# Read image in grayscale
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if img is None:
print("Error: Could not read the image.")
return None
# Display results
cv2.imshow('Original Image', img)
cv2.imshow('Gray Level Slicing (Without Background)', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
16

return result
# Example usage
output = gray_level_slicing_no_bg('input.jpg', 100, 200, 'sliced_output.jpg')
import cv2
import numpy as np
def advanced_gray_slicing_no_bg(image_path, ranges, output_path=None):
"""
Advanced gray level slicing with multiple ranges
:param image_path: Path to input image
:param ranges: List of (lower, upper) threshold tuples
:param output_path: Optional path to save output image
"""
# Read image
img = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if img is None:
print("Error: Could not read the image.")
return None
# Initialize result array with zeros
result = np.zeros_like(img)
17

# Display results
cv2.imshow('Original', img)
cv2.imshow('Gray Level Slicing', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Save output if path provided
if output_path:
cv2.imwrite(output_path, result)
return result
# Example usage with multiple ranges
ranges = [(50, 100), (150, 200)] # Two intensity ranges to preserve
output = advanced_gray_slicing_no_bg('input.jpg', ranges, 'advanced_sliced.jpg')
Output:
Experiment-6
Aim: Program to perform brightness enhancement and brightness suppression of an image
Implementation code:
import cv2
18


import numpy as np
# Brightness enhancement
enhanced = np.clip(img_float * enhancement_factor, 0, 1)
enhanced = (enhanced * 255).astype(np.uint8)
# Brightness suppression
suppressed = np.clip(img_float * suppression_factor, 0, 1)
suppressed = (suppressed * 255).astype(np.uint8)
# Display results
cv2.imshow('Original Image', img)
cv2.imshow(f'Enhanced (x{enhancement_factor})', enhanced)
cv2.imshow(f'Suppressed (x{suppression_factor})', suppressed)
cv2.waitKey(0)
cv2.destroyAllWindows()
19

return enhanced, suppressed
# Example usage
enhanced, suppressed = adjust_brightness('input.jpg', enhancement_factor=1.8,
suppression_factor=0.4)
import cv2
import numpy as np
20

suppressed = np.clip(suppressed * 255, 0, 255).astype(np.uint8)
# Display results
cv2.imshow('Original Image', img)
cv2.imshow(f'Enhanced (γ={gamma_enhance})', enhanced)
cv2.imshow(f'Suppressed (γ={gamma_suppress})', suppressed)
cv2.waitKey(0)
cv2.destroyAllWindows()
# Example usage
enhanced, suppressed = gamma_adjustment('input.jpg', gamma_enhance=0.4,
gamma_suppress=2.5)
import cv2
import numpy as np
def histogram_based_adjustment(image_path):
"""
Brightness adjustment using histogram equalization techniques
"""
img = cv2.imread(image_path)
if img is None:
print("Error: Could not read the image.")
return
21

# Enhance brightness (CLAHE - Contrast Limited Adaptive Histogram Equalization)
yuv_enhanced = yuv.copy()
clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))
yuv_enhanced[:,:,0] = clahe.apply(yuv_enhanced[:,:,0])
enhanced = cv2.cvtColor(yuv_enhanced, cv2.COLOR_YUV2BGR)
# Display results
cv2.imshow('Original Image', img)
cv2.imshow('Enhanced (CLAHE)', enhanced)
cv2.imshow('Suppressed (Hist Equalization + Dimming)', suppressed)
cv2.waitKey(0)
cv2.destroyAllWindows()
return enhanced, suppressed
# Example usage
enhanced, suppressed = histogram_based_adjustment('input.jpg')
Output:
22


Experiment-7
Aim: To create a vision program to find histogram value and display histograph of a
grayscale and color image.
Implementation code:
import cv2
import numpy as np
import matplotlib.pyplot as plt
def analyze_histograms(image_path):
"""
Analyze and display histograms for grayscale and color images
:param image_path: Path to input image
"""
# Read the image
img = cv2.imread(image_path)
if img is None:
print("Error: Could not read the image.")
return
# Convert to RGB for color histogram display
img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# Create a figure with subplots
plt.figure(figsize=(15, 10))
# Display original image
plt.subplot(2, 2, 1)
plt.imshow(img_rgb)
plt.title('Original Image')
plt.axis('off')
# Grayscale histogram
23

plt.subplot(2, 2, 2)
gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
hist_gray = cv2.calcHist([gray_img], [0], None, [256], [0, 256])
plt.plot(hist_gray, color='black')
plt.title('Grayscale Histogram')
plt.xlabel('Pixel Intensity')
plt.ylabel('Frequency')
plt.xlim([0, 256])
# Cumulative histogram
plt.subplot(2, 2, 4)
cum_hist = np.cumsum(hist_gray)
plt.plot(cum_hist, color='purple')
plt.title('Cumulative Grayscale Histogram')
plt.xlabel('Pixel Intensity')
plt.ylabel('Cumulative Frequency')
plt.xlim([0, 256])
24

plt.tight_layout()
plt.show()
# Example usage
analyze_histograms('your_image.jpg')
Ouput:
25


Experiment-8
Implementation code:
import cv2
import numpy as np
import matplotlib.pyplot as plt
def rgb_threshold_segmentation(image_path):
"""
Perform threshold-based segmentation on an RGB image
:param image_path: Path to input RGB image
"""
# Read the image
img = cv2.imread(image_path)
if img is None:
print("Error: Could not read the image.")
return
26


# Split into individual channels
channels = cv2.split(img)
channel_names = ['Blue', 'Green', 'Red']
# Otsu's threshold
_, otsu_thresh = cv2.threshold(channel, 0, 255,
cv2.THRESH_BINARY+cv2.THRESH_OTSU)
plt.subplot(3, 4, i*4 + 4)
plt.imshow(otsu_thresh, cmap='gray')
plt.title(f'{name} Otsu Thresh')
plt.axis('off')
plt.tight_layout()
plt.show()
plt.subplot(1, 2, 2)
plt.imshow(segmented_rgb)
plt.title('Segmented RGB (Otsu per channel)')
plt.axis('off')
plt.tight_layout()
plt.show()
# Example usage
rgb_threshold_segmentation('your_image.jpg')
28

Output:
Experiment-9
Aim: Read a colour image and separate the colour image into red green and blue planes.
Implementation code:
import cv2
import numpy as np
import matplotlib.pyplot as plt
def separate_color_channels(image_path):
"""
Separate a color image into its RGB components and display them
:param image_path: Path to input color image
"""
# Read the image
img = cv2.imread(image_path)
29


if img is None:
print("Error: Could not read the image.")
return
# Split the image into its three channels (BGR order in OpenCV)
blue_ch, green_ch, red_ch = cv2.split(img)
plt.subplot(2, 3, 6)
plt.imshow(green_ch, cmap='gray')
plt.title('Green Channel (Grayscale)')
plt.axis('off')
plt.tight_layout()
plt.show()
# Example usage
blue, green, red = separate_color_channels('your_image.jpg')
Output:
Experiment-10
Implementation code:
import cv2
import numpy as np
import matplotlib.pyplot as plt
32


:param gamma: Gamma value (γ > 1 darkens, γ < 1 brightens)
"""
# Read the image
img = cv2.imread(image_path)
if img is None:
print("Error: Could not read the image.")
return
# Display results
plt.figure(figsize=(12, 6))
plt.subplot(1, 2, 1)
plt.imshow(img_rgb)
plt.title(f'Original Image (γ=1.0)')
plt.axis('off')
plt.subplot(1, 2, 2)
plt.imshow(corrected_rgb)
33

plt.title(f'Gamma Corrected (γ={gamma})')
plt.axis('off')
plt.tight_layout()
plt.show()
return gamma_corrected
# Example usage
gamma_value = 0.5 # Try values: 0.5 (brighten), 1.0 (no change), 2.0 (darken)
corrected_image = apply_gamma_correction('your_image.jpg', gamma=gamma_value)
Output:
Experiment-11
import cv2
import numpy as np
import matplotlib.pyplot as plt
def image_conversion_demo(image_path):
"""
34


Demonstrate various image conversion techniques
:param image_path: Path to input image
"""
# Read the image
img = cv2.imread(image_path)
if img is None:
print("Error: Could not read the image.")
return
# 1. Original Image
plt.subplot(3, 4, 1)
plt.imshow(img_rgb)
plt.title('Original RGB Image')
plt.axis('off')
# 2. Grayscale Conversion
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
plt.subplot(3, 4, 2)
plt.imshow(gray, cmap='gray')
plt.title('Grayscale')
plt.axis('off')
# 6. Binary Threshold
_, binary = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
plt.subplot(3, 4, 6)
plt.imshow(binary, cmap='gray')
plt.title('Binary Threshold')
plt.axis('off')
# 7. Otsu's Threshold
_, otsu = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
plt.subplot(3, 4, 7)
plt.imshow(otsu, cmap='gray')
36

plt.title("Otsu's Threshold")
plt.axis('off')
# 8. Adaptive Threshold
adaptive = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)
plt.subplot(3, 4, 8)
plt.imshow(adaptive, cmap='gray')
plt.title('Adaptive Threshold')
plt.axis('off')
# Example usage
image_conversion_demo('your_image.jpg')
Output :
38

Experiment-12
39


Aim: To create a color image and perform read and write operation.
Implementation code:
import cv2
import numpy as np
40

Output:
41



Experiment-13
import cv2
import numpy as np
42

# Step 5: Blend watermark with original image
for c in range(3): # Loop over B, G, R channels
original[y_offset:y_offset+wm_h, x_offset:x_offset+wm_w, c] = \
(1 - alpha) * original[y_offset:y_offset+wm_h, x_offset:x_offset+wm_w, c] + \
alpha * wm_bgr[:, :, c]
Output:
43


Experiment-14
import cv2
import numpy as np
44

wm_bgr = watermark
alpha = np.ones((wm_h, wm_w), dtype=np.float32) # If no alpha, set full opacity
Output:
• The final image will have a watermark blended at the bottom-right corner.
45

46