0% found this document useful (0 votes)
12 views16 pages

Kushal Mehta - 60003220069 - IT2 - IPCVExp5

The document outlines an experiment for the Image Processing and Computer Vision Laboratory focusing on spatial filtering enhancement techniques. It details the procedure for applying various filters, including low-pass and high-pass filters, on images using Python libraries such as OpenCV and matplotlib. The document also discusses the effects of brightness, contrast adjustments, histogram equalization, and includes questions for further exploration of the concepts.

Uploaded by

jugalpandav0
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)
12 views16 pages

Kushal Mehta - 60003220069 - IT2 - IPCVExp5

The document outlines an experiment for the Image Processing and Computer Vision Laboratory focusing on spatial filtering enhancement techniques. It details the procedure for applying various filters, including low-pass and high-pass filters, on images using Python libraries such as OpenCV and matplotlib. The document also discusses the effects of brightness, contrast adjustments, histogram equalization, and includes questions for further exploration of the concepts.

Uploaded by

jugalpandav0
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/ 16

Academic Year 2024-25

DEPARTMENT OF INFORMATION TECHNOLOGY

COURSE CODE: DJS22ITL603 CLASS: T Y B. TECH


COURSE NAME: Image Processing and Computer Vision Laboratory SAP ID:60003220247

EXPERIMENT NO. 5
CO/LO: Apply Image Enhancement Techniques.
AIM / OBJECTIVE: To apply Spatial Filtering Enhancement Operations on a given image.

Description of the Experiment


Implement spatial domain filtering such as LPF (Average and Median Filter), HPF, High Boost
filters and observe its blurring or smoothening or sharpening effects on the image using
PIL/OpenCV libraries:
1. Read the image.
2. Convert into grayscale if it is colored.
3. Convert into the double format.
4. Use appropriate masks or filters.
5. Apply convolution operation over the given image.
6. Display the enhanced images.

INPUT/DATASET:

PROCEDURE / ALGORITHM:
Describe the procedure that is used to carry out the experiment step-by-step. Describe
the features of any programs you developed.

TECHNOLOGY STACK USED: matplotlib, pillow

CODE:
import cv2

import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import pandas as pd

def read_grayscale_image(path):
image = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
return image

def display_image(image, title):


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

def adjust_brightness(image, beta):


new_image = np.clip(image + beta, 0, 255).astype(np.uint8)
return new_image

def adjust_contrast(image, alpha):


mean = np.mean(image)
new_image = np.clip((image - mean) * alpha + mean, 0,
255).astype(np.uint8)
return new_image

def histogram_equalization(image):
hist, bins = np.histogram(image.flatten(), 256, [0, 256])
cdf = hist.cumsum()
cdf_normalized = cdf * 255 / cdf[-1]
equalized_image = np.interp(image.flatten(), bins[:-1],
cdf_normalized)
return equalized_image.reshape(image.shape).astype(np.uint8), hist,
cdf

def plot_histogram(image, title):


plt.hist(image.ravel(), bins=256, range=[0, 256], color='black')
plt.title(title)
plt.xlabel("Pixel Value")
plt.ylabel("Frequency")
plt.show()

def generate_pdf_cdf_table(hist, cdf):


pdf = hist / np.sum(hist)
cdf_normalized = cdf / cdf[-1]
df = pd.DataFrame({"Pixel Value": np.arange(256), "PDF": pdf, "CDF":
cdf_normalized})
print(df.head(20))
return df

def apply_filters(image):
image = image.astype(np.float64) / 255.0

kernel_avg = np.ones((5, 5), np.float64) / 25


lpf_avg = cv2.filter2D(image, -1, kernel_avg)

lpf_median = cv2.medianBlur((image * 255).astype(np.uint8), 5)


lpf_median = lpf_median.astype(np.float64) / 255.0

kernel_hpf = np.array([[-1, -1, -1],


[-1, 8, -1],
[-1, -1, -1]], np.float64)
hpf_image = cv2.filter2D(image, -1, kernel_hpf)

A = 1.5
high_boost_kernel = A * np.array([[0, 0, 0], [0, 1, 0], [0, 0, 0]]) -
kernel_hpf
high_boost_image = cv2.filter2D(image, -1, high_boost_kernel)

return lpf_avg, lpf_median, hpf_image, high_boost_image


# Read the grayscale image
gray_image = read_grayscale_image("/content/turkey.jpg")
display_image(gray_image, "Original Grayscale Image")

# Display intensity values


print("Intensity Values:")
print(gray_image)

# Adjust brightness and contrast


bright_image = adjust_brightness(gray_image, 30)
dark_image = adjust_brightness(gray_image, -30)
high_contrast_image = adjust_contrast(gray_image, 2.0)

# Perform histogram equalization


equalized_image, hist, cdf = histogram_equalization(gray_image)

display_image(bright_image, "Brightened Image")


display_image(dark_image, "Darkened Image")
display_image(high_contrast_image, "High Contrast Image")
display_image(equalized_image, "Histogram Equalized Image")

# Apply filters
lpf_avg, lpf_median, hpf_image, high_boost_image =
apply_filters(gray_image)
display_image(lpf_avg, "LPF - Average")
display_image(lpf_median, "LPF - Median")
display_image(hpf_image, "HPF - Edge Detection")
display_image(high_boost_image, "High Boost Filter")

# Plot histograms
plot_histogram(gray_image, "Histogram - Original Image")
plot_histogram(bright_image, "Histogram - Brightened Image")
plot_histogram(dark_image, "Histogram - Darkened Image")
plot_histogram(high_contrast_image, "Histogram - High Contrast Image")
plot_histogram(equalized_image, "Histogram - Histogram Equalized Image")

# Generate PDF & CDF Table


df_pdf_cdf = generate_pdf_cdf_table(hist, cdf)

# Process colored image


color_image = cv2.imread("/content/turkey.jpg")
color_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2RGB)

# Apply histogram equalization on each channel


channels = cv2.split(color_image)
equalized_channels = []
histograms = []
cdfs = []
for ch in channels:
eq_ch, hist_ch, cdf_ch = histogram_equalization(ch)
equalized_channels.append(eq_ch)
histograms.append(hist_ch)
cdfs.append(cdf_ch)

equalized_color_image = cv2.merge(equalized_channels)

plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(color_image)
plt.title("Original Color Image")

plt.subplot(1, 2, 2)
plt.imshow(equalized_color_image)
plt.title("Histogram Equalized Color Image")
plt.show()

# Generate PDF & CDF Table for color channels


for i, color in enumerate(['Red', 'Green', 'Blue']):
print(f"{color} Channel PDF & CDF Table:")
generate_pdf_cdf_table(histograms[i], cdfs[i])
QUESTIONS:
1. Write masks and give the mechanics of spatial filtering?
2. What is salt and pepper noise and how it can be removed effectively?
3. Compare smoothening and sharpening filters.

DISCUSSION OF THE RESULT:


 Brightness & Contrast Adjustments: Increasing brightness shifts pixel values higher,
making the image lighter, while decreasing brightness lowers values, making it darker. Contrast
adjustments stretch pixel intensity distribution, enhancing differences in light and dark regions.

 Histogram Equalization: This redistributes intensity values to enhance contrast, making


details more visible, especially in low-contrast images.

 Filtering Techniques:

 Low-Pass Filters (LPF): The averaging and median filters reduce noise and smooth the
image, but they can blur edges.
 High-Pass Filter (HPF): Enhances edges by emphasizing high-frequency details, useful
for detecting outlines.
 High-Boost Filtering: Enhances sharpness while preserving details by combining the
original image with high-pass filtering.
 Histograms: Brightened images shift the histogram right, darkened images shift left, and
high-contrast images stretch the histogram. Histogram equalization flattens the distribution,
improving contrast.

 PDF & CDF Tables: Probability Density Function (PDF) represents pixel intensity
distribution, while Cumulative Distribution Function (CDF) helps visualize intensity
accumulation, showing the effectiveness of contrast enhancement.

REFERENCES:
Website References:
1. Kaggle, “Spatial Filtering OpenCV,” Available:
https://www.kaggle.com/code/bhavinmoriya/spatial-filtering-opencv.
2. OpenCV “Image Filtering,” OpenCV Documentation. Available:
https://docs.opencv.org/4.x/dd/d6a/tutorial_js_filtering.html#:~:text=As%20in%20one%2Ddi
mensional%20signals,finding%20edges%20in%20the%20images..

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy