Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 54 ยท Image Processing

Histograms and Equalization

Read an image histogram with calcHist, then fix flat contrast with stretching, equalizeHist and CLAHE. Equalization is rebuilt in numpy so you can run it.

A histogram counts how many pixels have each brightness. Throw away every pixel position and keep only the counts, and you get a surprisingly rich summary: an image whose counts pile up at the dark end is underexposed, one whose counts occupy a narrow band has poor contrast, and one with two separate humps is a good candidate for thresholding.

This lesson shows how to compute and read a histogram, and then three ways to repair contrast: stretching, global equalization and CLAHE. As elsewhere in this track, cv2 cannot run here, so the OpenCV calls are read-only and the live examples rebuild the same ideas in numpy. If arrays of pixels are unfamiliar, start with Images Are NumPy Arrays.

Computing a histogram

For a grayscale 8-bit image there are 256 possible values, so the histogram has 256 bins.

Python
import cv2

gray = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)
hist = cv2.calcHist([gray], [0], None, [256], [0, 256])

The arguments are unusual, because calcHist is general enough for several images and channels. In order they are: a list of images, a list of channel indexes to use, an optional mask (None for the whole image), a list of bin counts, and a list of value ranges. The upper bound is exclusive, so 8-bit data uses [0, 256]. The result has shape (256, 1) and dtype float32.

For a plain grayscale image, numpy gives the same counts in one line, and it is often the easier tool:

Python
import numpy as np

counts = np.bincount(gray.ravel(), minlength=256)

For a color image you compute one histogram per channel by passing the channel index, for example [0] for blue in a BGR image. A mask restricts counting to a region of interest: the mask is an 8-bit image the same size as the source, and only pixels where it is nonzero are counted.

Reading a histogram

What a histogram tells you

Piled left Dark, underexposed picture.
Piled right Bright, washed-out picture.
Narrow band Low contrast, even if the brightness is fine.
Two humps Object and background, easy to threshold.

The picture's positions are gone, only the counts remain.

1 / 2

A histogram never says where a value occurs. Two very different pictures can share one histogram, so it is a diagnostic tool and the base of intensity transforms, not a description of content.

Contrast stretching

The cheapest repair is contrast stretching: map the darkest value present to 0 and the brightest to 255, with everything else scaled in between. It is a straight line, so it keeps the relative spacing of tones. In OpenCV you can do it with cv2.normalize(gray, None, 0, 255, cv2.NORM_MINMAX).

Stretching is gentle, but one stray bright pixel can ruin it, because the whole mapping hangs on the extremes. A common fix is to stretch between the 1st and 99th percentiles and clip the rest.

Python Histogram, cumulative counts and stretching

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 stretched histogram spans the full range, but the shape is the same: the bars only move apart. Stretching cannot change the relative shape of the distribution, which is exactly what equalization does.

Histogram equalization

Equalization tries to make every brightness level about equally common. It uses the cumulative distribution function (CDF): for each level, the fraction of pixels at or below it. The new value of a pixel is its old level's CDF scaled to 0..255. Levels that hold many pixels get stretched apart, levels that hold few are squeezed together.

Python
equalized = cv2.equalizeHist(gray)   # 8-bit single channel only

Essentially, OpenCV builds a lookup table: the cumulative count minus the first nonzero cumulative count, divided by the number of pixels minus that same value, multiplied by 255 and rounded. Subtracting the first nonzero count is why the darkest present level maps to exactly 0. The next example implements that table and applies it with fancy indexing, lut[img], which is also how OpenCV's cv2.LUT works.

Python equalizeHist rebuilt in numpy

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 dark majority gets spread across the whole range, so the mean rises from 53.5 to 130.5 and the eight bins end up with 178 to 229 pixels each, instead of one bin holding 1268. The result is never perfectly flat, because pixels with equal values cannot be split apart, and a second pass still changes 257 pixels, so do not expect equalization to be idempotent. The cost is that equalization is global and aggressive. If the picture has a large smooth background, the huge peak of background pixels gets stretched across many levels and any noise in it is amplified.

For color images do not call equalizeHist on each BGR channel, which shifts hues. Convert to a space with a separate brightness channel (YCrCb, or the L channel of Lab, see Color Spaces), equalize only that channel, and convert back.

CLAHE: adaptive, with a clip limit

CLAHE (Contrast Limited Adaptive Histogram Equalization) fixes the two weaknesses of global equalization. It splits the image into tiles, equalizes each tile with its own histogram (blending the results at tile borders to hide seams), and clips each histogram before building the CDF. Clipping caps how tall any single bin can be, and the removed excess is spread evenly over all bins, so a flat region cannot get an extreme boost.

Python
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
result = clahe.apply(gray)

tileGridSize is the number of tiles across and down (default 8 by 8). clipLimit is a multiplier relative to a flat histogram: the real per-bin cap works out to roughly clipLimit * tile_pixels / 256. A value of 1 means almost no contrast change, 2 to 4 is typical, and very large values approach plain adaptive equalization with its noise problems. A tiny example of the clipping step on a single tile shows why it tames flat regions.

Python Clipping the histogram, as CLAHE does

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.

Without clipping, the faint difference between levels 100 and 101 becomes a jump of 75 output levels. With clipping, the same step is only 3, and the mapping stays close to the identity for the detail (level 60 maps to 57, level 150 to 155). That trade is the whole point of the clip limit.

Where equalization helps, and where it hurts

Good uses: medical images such as X-rays, satellite and aerial photos with a hazy low-contrast range, underexposed photographs, and preprocessing before thresholding or feature detection so that algorithms see more consistent contrast. The result is an enhanced contrast and clearer detail without choosing any curve by hand.

Limits: equalization is global, so one bright window can push the whole transformation and flatten the rest. It also amplifies noise in nearly uniform regions (a clear sky turns grainy), can over-enhance an image so that it looks unnatural, and changes colors if you apply it to each BGR channel separately. For color images equalize only the brightness: convert to YCrCb or HSV, equalize the Y or V channel, and convert back. CLAHE below limits the amplification with a clip limit, which is why it is the usual choice for photographs.

Which tool to use

  • Normalize / stretching: the image is merely dull and has no outliers.
  • equalizeHist: quick, global, good for scientific or X-ray style images where you want maximum separation of tones.
  • CLAHE: photos and medical-style images with uneven local contrast; the usual choice before feature detection or thresholding on poorly lit pictures.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In cv2.calcHist([gray], [0], None, [256], [0, 256]), what is the first argument?

    calcHist works on several images at once, so the first argument is a list of images, even when it holds just one.
  2. 2. What does a histogram NOT tell you about an image?

    A histogram keeps only counts per brightness. All positional information is discarded.
  3. 3. Why is equalizeHist on each B, G and R channel a poor way to equalize a color photo?

    Each channel gets a different mapping, so colors shift. Equalize only a brightness channel such as Y in YCrCb or L in Lab instead.
  4. 4. What does the clip limit in CLAHE do?

    Bins above the cap are cut and the excess is redistributed evenly, which limits the slope of the mapping and keeps noise in flat areas under control.

Summary

  • A histogram counts pixels per brightness; cv2.calcHist takes a list of images, channels, a mask, bin counts and ranges, and np.bincount does the same for simple 8-bit cases.
  • Contrast stretching maps min to 0 and max to 255 linearly; one outlier can spoil it.
  • cv2.equalizeHist flattens the histogram using the CDF as a lookup table; it is global and works on one 8-bit channel.
  • For color, equalize a brightness channel (YCrCb or Lab), never the BGR channels separately.
  • CLAHE equalizes per tile and clips each histogram (clipLimit, tileGridSize), which preserves local detail without boosting noise.

Next up: Blurring and Noise Reduction.