KEMBAR78
Dip Lab File 34 | PDF | Digital Signal Processing | Imaging
0% found this document useful (0 votes)
189 views46 pages

Dip Lab File 34

This lab report on Digital Image Processing from Madhav Institute of Technology & Science includes various experiments conducted by Shikhar Gautam. Each experiment focuses on different image processing techniques such as reading images, creating negatives, applying filters, and enhancing brightness. The report outlines the aims, implementation codes, and expected outputs for each experiment conducted in the course.

Uploaded by

changertime3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
189 views46 pages

Dip Lab File 34

This lab report on Digital Image Processing from Madhav Institute of Technology & Science includes various experiments conducted by Shikhar Gautam. Each experiment focuses on different image processing techniques such as reading images, creating negatives, applying filters, and enhancing brightness. The report outlines the aims, implementation codes, and expected outputs for each experiment conducted in the course.

Uploaded by

changertime3
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 46

माधव एवं न सं न, यर (म. .

), भारत
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

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


MADHAV INSTITUTE OF TECHNOLOGY & SCIENCE
GWALIOR - 474005 (MP) est. 1957

Jan-June 2025

1

प्रौ
द्यो
गि
की
वि
ज्ञा
स्था
ग्वा
लि
प्र
1
Index
S. No. Name of the Program Date Page No. Signature

Program to read an image and display it on the 13/01/25 3.


screen.
Program to determine image negative. 13/01/25 4-5.

Read an image and perform different filtering 20/01/25 6-8.


operations (Average, Median etc.)
Program to create motion blur. 27/01/25 9-13.

Program performs gray level slicing without 27/01/25 14-16.


background.
Program to perform brightness enhancement and 03/02/25 17-20.
brightness suppression of an image.
To create a vision program to find histogram value 03/02/25 21-23.
and display histograph of a grayscale and color
image.
Read an RGB image and segment it using 03/02/25 24-26.
threshold method.
Read a colour image and separate the colour image 10/02/25 27-29.
into red green and blue planes

Perform gamma correction for the given colour 24/02/25 30-31.


image.

Program to perform different image conversion 03/03/25 32-36.


techniques

To create a color image and perform read and 17/03/25 37-38.


write operation

Code to implement watermarking in spatial 17/03/25 39-40.


domain.

Code to generate different levels of Gaussian 24/03/25 41-42.


Pyramid.

1
Experiment-1
Aim: Program to read an image and display it on the screen.

Implementation code:

import cv2

# Read an image from file


image_path = 'your_image.jpg' # Replace with your image path
image = cv2.imread(image_path)

# Check if image was loaded successfully


if image is None:
print("Error: Could not read the image.")
else:
# Display the image in a window
cv2.imshow('Image Display', image)

# Wait for a key press and then close the window


cv2.waitKey(0)
cv2.destroyAllWindows()

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:

Using OpenCV (cv2)

import cv2

# Read the image


image = cv2.imread('your_image.jpg')

# Check if image was loaded successfully


if image is None:
print("Error: Could not read the image.")
else:
# Calculate the negative
negative = 255 - image

# Display both original and negative images


cv2.imshow('Original Image', image)
cv2.imshow('Negative Image', negative)

# Wait for a key press and then close windows


cv2.waitKey(0)
cv2.destroyAllWindows()
5

# Optionally save the negative image
cv2.imwrite('negative_image.jpg', negative)
Using NumPy (Alternative Approach)

import cv2
import numpy as np

# Read the image


image = cv2.imread('your_image.jpg')

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

# Convert to RGB for matplotlib display


img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# 1. Average (Mean) Filter

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)

# 4. Bilateral Filter (preserves edges)


bilateral_filtered = cv2.bilateralFilter(img_rgb, 9, 75, 75)

# 5. Sobel Edge Detection (as an example of another filter)


gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5)
sobel_combined = np.sqrt(sobelx**2 + sobely**2)
sobel_combined = cv2.normalize(sobel_combined, None, 0, 255, cv2.NORM_MINMAX,
cv2.CV_8U)

# Display all results


plt.figure(figsize=(15, 10))

plt.subplot(2, 3, 1), plt.imshow(img_rgb)


plt.title('Original Image'), plt.axis('off')

plt.subplot(2, 3, 2), plt.imshow(avg_filtered)


plt.title('Average Filter (5x5)'), plt.axis('off')

plt.subplot(2, 3, 3), plt.imshow(median_filtered)


plt.title('Median Filter (5x5)'), plt.axis('off')

8

plt.subplot(2, 3, 4), plt.imshow(gaussian_filtered)
plt.title('Gaussian Filter (5x5)'), plt.axis('off')

plt.subplot(2, 3, 5), plt.imshow(bilateral_filtered)


plt.title('Bilateral Filter'), plt.axis('off')

plt.subplot(2, 3, 6), plt.imshow(sobel_combined, cmap='gray')


plt.title('Sobel Edge Detection'), 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

Aim: Program to create motion blur.

Implementation code:

Using OpenCV’s Filter2D with Motion Kernel:

import cv2
import numpy as np

def create_motion_blur(image_path, output_path, kernel_size=15, angle=0):


“””
Create motion blur effect
:param image_path: path to input image
:param output_path: path to save blurred image

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

# Create motion blur kernel


kernel = np.zeros((kernel_size, kernel_size))
center = kernel_size // 2

# Set the line of 1’s according to angle


angle_rad = np.deg2rad(angle)
cos_val, sin_val = np.cos(angle_rad), np.sin(angle_rad)

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

# Normalize the kernel


kernel /= np.sum(kernel)

# Apply the kernel to each channel


motion_blur = cv2.filter2D(img, -1, kernel)

# Save and show the result


11

cv2.imwrite(output_path, motion_blur)
cv2.imshow(‘Original’, img)
cv2.imshow(‘Motion Blur’, motion_blur)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Example usage
create_motion_blur(‘input.jpg’, ‘motion_blur_output.jpg’, kernel_size=30, angle=45)

Using PIL with Multiple Overlays (Photographic Effect):

from PIL import Image, ImageFilter


import numpy as np

def photographic_motion_blur(image_path, output_path, intensity=10, angle=0):


“””
Simulates motion blur by overlaying shifted copies
:param intensity: number of overlays (higher = more blur)
:param angle: direction of motion in degrees
“””
img = Image.open(image_path)
img = img.convert(‘RGBA’)

# Create blank canvas


result = Image.new(‘RGBA’, img.size, (0, 0, 0, 0))

angle_rad = np.radians(angle)
dx = np.cos(angle_rad)

12

dy = np.sin(angle_rad)

# Composite multiple shifted versions


for I in range(intensity):
offset = (I – intensity//2)
shifted = img.transform(
img.size,
Image.AFFINE,
(1, 0, offset*dx, 0, 1, offset*dy),
fillcolor=(0, 0, 0, 0)
)
# Blend with decreasing opacity
alpha = 100 // (I + 1)
result = Image.alpha_composite(
result,
shifted.copy().convert(‘RGBA’).point(lambda p: p * alpha // 100)
)

# Convert back to RGB and save


result = result.convert(‘RGB’)
result.save(output_path)
result.show()

# Example usage
photographic_motion_blur(‘input.jpg’, ‘photographic_motion_blur.jpg’, intensity=15,
angle=30)

Using Averaging Blur with Offset (Simpler Approach):

13

import cv2
import numpy as np

def simple_motion_blur(image_path, output_path, blur_amount=15, direction=’horizontal’):


“””
Simpler motion blur using averaging with offset
:param blur_amount: intensity of blur
:param direction: ‘horizontal’ or ‘vertical’
“””
img = cv2.imread(image_path)
if img is None:
print(“Error: Could not read the image.”)
return

# Create blurred version


if direction == ‘horizontal’:
kernel = np.ones((1, blur_amount)) / blur_amount
else:
kernel = np.ones((blur_amount, 1)) / blur_amount

motion_blur = cv2.filter2D(img, -1, kernel)

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

Aim: Program performs gray level slicing without background.

Implementation code:

Using OpenCV (Basic Implementation):

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

# Create mask for the desired intensity range


mask = cv2.inRange(img, lower_thresh, upper_thresh)

# Apply the mask - preserve only pixels in the range


result = cv2.bitwise_and(img, img, mask=mask)

# Display results
cv2.imshow('Original Image', img)
cv2.imshow('Gray Level Slicing (Without Background)', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

# Save output if path provided


if output_path:
cv2.imwrite(output_path, result)

16

return result

# Example usage
output = gray_level_slicing_no_bg('input.jpg', 100, 200, 'sliced_output.jpg')

Using NumPy (More Flexible):

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)

# Process each range


for lower, upper in ranges:
mask = (img >= lower) & (img <= upper)
result[mask] = img[mask]

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:

Simple Arithmetic Operations (Add/Subtract):

import cv2
18


import numpy as np

def adjust_brightness(image_path, enhancement_factor=1.5, suppression_factor=0.5):


"""
Adjust image brightness through enhancement and suppression
:param image_path: Path to input image
:param enhancement_factor: Brightness multiplier (>1 enhances)
:param suppression_factor: Brightness multiplier (<1 suppresses)
"""
# Read image
img = cv2.imread(image_path)
if img is None:
print("Error: Could not read the image.")
return

# Convert to float32 for precise calculations


img_float = img.astype(np.float32) / 255.0

# 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)

Gamma Correction (Non-linear Adjustment):

import cv2
import numpy as np

def gamma_adjustment(image_path, gamma_enhance=0.5, gamma_suppress=2.0):


"""
Adjust brightness using gamma correction
:param gamma_enhance: <1 brightens, >1 darkens (for enhancement)
:param gamma_suppress: >1 darkens, <1 brightens (for suppression)
"""
img = cv2.imread(image_path)
if img is None:
print("Error: Could not read the image.")
return

# Normalize and apply gamma correction


img_normalized = img / 255.0

# Enhanced version (brighter)


enhanced = np.power(img_normalized, gamma_enhance)
enhanced = np.clip(enhanced * 255, 0, 255).astype(np.uint8)

# Suppressed version (darker)


suppressed = np.power(img_normalized, gamma_suppress)

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()

return enhanced, suppressed

# Example usage
enhanced, suppressed = gamma_adjustment('input.jpg', gamma_enhance=0.4,
gamma_suppress=2.5)

Histogram Equalization (Contrast-Aware Brightness Adjustment):

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

# Convert to YUV color space (Y channel contains brightness)


yuv = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)

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)

# Suppress brightness (reduce Y channel)


yuv_suppressed = yuv.copy()
yuv_suppressed[:,:,0] = cv2.equalizeHist(yuv_suppressed[:,:,0])
yuv_suppressed[:,:,0] = np.clip(yuv_suppressed[:,:,0] * 0.5, 0, 255).astype(np.uint8)
suppressed = cv2.cvtColor(yuv_suppressed, 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])

# Color histogram (RGB channels)


plt.subplot(2, 2, 3)
colors = ('r', 'g', 'b')
for i, col in enumerate(colors):
hist = cv2.calcHist([img_rgb], [i], None, [256], [0, 256])
plt.plot(hist, color=col, label=col.upper())
plt.title('Color Channel Histograms')
plt.xlabel('Pixel Intensity')
plt.ylabel('Frequency')
plt.xlim([0, 256])
plt.legend()

# 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()

# Print basic histogram statistics


print("\nHistogram Statistics:")
print(f"Min intensity: {np.min(gray_img)}")
print(f"Max intensity: {np.max(gray_img)}")
print(f"Mean intensity: {np.mean(gray_img):.2f}")
print(f"Median intensity: {np.median(gray_img)}")
print(f"Most frequent intensity: {np.argmax(hist_gray)}")

# Example usage
analyze_histograms('your_image.jpg')

Ouput:

25


Experiment-8

Aim: Read an RGB image and segment it using threshold method.

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

# Convert from BGR to RGB for display


img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

26


# Split into individual channels
channels = cv2.split(img)
channel_names = ['Blue', 'Green', 'Red']

# Create a figure for visualization


plt.figure(figsize=(18, 12))

# Display original image


plt.subplot(3, 4, 1)
plt.imshow(img_rgb)
plt.title('Original RGB Image')
plt.axis('off')

# Apply different thresholding methods to each channel


for i, (channel, name) in enumerate(zip(channels, channel_names)):
# Display channel
plt.subplot(3, 4, i*4 + 2)
plt.imshow(channel, cmap='gray')
plt.title(f'{name} Channel')
plt.axis('off')

# Global threshold (fixed at 127)


_, global_thresh = cv2.threshold(channel, 127, 255, cv2.THRESH_BINARY)
plt.subplot(3, 4, i*4 + 3)
plt.imshow(global_thresh, cmap='gray')
plt.title(f'{name} Global Thresh (127)')
plt.axis('off')

# 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')

# Adaptive threshold (Gaussian)


adaptive_thresh = cv2.adaptiveThreshold(
27

channel, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
cv2.THRESH_BINARY, 11, 2)
plt.subplot(3, 4, i*4 + 5)
plt.imshow(adaptive_thresh, cmap='gray')
plt.title(f'{name} Adaptive Thresh')
plt.axis('off')

plt.tight_layout()
plt.show()

# Combine all channels using Otsu's method for demonstration


segmented_channels = []
for channel in channels:
_, thresh = cv2.threshold(channel, 0, 255,
cv2.THRESH_BINARY+cv2.THRESH_OTSU)
segmented_channels.append(thresh)

# Create a segmented RGB image (using Otsu's results)


segmented_rgb = cv2.merge(segmented_channels)

# Display final segmented RGB image


plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(img_rgb)
plt.title('Original Image')
plt.axis('off')

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)

# Create empty channels for visualization


zeros = np.zeros_like(blue_ch)

# Reconstruct each channel as a BGR image (for display purposes)


red_plane = cv2.merge([zeros, zeros, red_ch])
green_plane = cv2.merge([zeros, green_ch, zeros])
blue_plane = cv2.merge([blue_ch, zeros, zeros])

# Convert original to RGB for proper display


img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Create a figure to display the results


plt.figure(figsize=(15, 10))

# Display original image


plt.subplot(2, 3, 1)
plt.imshow(img_rgb)
plt.title('Original RGB Image')
plt.axis('off')

# Display red channel


plt.subplot(2, 3, 2)
plt.imshow(red_plane)
30

plt.title('Red Channel')
plt.axis('off')

# Display green channel


plt.subplot(2, 3, 3)
plt.imshow(green_plane)
plt.title('Green Channel')
plt.axis('off')

# Display blue channel


plt.subplot(2, 3, 4)
plt.imshow(blue_plane)
plt.title('Blue Channel')
plt.axis('off')

# Display grayscale representations


plt.subplot(2, 3, 5)
plt.imshow(red_ch, cmap='gray')
plt.title('Red Channel (Grayscale)')
plt.axis('off')

plt.subplot(2, 3, 6)
plt.imshow(green_ch, cmap='gray')
plt.title('Green Channel (Grayscale)')
plt.axis('off')

plt.tight_layout()
plt.show()

# Return the separated channels


31

return blue_ch, green_ch, red_ch

# Example usage
blue, green, red = separate_color_channels('your_image.jpg')

Output:

Experiment-10

Aim: Perform gamma correction for the given colour image.

Implementation code:

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

def apply_gamma_correction(image_path, gamma=1.0):


"""
Apply gamma correction to a color image
:param image_path: Path to input image

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

# Convert to float32 and normalize to [0,1] range


img_normalized = img.astype(np.float32) / 255.0

# Apply gamma correction


gamma_corrected = np.power(img_normalized, gamma)

# Scale back to [0,255] range


gamma_corrected = (gamma_corrected * 255).astype(np.uint8)

# Convert to RGB for display


img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
corrected_rgb = cv2.cvtColor(gamma_corrected, cv2.COLOR_BGR2RGB)

# 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

Aim: Program to perform different image conversion techniques.


Implementation code:

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

# Convert to RGB for proper display with matplotlib


img_rgb = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# Create a figure for visualization


plt.figure(figsize=(18, 12))

# 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')

# 3. HSV Color Space


hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
35

plt.subplot(3, 4, 3)
plt.imshow(hsv)
plt.title('HSV Color Space')
plt.axis('off')

# 4. LAB Color Space


lab = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
plt.subplot(3, 4, 4)
plt.imshow(lab)
plt.title('LAB Color Space')
plt.axis('off')

# 5. YCrCb Color Space


ycrcb = cv2.cvtColor(img, cv2.COLOR_BGR2YCrCb)
plt.subplot(3, 4, 5)
plt.imshow(ycrcb)
plt.title('YCrCb Color Space')
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')

# 9. Canny Edge Detection


edges = cv2.Canny(gray, 100, 200)
plt.subplot(3, 4, 9)
plt.imshow(edges, cmap='gray')
plt.title('Canny Edges')
plt.axis('off')
# 10. Sobel Edge Detection
sobelx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=5)
sobely = cv2.Sobel(gray, cv2.CV_64F, 0, 1, ksize=5)
sobel = np.sqrt(sobelx**2 + sobely**2)
sobel = cv2.normalize(sobel, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
plt.subplot(3, 4, 10)
plt.imshow(sobel, cmap='gray')
plt.title('Sobel Edges')
plt.axis('off')

# 11. Laplacian Edge Detection


laplacian = cv2.Laplacian(gray, cv2.CV_64F)
laplacian = cv2.normalize(laplacian, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)
37

plt.subplot(3, 4, 11)
plt.imshow(laplacian, cmap='gray')
plt.title('Laplacian Edges')
plt.axis('off')
# 12. Color Quantization (K-means)
Z = img_rgb.reshape((-1,3))
Z = np.float32(Z)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K=8
_, label, center = cv2.kmeans(Z, K, None, criteria, 10,
cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
quantized = center[label.flatten()].reshape(img_rgb.shape)
plt.subplot(3, 4, 12)
plt.imshow(quantized)
plt.title(f'Color Quantization (K={K})')
plt.axis('off')
plt.tight_layout()
plt.show()

# 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

# Step 1: Create a blank color image (Height x Width x Channels)


image = np.zeros((500, 500, 3), dtype=np.uint8) # Black image

# Step 2: Fill the image with a white background


image[:] = (255, 255, 255) # (B, G, R) - OpenCV uses BGR color format

# Step 3: Draw a blue rectangle


cv2.rectangle(image, (100, 100), (400, 400), (255, 0, 0), -1) # (B, G, R), -1 for filled

# Step 4: Save the image


cv2.imwrite("color_image.png", image)

# Step 5: Read the saved image


read_image = cv2.imread("color_image.png")

# Step 6: Display the image


cv2.imshow("Color Image", read_image)

cv2.waitKey(0) # Wait for a key press


cv2.destroyAllWindows() # Close the window

40

Output:

41



Experiment-13

Aim: Code to implement watermarking in spatial domain.


Implementation code:

import cv2
import numpy as np

# Step 1: Load the original image and watermark image


original = cv2.imread("original_image.jpg") # Load main image
watermark = cv2.imread("watermark.png", cv2.IMREAD_UNCHANGED) # Load
watermark (supports transparency)

# Step 2: Resize watermark to fit the original image


(h, w) = original.shape[:2]
watermark = cv2.resize(watermark, (w // 4, h // 4)) # Resize watermark to 1/4 of the
original image

# Step 3: Define position for watermark (bottom-right corner)


wm_h, wm_w = watermark.shape[:2]
x_offset = w - wm_w - 10 # 10-pixel padding
y_offset = h - wm_h - 10

# Step 4: Extract the watermark alpha channel (for transparency)


if watermark.shape[2] == 4: # If watermark has an alpha channel
wm_bgr = watermark[:, :, :3] # Extract RGB channels
alpha = watermark[:, :, 3] / 255.0 # Normalize alpha to range [0, 1]
else:
wm_bgr = watermark
alpha = np.ones((wm_h, wm_w), dtype=np.float32) # If no alpha, set full opacity

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]

# Step 6: Save and display the watermarked image


cv2.imwrite("watermarked_image.jpg", original)
cv2.imshow("Watermarked Image", original)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:

43


Experiment-14

Aim: Code to generate different levels of Gaussian Pyramid.


Implementation code:

import cv2
import numpy as np

# Step 1: Load the original image and watermark image


original = cv2.imread("original_image.jpg") # Load main image
watermark = cv2.imread("watermark.png", cv2.IMREAD_UNCHANGED) # Load
watermark (supports transparency)

# Step 2: Resize watermark to fit the original image


(h, w) = original.shape[:2]
watermark = cv2.resize(watermark, (w // 4, h // 4)) # Resize watermark to 1/4 of the
original image

# Step 3: Define position for watermark (bottom-right corner)


wm_h, wm_w = watermark.shape[:2]
x_offset = w - wm_w - 10 # 10-pixel padding
y_offset = h - wm_h - 10

# Step 4: Extract the watermark alpha channel (for transparency)


if watermark.shape[2] == 4: # If watermark has an alpha channel
wm_bgr = watermark[:, :, :3] # Extract RGB channels
alpha = watermark[:, :, 3] / 255.0 # Normalize alpha to range [0, 1]
else:

44

wm_bgr = watermark
alpha = np.ones((wm_h, wm_w), dtype=np.float32) # If no alpha, set full opacity

# 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]

# Step 6: Save and display the watermarked image


cv2.imwrite("watermarked_image.jpg", original)
cv2.imshow("Watermarked Image", original)
cv2.waitKey(0)
cv2.destroyAllWindows()

Output:
• The final image will have a watermark blended at the bottom-right corner.

• If a transparent PNG is used, the transparency is maintained.

45

46

You might also like