0% found this document useful (0 votes)
11 views

Chapter 3

Uploaded by

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

Chapter 3

Uploaded by

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

Chapter Three

Spatial Domain Image Processing


Outline

 Spatial Processing of Digital Images


 Basic Intensity Transformation Functions
 Histogram of images
 Histogram processing
 Spatial filtering
 Combining Spatial Enhancement Methods
Spatial Processing of Digital Images
Definition
 Spatial processing is sensing and integrating information pertaining to a location
in space.
 In an image, this space is a 2D plane (xy-plane).
 Therefore, the spatial domain refers to the image plane itself and methods in
spatial domain are based on directly modifying the value of the pixels.
 Spatial processing of images works by operating directly on an image's pixel
values.
Cont’d..
 Spatial processing in Computer Science refers to the manipulation and blending of
pixels within individual frames of a video.
 It involves operations such as alpha blending to create new pixels based on
specific criteria within a single frame.
Cont’d..
Basic Intensity Transformation Functions
 Basic intensity transformations are essential tools in image processing that
enable the adjustment of pixel intensity values in images.
 These operations serve as the building blocks for enhancing and
manipulating the visual appearance of various types of images,
 including gray scale and color ones.
Intensity transformations functions
Identity Function
 The identity transformation is the simplest of all intensity transformations.
 It doesn’t change the pixel intensities of the image
 Output intensities are identical to input intensities
 If “r” represents the original pixel intensity and “s” is the transformed
intensity,
 the identity transformation equation is: Its expression: s = r
Image Negatives (Negative Transformation)
 The negative of an image with gray level in the range [0, L-1], where L = Largest
value in an image,
 is obtained by using the negative transformation’s expression: s = L – 1 – r
 Which is the original pixel intensity is denoted by “r,” the corresponding negative
intensity, denoted by “s.

Advantages of negative :
 Produces an equivalent of a photographic negative.
 Enhances white or gray detail embedded in dark regions
Cont’d..
 Example 1: the following matrix represents the pixels values of an 8-bit image
(r) , apply negative transform and find the resulting image pixel values.

 solution: L= 28 = 256 s=L-1-r s =255-r


 Apply this transform to each pixel to find the negative
Cont’d..
 Exercise: the following matrix represents the pixels values of a 5-bit image (r) ,
apply negative transform and find the resulting image pixel values.
Logarithmic Functions
 Logarithmic transformations in image processing are a group of nonlinear
intensity adjustments aimed at enhancing the visibility of details in images.
 They are particularly useful for images with a wide range of pixel values, such as
those captured in low-light or high-contrast conditions.
A. Log Transformation (Logarithm Function)
 The log transformation involves applying the logarithm function to each pixel
value in an image.
 This operation spreads out the darker pixel values, making fine details in
shadowed regions more visible.
 The transformation equation is given by:
 S represents the transformed pixel value.
 R is the original pixel value.
 c is a constant that adjusts the degree of enhancement.
 The logarithm function compresses high-intensity values and stretches low-
intensity values.
B. Inverse-Log Transformation (Exponential
Function)
 The inverse-log transformation is the reverse operation, aimed at expanding the
range of brighter pixels. This is especially useful for images with overexposed
regions.
 The transformation equation is:
 S represents the transformed pixel value.
 R is the original pixel value.
 c is a constant that controls the degree of enhancement.
 The exponential function stretches high-intensity values.
Cont’d..

 Logarithmic transformations are applied to images to improve visibility in both


dark and bright areas.
 The choice of the constant ‘c’ in these transformations depends on the specific
image characteristics and enhancement goals, and
 experimentation may be required to find the optimal value.
Power-law transformations
 Power-law transformations, also known as gamma correction, are a class of
mathematical transformations used to adjust the tonal and brightness
characteristics of an image.
 These transformations are particularly useful in image processing and computer
vision to enhance the visual quality of images or correct for issues related to
illumination and contrast.
 power-law transformations are used in various applications,
 including image enhancement, gamma correction for display devices, and
improving the visibility of details in medical imaging.
Cont’d..
 The basic idea behind power-law transformations is to raise the pixel values of an
image to a certain power (exponent) in order to adjust the image’s overall
brightness and contrast.
 The general form of a power-law transformation is:
 Where:
 O is the output pixel value (transformed value).
 I the input pixel value (original value).
 γ is the exponent, which controls the degree of transformation.
 k is a constant that scales the result to fit within the desired intensity range.
Cont’d..
 Key points about power-law transformations:
Cont’d..
 For example, let's consider an input pixel value I=100 and apply a power-law
transformation with a gamma value of γ=0.5 and a scaling constant of k=1 for
simplicity:
 O?
 O
 O=
 O=10.
 The transformed pixel value O will replace the original pixel value I=100 in the
image.
2) piecewise Linear transformation functions
Contrast Stretching
 Contrast stretching, also known as normalization,
 is a technique used in image processing to improve the contrast in an image by
expanding the range of intensity values.
 Low contrast images may result from:
 Poor illumination
 Wrong setting of lens aperture during image acquisition.
Contrast Stretching and Thresholding
Cont’d..
Thresholding
Bit-plane slicing
 Pixel values are integers having bit value.
 A n-bit image will have 2^n intensity or gray levels.
 In this bit-plane slicing, instead of highlighting the intensity level.
 We will highlight the contribution of each bit in the image.
 Lower order bits generally have no contribution whereas higher order bits have
maximum contribution.
 We multiply kth bit with 2^(k-1) to visualise its contribution.
 Note that an n-bit image will have n bit planes.
 Bit-plane slicing is used in image compression as lower order bits are not stored.
Histogram of images
 A histogram is a graphical representation of the distribution of pixel
intensities (or colors) in an image. It shows the frequency of occurrence
of each intensity value (or color value) across the entire image. In the
context of grayscale images, a histogram plots the intensity levels (from
0 to 255 for 8-bit images) on the x-axis and their corresponding
frequency on the y-axis.
Histogram of images
 Histogram of high contrast images have intensity values
spanned across the maximum and minimum intensity levels.
 transform the histogram of a given input image to a uniform
distribution using the technique of histogram equalization.
 Result of histogram equalization is always uniform distribution.
 It is independent of the probability distribution function of the
input image. Hence we obtain a high contrast image.
Types of Histograms
Grayscale Histogram: For single-channel
images (e.g., grayscale), the histogram
represents the distribution of pixel intensities.
Color Histogram: For color images,
histograms are typically calculated separately
for each color channel (Red, Green, and Blue).
Each channel will have its own histogram
showing the frequency of intensities.
Histogram Use Cases
 Image Enhancement: Analyzing histograms
helps in adjusting brightness, contrast, and
applying other image enhancement techniques
(e.g., histogram equalization).
 Thresholding: Histograms can assist in
choosing threshold values for tasks like binary
segmentation.
 Image Analysis: Histograms provide insights
into image features like brightness, contrast,
and intensity distribution.
Python code that express image histogram
import cv2 color_histogram = # Color Histograms (Blue, Green, Red)
import numpy as np cv2.calcHist([image], [0], None, plt.subplot(2, 3, 2)
import matplotlib.pyplot as [256], [0, 256]) # Blue channel plt.plot(color_histogram, color='blue')
plt color_histogram_g = plt.title('Blue Histogram')

# Load an image (grayscale cv2.calcHist([image], [1], None, plt.xlim([0, 256])
or color) [256], [0, 256]) # Green channel
image = color_histogram_r = plt.subplot(2, 3, 3)
cv2.imread('image.jpg') # cv2.calcHist([image], [2], None, plt.plot(color_histogram_g, color='green')
Replace with your image file [256], [0, 256]) # Red channel plt.title('Green Histogram')
path plt.xlim([0, 256])
# Convert the image to # Calculate histogram for
grayscale grayscale image plt.subplot(2, 3, 4)
gray_image = gray_histogram = plt.plot(color_histogram_r, color='red')
cv2.cvtColor(image, cv2.calcHist([gray_image], [0], plt.title('Red Histogram')
cv2.COLOR_BGR2GRAY) None, [256], [0, 256]) plt.xlim([0, 256])
# Calculate histograms for
each channel (Blue, Green, # Plot histograms # Display image
Red) in color image plt.figure(figsize=(12, 6)) plt.subplot(2, 3, 5)
plt.imshow(cv2.cvtColor(image,
# Grayscale Histogram cv2.COLOR_BGR2RGB))
plt.subplot(2, 3, 1) plt.title('Original Image')
plt.plot(gray_histogram, plt.axis('off')
color='black')
plt.title('Grayscale Histogram') plt.tight_layout()
plt.xlim([0, 256]) plt.show()
code explanations
1. Loading the Image: 3. Plotting Histograms: 4. Displaying the Image:

The image is loaded using We use Matplotlib to plot the The original image is displayed using
cv2.imread(). The image histograms. For the grayscale image, plt.imshow(). The cv2.cvtColor(image,

color image.

variable contains the original we plot the histogram in black. For
the color image, we plot the
cv2.COLOR_BGR2RGB) function converts the
color image from OpenCV's default BGR
The image is then converted to histograms for each color channel in format to RGB format for correct display in
grayscale using cv2.cvtColor() blue, green, and red. Matplotlib.
for grayscale histogram The plt.xlim([0, 256]) ensures that the
calculation. x-axis of each histogram spans the
entire range of intensity values (from 5. Tight Layout:
2. Calculating Histograms: 0 to 255).
plt.tight_layout() ensures that the subplots do
Grayscale Histogram: not overlap.
cv2.calcHist([gray_image], [0],
None, [256], [0, 256]) computes
the histogram for the grayscale
image. The histogram will have
256 bins (one for each intensity
value from 0 to 255).
Color Histograms: For the
color image, histograms for the
Blue, Green, and Red channels
are computed separately using
cv2.calcHist(). The channel
indices are 0 for Blue, 1 for
Green, and 2 for Red.
Histogram processing

 In digital image processing, the histogram is used for graphical


representation of a digital image.
 Histogram Sliding
 In Histogram sliding, the complete histogram is shifted towards rightwards or
leftwards.
 When a histogram is shifted towards the right or left, clear changes are seen in
the brightness of the image.
code for Histogram Sliding
import cv2 # Perform histogram sliding using the formula # Step 4: Show the original and stretched images
import numpy as np stretched_image = np.uint8((image - r_min) * plt.figure(figsize=(12, 6))
import matplotlib.pyplot as plt (s_max - s_min) / (r_max - r_min) + s_min)
# Original Image

# Load the image (grayscale)
image = cv2.imread('image.jpg',
# Step 3: Plot the original and stretched
histograms
plt.subplot(1, 2, 1)
plt.imshow(image, cmap='gray')
cv2.IMREAD_GRAYSCALE) # original_hist = cv2.calcHist([image], [0], None, plt.title('Original Image')
Replace 'image.jpg' with your image [256], [0, 256]) plt.axis('off')
path stretched_hist = cv2.calcHist([stretched_image],
[0], None, [256], [0, 256]) # Stretched Image
# Check if image is loaded plt.subplot(1, 2, 2)
if image is None: plt.figure(figsize=(12, 6)) plt.imshow(stretched_image, cmap='gray')
raise ValueError("Image not plt.title('Stretched Image')
found. Please check the file path.") # Original Image Histogram plt.axis('off')
plt.subplot(1, 2, 1)
# Step 1: Identify the minimum and plt.plot(original_hist, color='black') plt.tight_layout()
maximum pixel values in the original plt.title('Original Histogram') plt.show()
image plt.xlim([0, 256])
r_min = np.min(image) # Optionally save the stretched image
r_max = np.max(image) # Stretched Image Histogram cv2.imwrite('stretched_image.jpg', stretched_image)
plt.subplot(1, 2, 2)
plt.plot(stretched_hist, color='black')
# Step 2: Apply Histogram Sliding plt.title('Stretched Histogram')
(Stretching) plt.xlim([0, 256])
# We map the intensity range [r_min,
r_max] to [0, 255] plt.tight_layout()
s_min = 0 plt.show()
s_max = 255
code explanation for Histogram Sliding

1. Image Loading: The image 3. Histogram Sliding (Stretching): Using 5. Displaying Images: Both the original and

is loaded in grayscale using
cv2.imread(). Make sure to
the formula provided, we calculate the
new pixel values and stretch the image
the stretched images are displayed side by
side using Matplotlib for easy comparison.
replace 'image.jpg' with the intensity values. 6. Saving the Image: Optionally, the
correct path to your image. 4. Plotting Histograms: We calculate stretched image is saved to the disk using
2. Identify Min and Max and plot the histograms of the original cv2.imwrite().
Values: We use np.min(image) and stretched images using
and np.max(image) to find the cv2.calcHist(). The histograms are
minimum and maximum pixel plotted using Matplotlib.
values in the image. These are
used to stretch the pixel
intensities to the full range of
[0, 255].
Cont’d..
 Histogram Stretching
 In histogram stretching, contrast of an image is increased.
 The contrast of an image is defined between the maximum and minimum value
of pixel intensity.

Histogram Equalization
 Histogram equalization is used for equalizing all the pixel values of an image.
 Transformation is done in such a way that uniform flattened histogram is
produced.
 Histogram Equalization is a technique in
image processing that enhances the contrast
of an image by adjusting the intensity values.
 The goal is to distribute the pixel intensities
evenly across the available range (e.g., from
0 to 255 in 8-bit grayscale images).
 This method improves the visibility of details
in an image, especially when the image has
poor contrast or is too dark/bright.
How Histogram Equalization Works:
1. Compute the histogram of the image, which
represents the frequency of each intensity
value.
2. Compute the cumulative distribution
function (CDF) from the histogram. This
function helps us map the original intensities
to new values.
3. Normalize the CDF so that it spans the full
range of pixel values (from 0 to 255).
4. Map the original intensities to the new
Python Code for Histogram Equalization:
import cv2 # Step 2: Calculate histograms of the # Step 4: Display the original and equalized

import numpy as np
import matplotlib.pyplot as plt
original and equalized images
original_hist = cv2.calcHist([image], [0],
images
plt.figure(figsize=(12, 6))
None, [256], [0, 256])
# Load the image (grayscale) equalized_hist = # Original Image
image = cv2.calcHist([equalized_image], [0], plt.subplot(1, 2, 1)
cv2.imread('image.jpg', None, [256], [0, 256]) plt.imshow(image, cmap='gray')
cv2.IMREAD_GRAYSCALE) plt.title('Original Grayscale Image')
# Replace 'image.jpg' with # Step 3: Plot the original and equalized plt.axis('off')
your image path histograms
plt.figure(figsize=(12, 6)) # Equalized Image
# Check if image is loaded plt.subplot(1, 2, 2)
correctly # Original Image Histogram plt.imshow(equalized_image, cmap='gray')
if image is None: plt.subplot(1, 2, 1) plt.title('Equalized Grayscale Image')
raise ValueError("Image plt.plot(original_hist, color='black') plt.axis('off')
not found. Please check the file plt.title('Original Histogram')
path.") plt.xlim([0, 256]) plt.tight_layout()
plt.show()
# Step 1: Apply Histogram # Equalized Image Histogram
Equalization using OpenCV plt.subplot(1, 2, 2) # Optionally, save the equalized image
equalized_image = plt.plot(equalized_hist, color='black') cv2.imwrite('equalized_image.jpg',
cv2.equalizeHist(image) plt.title('Equalized Histogram') equalized_image)
plt.xlim([0, 256])

plt.tight_layout()
plt.show()
Code Explanation:
1. Image Loading: 3. Histogram Calculation: 5. Displaying Images:

The image is loaded in cv2.calcHist() calculates the histogram Both the original and equalized images are
grayscale using cv2.imread(). of the original and equalized images. displayed using plt.imshow() for visual
Make sure the file path The histograms represent the comparison. This shows how histogram
('image.jpg') is correct for distribution of pixel intensities in the equalization improves image contrast.
your specific image. images. 6. Saving the Equalized Image:
2. Histogram Equalization: 4. Plotting Histograms:
cv2.equalizeHist(image) The equalized image can be saved using
applies the histogram Using Matplotlib, we plot the cv2.imwrite().
equalization algorithm histograms of both the original and the
provided by OpenCV. It equalized images side by side. This
enhances the contrast by shows how the equalized image has a
redistributing the pixel values more uniform intensity distribution
to cover the entire intensity compared to the original.
range [0, 255].1
Spatial filtering
Fundamental of Spatial filtering
 Filter term in “Digital image processing” is referred to the sub image
 Spatial filtering is a technique used to enhance the image based on the spatial
characteristics of the image.
 Filtering is a fundamental operation in image processing. It can be used for:

1- Image enhancement

2- Noise reduction

3- Edge detection,

4- Sharpening.
Cont’d..
 The concept of filtering has been applied in the:
 Frequency domain, where it rejects some frequency components while
accepting others.
 The term frequency in an image tells about the rate of change of pixel values.
 Spatial domain, Spatial filtering modifies an image by replacing the value of
each pixel with a function of the values of the pixel and
 its neighbors (filtering is pixel neighborhood operation).
Cont’d..

 Commonly used spatial filtering techniques include median, average, Gaussian


filtering, etc.
 The filtering function sometimes is called filter mask, or filter kernel.
 They can be broadly classified into two different categories :
 1. Linear filtering.
 2. Nonlinear filtering ( Order-statistic filters).
Cont’d..
 A linear spatial filter performs a sum-of-products operation between an
image f and a filter kernel, w.
 The kernel is an array whose size defines the neighborhood of operation, and
whose coefficients determine the nature of the filter.
 Other terms used to refer to a spatial filter kernel are mask, template, and
window.
 We use the term filter kernel or simply kernel.
Smoothing Filters

 Smoothing filter is used for blurring and noise reduction in the image.
 Blurring is pre-processing steps for removal of small details and
Noise Reduction is accomplished by blurring.
 The commonly used smoothing filters are Averaging and Gaussian
filters.
 It can be performed using the convolution operation
Combining Spatial Enhancement Methods

 In real applications, it is hard to know what kind of noise has been added
to an image.
 Therefore, it is difficult to find a unique filter that can appropriately
enhance this noisy image.
 However, it is possible if several de-blurring methods can be combined in
a framework in order to pursue a maximum demising outcome.
 We explain one of the combinatorial techniques using an X-ray example.
Cont’d..
 Illustrates a male chest’s X-ray image.
 The purpose of the process is to highlight the middle cross section of the
image using the combination of sharpening and edge detection
Reading Assignment

 Representation of different image type‘s


 check python codes for spatial filters

You might also like