NAME: ADITYA SHARMA
REGISTRATION I’D: 221070001
BATCH: A
EXPERIMENT NO: 2
AIM: Write programme for histogram display and histogram
equalization
THEORY:
In digital image processing, a histogram is a graphical representation
of the tonal distribution in a digital image. It plots the number of pixels
at each gray level (for grayscale images) or for each color channel (for
color images). The x-axis represents the pixel intensity values
(typically ranging from 0 to 255 for an 8-bit image), and the y-axis
represents the frequency or count of pixels at each intensity level.
Key Terms:
● Pixel Intensity: The brightness value of a pixel. For grayscale
images, it's a single value. For color images (e.g., RGB), it's a
set of values (one for each channel).
● Gray Level: A discrete level of brightness in a grayscale image.
● Frequency/Count: The number of pixels in the image that have
a specific intensity value.
● Bins: The intervals along the x-axis of the histogram. Each bin
represents a range of intensity values.
2. Histogram Display
Displaying a histogram provides valuable insights into the image's
characteristics:
● Brightness: The histogram's position indicates the overall
brightness. A histogram concentrated towards the left indicates a
darker image, while one concentrated towards the right suggests
a brighter image.
● Contrast: The spread of the histogram indicates the contrast. A
narrow histogram implies low contrast, while a wide histogram
suggests high contrast.
● Dynamic Range: The range of intensity values present in the
image, also reflected by the histogram's spread.
● Image Defects: Unusual peaks or gaps in the histogram can
sometimes indicate image defects or artifacts.
Example:
Imagine a grayscale image. Its histogram might show a high peak at
low intensity values, indicating a predominance of dark pixels, and a
smaller peak at higher values, suggesting fewer bright pixels.
3. Histogram Equalization
Histogram equalization is a technique used to improve the contrast of
an image by transforming its pixel intensities to achieve a more
uniform distribution across the entire intensity range. It aims to
redistribute the pixel intensities so that all gray levels are
approximately equally populated, thereby enhancing the image's
dynamic range and making details more visible.
Process of Histogram Equalization:
1.Calculate the Histogram: Compute the histogram of the input
image.
2.Calculate the Cumulative Distribution Function (CDF): The
CDF, denoted by CDF(k), is the sum of all histogram values up to
and including gray level k.
3.Normalize the CDF: Normalize the CDF to the desired range of
pixel values (e.g., 0-255). This is done by multiplying each CDF
value by the maximum gray level and dividing by the total
number of pixels.
4.Map the Pixel Values: Map the original pixel values to the new
values obtained from the normalized CDF. This mapping is the
transformation function.
Mathematical Representation:
Let h(i) be the histogram value at gray level i, CDF(k) be the
cumulative distribution function, N be the total number of pixels, and
L-1 be the maximum gray level (e.g., 255 for an 8-bit image).
CDF(k) = Σ h(i) (from i=0 to k)
Normalized CDF(k) = round((CDF(k) / N) * (L-1))
The normalized CDF provides the new intensity value for each original
intensity value k.
Benefits of Histogram Equalization:
● Improved Contrast: By spreading the histogram, it increases
the difference between light and dark regions, enhancing
contrast.
● Enhanced Detail: Makes previously indistinguishable details
more visible.
Drawbacks of Histogram Equalization:
● Noise Amplification: Can amplify noise in relatively uniform
regions of the image.
● Over-Enhancement: Can sometimes lead to an unnatural or
artificial look, particularly if the original image has a very specific
intensity distribution.
4. Related Concepts and Terms
● Histogram Specification (Matching): A more generalized
technique where the histogram of the image is modified to match
a desired, pre-specified histogram, rather than aiming for a
uniform distribution.
● Local Histogram Equalization: Applies histogram equalization
to small, localized regions of the image, useful for enhancing
details in specific areas while preserving overall brightness.
● Contrast Stretching: A simpler technique that linearly scales
the pixel intensities to cover the full dynamic range, improving
contrast.
● Image Enhancement: A broader term that encompasses
various techniques to improve the visual quality of an image,
including histogram equalization, contrast stretching, and others.
. Algorithm for Histogram Equalization:
1. Read the input image.
2. Calculate the image histogram:
- Create an array (e.g., of size 256 for 8-bit images) to store the
frequency of each gray level.
- Iterate through each pixel in the image and increment the
corresponding bin in the histogram array.
3. Calculate the Cumulative Distribution Function (CDF):
- Create an array (e.g., of size 256) to store the CDF values.
- Initialize the first element of the CDF array with the first element of
the histogram array.
- For each subsequent element in the CDF array, add the
corresponding element from the histogram array to the previous
element in the CDF array.
4. Normalize the CDF:
- Multiply each element of the CDF array by (L-1)/N, where L is the
number of gray levels (e.g., 256) and N is the total number of pixels.
Round the result to the nearest integer.
5. Create a mapping table:
- The normalized CDF array serves as the mapping table. The
index of the array represents the original gray level, and the value at
that index represents the new gray level.
6. Apply the mapping to the image:
- Iterate through each pixel in the input image.
- Look up the original gray level of the pixel in the mapping table.
- Set the pixel's new gray level to the value found in the mapping
table.
7. Save or display the equalized image.
4. Space and Time Complexity:
● Space Complexity:
○ The dominant space usage comes from storing the
histogram and the CDF, which are both of size L (number
of gray levels). For an 8-bit image, L = 256. Therefore, the
space complexity is O(L), which is considered constant
space since L is usually a fixed value. The input image also
takes up space, but this is not specific to the equalization
algorithm itself.
● Time Complexity:
○ Calculating the histogram requires iterating through all N
pixels in the image, which takes O(N) time.
○ Calculating the CDF also takes O(L) time.
○ Normalizing the CDF takes O(L) time.
○ Applying the mapping to the image requires iterating
through all N pixels again, taking O(N) time.
Therefore, the overall time complexity of histogram equalization is O(N
+ L). Since N (number of pixels) is typically much larger than L
(number of gray levels), the time complexity is effectively dominated
by O(N), making it linear with respect to the number of pixels.
CODE:
import cv2
import numpy as np
import matplotlib.pyplot as plt
# Load the image and convert it to grayscale
image = cv2.imread("image1.jpg", 0)
# Display original image
plt.imshow(image, cmap='gray')
plt.title("Original Image")
plt.axis("off")
plt.show()
# Step 1: Convert the image into a 2D matrix
rows, cols = image.shape
image_matrix = image.flatten()
# Step 2: Plot original histogram
plt.hist(image_matrix, bins=256, range=[0, 256], color='blue', alpha=0.7)
plt.title("Original Histogram")
plt.show()
# Step 3: Calculate PDF
hist, bins = np.histogram(image_matrix, bins=256, range=[0, 256])
pdf = hist / sum(hist)
# Step 4: Compute CDF from PDF
cdf = np.cumsum(pdf)
cdf_normalized = cdf * 255 / cdf[-1] # Normalize CDF to 255
# Step 5: Map the pixel values based on the CDF
equalized_image = np.interp(image_matrix, bins[:-1],
cdf_normalized).reshape(rows, cols).astype(np.uint8)
# Step 6: Plot the histogram of the enhanced image
plt.hist(equalized_image.ravel(), bins=256, range=[0, 256], color='green',
alpha=0.7)
plt.title("Enhanced Image Histogram")
plt.show()
# Display enhanced image
plt.imshow(equalized_image, cmap='gray')
plt.title("Enhanced Image (CDF Applied)")
plt.axis("off")
plt.show()
OUTPUT:
In summary: Histogram equalization has a linear time complexity with
respect to the number of pixels and constant space complexity with
respect to the number of gray levels. This makes it an efficient
algorithm for image enhancement.