Skip to content
Tutorials Center
My learning

Topics

Lesson 6 of 46 ยท Pixel Operations

Histograms and Equalization

Compute intensity histograms and cumulative distributions, build histogram equalization from scratch, understand the CLAHE idea and compare images by histogram.

A histogram answers a simple question about an image: how many pixels have each brightness? It throws away where the pixels are and keeps only how much of each value there is. That small summary tells you at a glance whether a picture is too dark, washed out or well exposed, and it drives some of the most useful pixel operations, such as histogram equalization and automatic thresholding.

In this lesson you will compute histograms with NumPy, read them, build equalization from scratch with the cumulative distribution, see why local methods like CLAHE exist, and use histograms to compare images. It follows on from Brightness, Contrast and Gamma.

The intensity histogram

For an 8-bit grayscale image, the histogram has 256 bins: hist[v] is the number of pixels with value v. NumPy gives it to you with np.bincount(img.ravel(), minlength=256), or with np.histogram when you want other bin widths.

How to read one:

  • A histogram bunched at the left means a dark image; at the right, a bright one.
  • A narrow hump means low contrast: few distinct gray levels are in use.
  • Two separate humps (a bimodal histogram) often mean object and background, which is the idea behind Thresholding.
  • Tall spikes at 0 or 255 mean clipping.
Python Computing and plotting a histogram

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Two humps, near 70 and near 110, and nothing else: the image uses only a sliver of the 256 available levels. We can do better.

The cumulative distribution

Divide the histogram by the number of pixels and you get the share of pixels at each value (a probability mass function). Add those up from left to right and you get the cumulative distribution function (CDF): cdf[v] is the fraction of pixels with value v or darker. The CDF runs from near 0 to exactly 1 and never goes down.

The CDF is more than a summary. It answers "what rank does this brightness have among all pixels?" A pixel whose value has CDF 0.75 is brighter than three quarters of the image. That ranking idea is the key to equalization.

Histogram equalization from scratch

The goal of histogram equalization is to spread the gray levels so that the output uses the whole range roughly evenly: flat histogram, strong contrast. The trick is to use the CDF itself as the transform:

s = round(255 ยท cdf[r])

An input value that sits at the 25th percentile maps to about 64, one at the median maps to about 128, and so on. Dense groups of nearly equal values get stretched apart; empty stretches of the range get skipped over.

flowchart LR
    A["Image"] --> B["Histogram<br/>bincount"]
    B --> C["CDF<br/>cumsum / N"]
    C --> D["Lookup table<br/>round(255 * cdf)"]
    D --> E["Equalized image<br/>lut[img]"]

Equalization is a point operation whose curve is learned from the image's own histogram.

A refinement, used by most libraries, subtracts the smallest nonzero CDF value so that the darkest pixel in the image maps exactly to 0:

s = round(255 ยท (cdf[r] - cdf_min) / (1 - cdf_min))

Python Equalization step by step

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The output now spans 0 to 255 and the disc stands out clearly from the background. Two things to notice. First, the number of distinct gray levels does not increase: equalization moves values apart, it cannot invent new ones, so the output histogram is spread out but "combed" with gaps. Second, noise is stretched together with the signal. Here the noisy background becomes visibly coarser, a typical side effect.

Note: Equalization is not always an improvement. For photographs it can look harsh and exaggerate noise. It shines on dim, low-contrast images such as X-rays, microscope slides or surveillance frames, and as a preprocessing step before feature extraction.

Local equalization and CLAHE

Global equalization applies one curve to the whole image. If one part of the image is dark and another bright, one curve cannot serve both. The idea of adaptive histogram equalization is to divide the image into tiles and equalize each tile with its own histogram.

Tiles alone cause two problems: noise gets amplified badly in flat tiles, and visible seams appear at tile borders. CLAHE (Contrast Limited Adaptive Histogram Equalization) fixes them:

  1. Clip the histogram of each tile at a limit and redistribute the excess evenly over all bins. This caps the slope of the curve, and therefore the noise amplification.
  2. Interpolate between the curves of neighboring tiles, so pixels near a border blend two tile mappings smoothly.

Our version below keeps only the first idea (tile-wise equalization with clipping) and skips the border interpolation, to show the principle. Libraries such as scikit-image (exposure.equalize_adapthist) and OpenCV implement the full method.

Python A tiny tile-wise equalizer with clipping

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Each half of this image has a standard deviation of only about 9 gray levels. Global equalization pools both halves into one histogram, so it spends half of the output range on each side and raises the contrast inside both to about 37. The tiled version lifts it to about 18 only: the clip limit deliberately holds back the stretch so that the noise in flat tiles is not blown up. A smaller clip limit means a gentler result, a larger one approaches plain per-tile equalization. Real CLAHE adds the interpolation between tiles that we skipped, so no seams show.

Comparing images by histogram

Because a histogram ignores position, it is a compact fingerprint of an image's overall tonality or color. Two images with similar histograms look alike in distribution (not necessarily in content). Common distance measures between normalized histograms p and q:

  • Intersection: sum(min(p, q)); 1 means identical, 0 means no overlap.
  • Chi-square: sum((p - q)^2 / (p + q)); 0 means identical.
  • Correlation of the two histogram vectors.

Histogram comparison is used for quick image retrieval and shot-change detection in video; the project Image Search by Similarity builds on it. Its weakness is exactly the dropped position information: a photo and a shuffled copy of the same pixels have identical histograms.

Python Comparing histograms

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Similar images give high intersection and low chi-square; the dark and bright images barely overlap. The shuffled copy matches perfectly even though it is noise.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A histogram with a single narrow hump in the middle of the range indicates what?

    A narrow hump means most pixels have similar values, so the image has little tonal variety and looks flat.
  2. 2. In histogram equalization, what is used as the intensity transform?

    Mapping each value to 255 times its CDF spreads pixels evenly over the range, since the CDF measures each value's rank among all pixels.
  3. 3. What problem does the 'contrast limited' part of CLAHE address?

    Clipping each tile's histogram caps the slope of its mapping, so flat, noisy areas are not stretched into large random swings. Interpolation between tiles handles the border seams.
  4. 4. Why can a histogram comparison say that two very different pictures are identical?

    Shuffling pixel positions leaves the histogram unchanged, so histograms alone cannot tell apart images that differ only in layout.
  5. 5. After equalizing an 8-bit image, how does the number of distinct gray levels change?

    Equalization is a lookup table: different input values can merge, but no new values can appear, so the output histogram has gaps.

Summary

  • A histogram counts pixels per intensity; np.bincount(img.ravel(), minlength=256) computes it. Its shape reveals brightness, contrast and clipping.
  • The CDF (cumulative sum of the normalized histogram) gives each value's rank; equalization maps v to 255 * cdf[v], flattening the distribution.
  • Equalization stretches noise as well as signal, and cannot create new gray levels.
  • CLAHE equalizes local tiles with a clipped histogram and interpolates between them, avoiding both global one-curve limits and noise blow-up.
  • Histogram distances (intersection, chi-square) compare tonal distribution but ignore layout.

Next, use the histogram's two humps to separate object from background: Thresholding.