0% found this document useful (0 votes)
19 views11 pages

Gray Scaling of Image

The document contains multiple image processing techniques applied to grayscale images, including negative transformation, log transformation, power-law transformation, piecewise linear transformation, contrast stretching, gray-level slicing, and bit-plane slicing. Each technique is implemented using Python with OpenCV and Matplotlib, showcasing how to manipulate pixel values to enhance or analyze images. The document also includes experiments with various parameters to observe their effects on the transformed images.
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)
19 views11 pages

Gray Scaling of Image

The document contains multiple image processing techniques applied to grayscale images, including negative transformation, log transformation, power-law transformation, piecewise linear transformation, contrast stretching, gray-level slicing, and bit-plane slicing. Each technique is implemented using Python with OpenCV and Matplotlib, showcasing how to manipulate pixel values to enhance or analyze images. The document also includes experiments with various parameters to observe their effects on the transformed images.
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/ 11

# prompt: Load a grayscale image into the image processing

environment.
# Implement the image negative transformation by subtracting each
pixel
# value from the maximum intensity value.
# Display the original and the transformed image.

import cv2
import matplotlib.pyplot as plt

# Load the grayscale image


image = cv2.imread('hill.webp', cv2.IMREAD_GRAYSCALE)

# Get the maximum intensity value


max_intensity = 255

# Apply the negative transformation


negative_image = max_intensity - image

# Display the original and transformed images


plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')

plt.subplot(1, 2, 2)
plt.imshow(negative_image, cmap='gray')
plt.title('Negative Image')

plt.show()

# prompt: Load a grayscale image into the image processing


environment.
# Implement the log transformation using the formula:
# where $r$ is the input intensity value, $s$ is the output intensity
value, and
# $c$ is a constant for scaling.
# Experiment with different values of $c$.
# Display the original and transformed images.
import cv2
import matplotlib.pyplot as plt
import numpy as np

# Load the grayscale image


image = cv2.imread('hill.webp', cv2.IMREAD_GRAYSCALE)

# Define the log transformation function


def log_transform(image, c):
"""Applies log transformation to an image.

Args:
image: The input grayscale image.
c: The scaling constant.

Returns:
The transformed image.
"""
# Convert the image to float for calculations
image_float = image.astype(np.float32)
# Apply the log transformation
transformed_image = c * np.log(1 + image_float)
# Clip values to the range [0, 255]
transformed_image = np.clip(transformed_image, 0, 255)
# Convert back to uint8
transformed_image = transformed_image.astype(np.uint8)
return transformed_image

# Experiment with different values of c


c_values = [1, 5, 10]

# Display the original and transformed images


plt.figure(figsize=(15, 5))
plt.subplot(1, len(c_values) + 1, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')

for i, c in enumerate(c_values):
transformed_image = log_transform(image, c)
plt.subplot(1, len(c_values) + 1, i + 2)
plt.imshow(transformed_image, cmap='gray')
plt.title(f'Log Transformed (c = {c})')

plt.show()
# prompt: Load a grayscale image into the image processing
environment.
# Implement the power-law transformation using the formula:
# where $r$ is the input intensity value, $s$ is the output intensity
value, $c$
# is a constant for scaling, and $\gamma$ is the gamma parameter.
# Experiment with different values of $\gamma$.
# Display the original and transformed images.

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

# Load the grayscale image


image = cv2.imread('hill.webp', cv2.IMREAD_GRAYSCALE)

# Define the power-law transformation function


def power_law_transform(image, c, gamma):
"""Applies power-law transformation to an image.

Args:
image: The input grayscale image.
c: The scaling constant.
gamma: The gamma parameter.

Returns:
The transformed image.
"""
# Convert the image to float for calculations
image_float = image.astype(np.float32)
# Apply the power-law transformation
transformed_image = c * np.power(image_float, gamma)
# Clip values to the range [0, 255]
transformed_image = np.clip(transformed_image, 0, 255)
# Convert back to uint8
transformed_image = transformed_image.astype(np.uint8)
return transformed_image

# Experiment with different values of gamma


gamma_values = [0.5, 1.5, 2.5]

# Display the original and transformed images


plt.figure(figsize=(15, 5))
plt.subplot(1, len(gamma_values) + 1, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')

for i, gamma in enumerate(gamma_values):


transformed_image = power_law_transform(image, 1, gamma)
plt.subplot(1, len(gamma_values) + 1, i + 2)
plt.imshow(transformed_image, cmap='gray')
plt.title(f'Power-Law Transformed (gamma = {gamma})')

plt.show()

# prompt: Load a grayscale image into the image processing


environment.
# Design a piecewise linear transformation function with multiple
segments.
# Implement the transformation function to enhance specific regions
of
# interest in the image.
# Display the original and transformed images.

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

# Load the grayscale image


image = cv2.imread('Sunset_2007-1.jpg', cv2.IMREAD_GRAYSCALE)

# Define the piecewise linear transformation function


def piecewise_linear_transform(image, points):
"""Applies piecewise linear transformation to an image.

Args:
image: The input grayscale image.
points: A list of tuples representing the control points
of the transformation. Each tuple contains
(input intensity, output intensity).

Returns:
The transformed image.
"""
# Create a lookup table (LUT)
lut = np.zeros(256, dtype=np.uint8)
# Sort the points based on input intensity
points.sort()

# Calculate the output intensity for each input intensity


for i in range(len(points) - 1):
x1, y1 = points[i]
x2, y2 = points[i + 1]
for j in range(x1, x2 + 1):
# Linear interpolation
y = y1 + ((j - x1) * (y2 - y1)) / (x2 - x1)
lut[j] = int(y)

# Apply the LUT to the image


transformed_image = cv2.LUT(image, lut)
return transformed_image

# Define the control points for the piecewise linear transformation


points = [(0, 0), (50, 50), (100, 150), (150, 200), (255, 255)]

# Apply the transformation


transformed_image = piecewise_linear_transform(image, points)

# Display the original and transformed images


plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')

plt.subplot(1, 2, 2)
plt.imshow(transformed_image, cmap='gray')
plt.title('Transformed Image')

plt.show()
# prompt: Apply contrast stretching to a grayscale image to enhance
its contrast.
# Experiment with different stretching ranges (minimum and maximum
intensity
# values).

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

# Load the grayscale image


image = cv2.imread('hill.webp', cv2.IMREAD_GRAYSCALE)

# Define the contrast stretching function


def contrast_stretch(image, min_intensity, max_intensity):
"""Applies contrast stretching to an image.

Args:
image: The input grayscale image.
min_intensity: The minimum intensity value for stretching.
max_intensity: The maximum intensity value for stretching.

Returns:
The contrast-stretched image.
"""
# Convert the image to float for calculations
image_float = image.astype(np.float32)
# Normalize the image to the range [0, 1]
normalized_image = (image_float - np.min(image_float)) /
(np.max(image_float) - np.min(image_float))
# Stretch the contrast
stretched_image = (normalized_image * (max_intensity -
min_intensity)) + min_intensity
# Clip values to the range [0, 255]
stretched_image = np.clip(stretched_image, 0, 255)
# Convert back to uint8
stretched_image = stretched_image.astype(np.uint8)
return stretched_image

# Experiment with different stretching ranges


min_intensities = [50, 100]
max_intensities = [200, 250]

# Display the original and transformed images


plt.figure(figsize=(15, 5))
plt.subplot(1, len(min_intensities) + 1, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')

for i, (min_intensity, max_intensity) in


enumerate(zip(min_intensities, max_intensities)):
stretched_image = contrast_stretch(image, min_intensity,
max_intensity)
plt.subplot(1, len(min_intensities) + 1, i + 2)
plt.imshow(stretched_image, cmap='gray')
plt.title(f'Contrast Stretched (min={min_intensity},
max={max_intensity})')

plt.show()

# prompt: Select a specific range of gray levels from an image using


gray-level slicing.
# Highlight specific features or regions of interest by setting all
other pixel values
# to zero.
# Experiment with different threshold values to observe their effects
on the sliced
# image.

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

# Load the grayscale image


image = cv2.imread('football.jpg', cv2.IMREAD_GRAYSCALE)

# Define the gray-level slicing function


def gray_level_slicing(image, lower_threshold, upper_threshold):
"""Applies gray-level slicing to an image.

Args:
image: The input grayscale image.
lower_threshold: The lower threshold value.
upper_threshold: The upper threshold value.

Returns:
The sliced image.
"""
# Create a mask for the specified range
mask = (image >= lower_threshold) & (image <= upper_threshold)
# Set all other pixels to zero
sliced_image = np.where(mask, image, 0)
return sliced_image

# Experiment with different threshold values


lower_thresholds = [50, 100]
upper_thresholds = [150, 200]

# Display the original and sliced images


plt.figure(figsize=(15, 5))
plt.subplot(1, len(lower_thresholds) + 1, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')

for i, (lower_threshold, upper_threshold) in


enumerate(zip(lower_thresholds, upper_thresholds)):
sliced_image = gray_level_slicing(image, lower_threshold,
upper_threshold)
plt.subplot(1, len(lower_thresholds) + 1, i + 2)
plt.imshow(sliced_image, cmap='gray')
plt.title(f'Sliced Image (lower={lower_threshold},
upper={upper_threshold})')

plt.show()

# prompt: Perform bit-plane slicing on a grayscale image to decompose


it into its binary
# representations.
# Visualize individual bit-planes to understand the contribution of
each bit to the
# image.
# Combine selected bit-planes to reconstruct the original image with
reduced
# bit-depth.

import cv2
import matplotlib.pyplot as plt
import numpy as np
# Load the grayscale image
image = cv2.imread('football.jpg', cv2.IMREAD_GRAYSCALE)

# Function to extract bit planes


def extract_bit_planes(image):
"""Extracts bit planes from a grayscale image.

Args:
image: The input grayscale image.

Returns:
A list of bit planes.
"""
bit_planes = []
for i in range(8):
bit_plane = (image >> i) & 1
bit_planes.append(bit_plane)
return bit_planes

# Extract bit planes


bit_planes = extract_bit_planes(image)

# Display individual bit planes


plt.figure(figsize=(15, 10))
for i in range(8):
plt.subplot(3, 3, i + 1)
plt.imshow(bit_planes[i], cmap='gray')
plt.title(f'Bit Plane {i}')
plt.show()

# Function to combine bit planes


def combine_bit_planes(bit_planes, planes_to_combine):
"""Combines selected bit planes to reconstruct an image.

Args:
bit_planes: A list of bit planes.
planes_to_combine: A list of indices of bit planes to combine.

Returns:
The reconstructed image.
"""
combined_image = np.zeros_like(bit_planes[0])
for i in planes_to_combine:
combined_image = combined_image + (bit_planes[i] << i)
return combined_image

# Combine bit planes 4, 5, 6, and 7


planes_to_combine = [4, 5, 6, 7]
reconstructed_image = combine_bit_planes(bit_planes,
planes_to_combine)

# Display the original and reconstructed images


plt.figure(figsize=(10, 5))
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
plt.title('Original Image')

plt.subplot(1, 2, 2)
plt.imshow(reconstructed_image, cmap='gray')
plt.title('Reconstructed Image (4-bit)')

plt.show()

You might also like