0% found this document useful (0 votes)
8 views23 pages

Updated - Lab Manual - 10 - DIP

The lab manual focuses on implementing color image processing techniques using Python, covering topics such as color fundamentals, color models, and various enhancement algorithms. Key objectives include understanding color image enhancement, gray to color conversion, brightness control, contrast stretching, negative transformation, and thresholding. The manual provides practical code examples using OpenCV for each technique, demonstrating their applications in improving image quality.
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)
8 views23 pages

Updated - Lab Manual - 10 - DIP

The lab manual focuses on implementing color image processing techniques using Python, covering topics such as color fundamentals, color models, and various enhancement algorithms. Key objectives include understanding color image enhancement, gray to color conversion, brightness control, contrast stretching, negative transformation, and thresholding. The manual provides practical code examples using OpenCV for each technique, demonstrating their applications in improving image quality.
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/ 23

UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA

FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

DIGITAL IMAGE PROCESSING

LAB MANUAL 10

Implementation of Color Image Processing techniques in Python


 Color Image Processing
 Color Spectrum
 Color Fundamentals
 Human Perception
 Primary color of lights vs primary color of pigments
 Chromaticity Diagram
 Color Models
 RGB
 CMY
 CMYK
 HIS
 YIQ

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

LAB OBJECTIVE:

The objective of this lab is to understand & implement Color Image Processing techniques in
Python

1. Introduction to most commonly used Color image enhancement algorithms

2. Gray to Color Conversion

3. Brightness Control

4. Contrast Stretching

5. Négative Transformation

6. Threshold

7. Filtering techniques

1. Introduction to Color image enhancement algorithms


Color image enhancement algorithms improve the quality of digital images by adjusting brightness,
contrast, sharpness, and color balance. These techniques are widely used in fields like medical
imaging, satellite image processing, and computer vision.

Histogram-Based Methods

 Histogram Equalization (HE): Enhances contrast by redistributing pixel intensity

values.

 CLAHE (Contrast Limited AHE): Prevents noise over-enhancement in localized

regions.

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Spatial Domain Methods

 Gamma Correction: Adjusts brightness using a power-law function.

 Unsharp Masking: Enhances edges for sharper images.

Frequency Domain Methods

 Fourier Transform-Based Enhancement: Enhances image details by modifying

frequency components.

Color-Based Enhancement

 White Balance Adjustment: Corrects color distortions for natural color appearance.

 Retinex Algorithm: Enhances brightness while maintaining color consistency.

 These techniques enhance images for better visual perception and automated analysis.

Gray to Color Conversion in Python


 Converting a grayscale image to a color image involves adding color information to a single-

channel grayscale image.

 While true colorization is complex and often requires deep learning, simple techniques like

applying colormaps or using manual transformations can be implemented using OpenCV and

NumPy.

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Methods for Gray to Color Conversion

1. Using OpenCV Colormaps

import cv2
import matplotlib.pyplot as plt

# Load grayscale image


gray_image = cv2.imread('2.jpg', cv2.IMREAD_GRAYSCALE)

# Apply a colormap (e.g., JET, HSV, HOT)


color_image = cv2.applyColorMap(gray_image, cv2.COLORMAP_JET)

# Display the images


plt.subplot(1, 2, 1)
plt.imshow(gray_image, cmap='gray')
plt.title('Grayscale Image')

plt.subplot(1, 2, 2)
plt.imshow(cv2.cvtColor(color_image, cv2.COLOR_BGR2RGB))
plt.title('Colorized Image')

plt.show()

Output

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

2. Manually Mapping Gray Levels to RGB

import cv2
import matplotlib.pyplot as plt

# Load grayscale image


gray_image = cv2.imread('2.jpg', cv2.IMREAD_GRAYSCALE)

# Convert grayscale to a 3-channel color image


color_image = cv2.cvtColor(gray_image, cv2.COLOR_GRAY2BGR)

# Example: Mapping intensity values to blue shades


color_image[:, :, 1] = gray_image // 2 # Reduce green channel
color_image[:, :, 2] = gray_image // 3 # Reduce red channel

plt.imshow(cv2.cvtColor(color_image, cv2.COLOR_BGR2RGB))
plt.title("Manual Color Mapping")
plt.show()

Output

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Brightness Control in Color Images using OpenCV


Brightness control in color images can be achieved by modifying the pixel intensity values.

OpenCV provides multiple methods to increase or decrease brightness, such as:

 Using Arithmetic Operations (cv2.add() and cv2.subtract())

 Using Image Blending (cv2.addWeighted())

 Using Gamma Correction

1. Brightness Adjustment using cv2.add() and cv2.subtract()

 This code applies the first technique to adjust brightness in a color image (1.jpg) using
cv2.add() (to increase brightness) and cv2.subtract() (to decrease brightness).

 It also displays the original, brightened, and darkened images in a montage format.

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

# Load your image (1.jpg)


image = cv2.imread("1.jpg")

if image is None:
print("Error: Image not found! Make sure '1.jpg' is in the working
directory.")
else:
# Define brightness factor
brightness_value = 50 # Increase or decrease brightness by this
amount

# Increase brightness using cv2.add()


bright_image = cv2.add(image, np.array([brightness_value],
dtype=np.uint8))
Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

# Decrease brightness using cv2.subtract()


dark_image = cv2.subtract(image, np.array([brightness_value],
dtype=np.uint8))

# Create a montage (concatenate images horizontally)


montage = np.hstack((dark_image, image, bright_image))

# Convert BGR to RGB for correct display in Matplotlib


montage_rgb = cv2.cvtColor(montage, cv2.COLOR_BGR2RGB)

# Display the images


plt.figure(figsize=(15, 5))
plt.imshow(montage_rgb)
plt.title("Darkened (Left) | Original (Middle) | Brightened (Right)")
plt.axis("off")
plt.show()

Output

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

2. Brightness Adjustment using Image Blending


(cv2.addWeighted())

 The image blending technique (cv2.addWeighted()) can be used to adjust brightness in a

color image.

 his method blends the original image with a zero matrix (black image), adding a brightness

factor (beta).

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

# Load your image (1.jpg)


image = cv2.imread("1.jpg")

if image is None:
print("Error: Image not found! Make sure '1.jpg' is in the working
directory.")
else:
# Brightness adjustment using cv2.addWeighted()
alpha = 1.2 # Weight for original image
beta = 50 # Brightness factor
bright_image = cv2.addWeighted(image, alpha, np.zeros(image.shape,
image.dtype), 0, beta)

# Create a montage: concatenate images side by side


montage = np.hstack((image, bright_image))

# Convert BGR to RGB for correct display in Matplotlib


montage_rgb = cv2.cvtColor(montage, cv2.COLOR_BGR2RGB)

# Display the montage


plt.figure(figsize=(10, 5))
plt.imshow(montage_rgb)
plt.title("Original (Left) vs Brightness Adjusted (Right)")
Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

plt.axis("off")
plt.show()

Explanation

 Loads "1.jpg" (color image).

 Uses cv2.addWeighted() for brightness control:

 alpha controls contrast (default: 1.2).

 beta adds brightness (default: 50).

 Creates a montage: Displays original and brightened images side by side.

 Converts BGR → RGB for correct display in Matplotlib.

Output

3. Brightness Adjustment using using Gamma Correction

 Gamma correction is useful for non-linear brightness adjustments.

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

 It brightens or darkens an image based on a power-law function, making it great for correcting

overexposed or underexposed images.

 This code applies gamma correction to adjust brightness in "1.jpg", then displays the

darkened, original, and brightened images in a montage format.

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

# Load your image (1.jpg)


image = cv2.imread("1.jpg")

if image is None:
print("Error: Image not found! Make sure '1.jpg' is in the working
directory.")
else:
# Function to apply Gamma Correction
def adjust_gamma(image, gamma=1.0):
inv_gamma = 1.0 / gamma
table = np.array([(i / 255.0) ** inv_gamma * 255 for i in
np.arange(0, 256)]).astype("uint8")
return cv2.LUT(image, table)

# Apply Gamma Correction


gamma_dark = adjust_gamma(image, gamma=0.5) # Darken the image
gamma_bright = adjust_gamma(image, gamma=1.5) # Brighten the image

# Create a montage (concatenate images horizontally)


montage = np.hstack((gamma_dark, image, gamma_bright))

# Convert BGR to RGB for correct display in Matplotlib


montage_rgb = cv2.cvtColor(montage, cv2.COLOR_BGR2RGB)

# Display the images


plt.figure(figsize=(15, 5))
plt.imshow(montage_rgb)
plt.title("Darkened (Left) | Original (Middle) | Brightened (Right)
using Gamma Correction")
Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

plt.axis("off")
plt.show()

Output

Which Brightness Control Method is Best?

✅ cv2.add()/cv2.subtract() – Good for linear brightness changes.

✅ cv2.addWeighted() – Better for contrast-aware brightness adjustments.

✅ Gamma Correction – Best for perceptual brightness control, avoiding overexposure.

Contrast Stretching in Color Images using OpenCV


Contrast stretching is a technique that improves the contrast in an image by normalizing pixel

intensities to a wider range. This can be done using Min-Max Normalization:

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

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

# Load your image (1.jpg)


image = cv2.imread("1.jpg")

if image is None:
print("Error: Image not found! Make sure '1.jpg' is in the working
directory.")
else:
# Convert image to float32 for precise calculations
image_float = np.float32(image)

# Compute min and max per channel


min_val = np.min(image_float, axis=(0, 1), keepdims=True)
max_val = np.max(image_float, axis=(0, 1), keepdims=True)

# Apply contrast stretching formula


stretched_image = (image_float - min_val) / (max_val - min_val) *
255

# Convert back to uint8


stretched_image = np.uint8(stretched_image)

# Create a montage for comparison


montage = np.hstack((image, stretched_image))

# Convert BGR to RGB for correct display in Matplotlib


montage_rgb = cv2.cvtColor(montage, cv2.COLOR_BGR2RGB)

# Display images
plt.figure(figsize=(15, 5))
plt.imshow(montage_rgb)
plt.title("Original (Left) | Contrast Stretched (Right)")
plt.axis("off")
Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

plt.show()

✅ Loads "1.jpg" and converts it to float32 for accurate calculations.


✅ Finds the min & max values for each color channel (R, G, B).
✅ Stretches contrast using Min-Max Normalization to spread pixel values from 0 to 255.
✅ Displays the original and enhanced images in a montage (side-by-side view).

This method is effective for low-contrast images, improving details without over-enhancing noise.

Output

Negative Transformation in Color Images using OpenCV

The negative transformation inverts an image’s colors by applying the formula:

Negative Image=255 − Original Image

This transformation flips the brightness levels, making light areas dark and dark areas light
while inverting colors.

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

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

# Load your image (1.jpg)


image = cv2.imread("1.jpg")

if image is None:
print("Error: Image not found! Make sure '1.jpg' is in the working
directory.")
else:
# Apply negative transformation
negative_image = 255 - image

# Create a montage: Original (left) vs Negative (right)


montage = np.hstack((image, negative_image))

# Convert BGR to RGB for correct display in Matplotlib


montage_rgb = cv2.cvtColor(montage, cv2.COLOR_BGR2RGB)

# Display the images


plt.figure(figsize=(12, 5))
plt.imshow(montage_rgb)
plt.title("Original (Left) vs Negative (Right)")
plt.axis("off")
plt.show()

Output

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Threshold in Color Images using OpenCV

 Thresholding is a technique used to segment an image by converting it into binary (black &
white) or filtered color regions.
 Unlike grayscale thresholding, for color images, we typically apply thresholding channel-
wise or in a different color space like HSV.

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

# Load your image (1.jpg)


image = cv2.imread("1.jpg")

if image is None:
print("Error: Image not found! Make sure '1.jpg' is in the working
directory.")
else:
# Convert image to HSV color space
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)

# Define lower and upper thresholds for color filtering (e.g.,


detecting bright regions)
lower_bound = np.array([0, 50, 50]) # Lower HSV threshold
upper_bound = np.array([180, 255, 255]) # Upper HSV threshold

# Apply thresholding to get a binary mask


mask = cv2.inRange(hsv, lower_bound, upper_bound)

# Apply the mask to keep only the selected regions


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

# Create a montage for comparison


montage = np.hstack((image, result))

# Convert BGR to RGB for Matplotlib display


montage_rgb = cv2.cvtColor(montage, cv2.COLOR_BGR2RGB)

# Display the images


Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

plt.figure(figsize=(12, 5))
plt.imshow(montage_rgb)
plt.title("Original (Left) | Thresholded (Right) - HSV Method")
plt.axis("off")
plt.show()

Explanation
Loads "1.jpg" as a color image.

Converts BGR → HSV (better for color-based thresholding).

Defines HSV threshold values:

Detects bright regions in the image.

Lower Bound → Controls the minimum color range.

Upper Bound → Controls the maximum color range.

Applies cv2.inRange() to create a binary mask.

Uses cv2.bitwise_and() to filter the image, keeping only selected regions.

Displays a montage: Shows original vs. thresholded image.

Output

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Filtering techniques for Color Images using OpenCV


 Image filtering is essential for noise reduction, edge detection, and smoothing.
 OpenCV provides various filtering techniques for color images, including blurring,
sharpening, and edge detection.

1. Averaging (Mean) Filter – Removes Noise

✅ Smooths the image by averaging nearby pixels.

✅ Reduces noise but blurs edges.

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

# Load your image (1.jpg)


image = cv2.imread("1.jpg")

if image is None:
print("Error: Image not found! Make sure '1.jpg' is in the working
directory.")
else:
# Apply averaging filter
blurred_image = cv2.blur(image, (5, 5))

# Create a montage for comparison


montage = np.hstack((image, blurred_image))

# Convert BGR to RGB for Matplotlib


montage_rgb = cv2.cvtColor(montage, cv2.COLOR_BGR2RGB)

# Display images
plt.figure(figsize=(12, 5))
plt.imshow(montage_rgb)
plt.title("Original (Left) | Averaging Filter (Right)")
plt.axis("off")
plt.show()

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Output

2. Gaussian Blur – Better Smoothing

✅ Preserves edges better than averaging.

✅ Used in preprocessing for object detection.

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

# Load your image (1.jpg)


image = cv2.imread("1.jpg")

if image is None:
print("Error: Image not found! Make sure '1.jpg' is in the working
directory.")
else:
# Apply Gaussian filter
gaussian_blur = cv2.GaussianBlur(image, (5, 5), 0)

# Display
montage = np.hstack((image, gaussian_blur))
montage_rgb = cv2.cvtColor(montage, cv2.COLOR_BGR2RGB)
Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

plt.figure(figsize=(12, 5))
plt.imshow(montage_rgb)
plt.title("Original (Left) | Gaussian Blur (Right)")
plt.axis("off")
plt.show()

Output

3. Median Filter – Best for Salt-and-Pepper Noise

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

# Load your image (1.jpg)


image = cv2.imread("1.jpg")

if image is None:
print("Error: Image not found! Make sure '1.jpg' is in the working
directory.")
else:
# Apply median filter
median_blur = cv2.medianBlur(image, 5)

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

# Display
montage = np.hstack((image, median_blur))
montage_rgb = cv2.cvtColor(montage, cv2.COLOR_BGR2RGB)
plt.figure(figsize=(12, 5))
plt.imshow(montage_rgb)
plt.title("Original (Left) | Median Filter (Right)")
plt.axis("off")
plt.show()

Output

4. Sharpening Filter – Enhances Edges


 Sharpening an image enhances edges and fine details, making the image appear crisper.
 This is done using a convolution kernel, where a sharpening filter highlights differences
between neighboring pixels.

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

# Load your image (1.jpg)


image = cv2.imread("1.jpg")
Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

if image is None:
print("Error: Image not found! Make sure '1.jpg' is in the working
directory.")
else:
# Define a sharpening kernel
sharpening_kernel = np.array([[-1, -1, -1],
[-1, 9, -1],
[-1, -1, -1]])

# Apply sharpening filter using cv2.filter2D()


sharpened_image = cv2.filter2D(image, -1, sharpening_kernel)

# Create a montage: Original (left) vs Sharpened (right)


montage = np.hstack((image, sharpened_image))

# Convert BGR to RGB for correct display in Matplotlib


montage_rgb = cv2.cvtColor(montage, cv2.COLOR_BGR2RGB)

# Display the images


plt.figure(figsize=(12, 5))
plt.imshow(montage_rgb)
plt.title("Original (Left) | Sharpened (Right)")
plt.axis("off")
plt.show()

Explanation
 Loads "1.jpg" as a color image.

 Defines a sharpening kernel:

[-1, -1, -1]

[-1, 9, -1]

[-1, -1, -1]

 The center value 9 intensifies the center pixel.


 The surrounding -1 values subtract neighbor intensity, enhancing edges.
Digital Image Processing 6th Term-SE UET Taxila
UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

 Applies cv2.filter2D() for sharpening convolution.

 Creates a montage to compare the original and sharpened images.

 Converts BGR → RGB for Matplotlib visualization.

Output

Digital Image Processing 6th Term-SE UET Taxila


UNIVERSITY OF ENGINEERING AND TECHNOLOGY, TAXILA
FACULTY OF TELECOMMUNICATION AND INFORMATION ENGINEERING

SOFTWARE ENGINEERING DEPARTMENT

Task

 Implement an interactive trackbar (slider) to allow real-time control of gamma values and

threshold levels.

 Use adaptive thresholding instead of a fixed threshold value.

 Apply edge detection (Sobel/Laplacian) on the processed image to extract key features.

 See Output Below.

Output

Digital Image Processing 6th Term-SE UET Taxila

You might also like