Practical 5: Histogram Equalization

Open In Colab Run this practical in Google Colab

1. Aim

Objective

To understand and implement histogram equalization — a technique that enhances image contrast by redistributing pixel intensities to approximate a uniform distribution.

2. Description / Theory
Theory: Histogram equalization uses the cumulative distribution function (CDF) of an image's intensity histogram as a transfer function. For an image with \(L\) intensity levels (0 to \(L{-}1\)), the transformation maps each input intensity \(r_k\) to output intensity \(s_k\) using:
  • PDF: \(p(r_k) = n_k / n\), where \(n_k\) is the count of pixels with intensity \(r_k\) and \(n\) is the total pixel count.
  • CDF: \(T(r_k) = \sum_{j=0}^{k} p(r_j)\), the cumulative sum of the PDF.
  • The output intensity: \(s_k = (L{-}1) \cdot T(r_k)\), rounded to the nearest integer.
$$s_k = (L - 1) \cdot \sum_{j=0}^{k} \frac{n_j}{n}$$
3. Code

Part 1: Original Image & Histogram

Load an image and visualize its pixel intensity histogram. The histogram shape reveals the contrast characteristics — a narrow cluster means low contrast, a wide spread means high contrast.

Part 2: Histogram Equalization

Apply histogram equalization using cv2.equalizeHist(). Compare the original and equalized images side by side with their histograms. Notice how the equalized histogram spreads pixel intensities across the full 0–255 range.

Part 3: Transfer Function & CDF Analysis

Examine the internals of histogram equalization: the original PDF, the CDF-based transfer function \(T(r) = \text{CDF}(r) \times (L{-}1)\), the equalized PDF, and a comparison of original vs. equalized CDFs. The equalized CDF should approximate a straight diagonal line (uniform distribution).

Part 4: Multi-Image Comparison

Apply histogram equalization to multiple images simultaneously and compare the before/after results. This demonstrates that equalization adapts to each image's unique intensity distribution.

4. Output 5. Analysis / Conclusion

Analysis Questions

  1. Compare the original and equalized histograms. Why does the equalized histogram approximate a uniform distribution? Is it perfectly uniform — why or why not?
  2. Look at the CDF comparison plot. How does the equalized CDF differ from the original CDF? What would a perfectly uniform histogram's CDF look like?
  3. Does histogram equalization always improve image quality? Consider an image that already has good contrast — what happens when you equalize it?
  4. The transfer function is monotonically increasing. Why is this property necessary? What would happen if the mapping were not monotonic?