Histograms and contrast

Intermediate

Introduction

Photographers judge a picture with its histogram: a bar chart of how many pixels have each brightness. A photo taken in fog has all its pixels bunched in a narrow grey band; an underexposed photo has them piled up near black. Vision programs use histograms the same way, to check images and to fix them before further processing. This lesson builds histograms and two classic fixes: contrast stretching and histogram equalisation.

How it works

Histogram. For a greyscale image, count the pixels at each level from 0 to 255. With 256 bars the chart is noisy, so we often group levels into bins: with bins 32 wide, values 0 to 31 fall in bin 0, 32 to 63 in bin 1, and so on. The bin of value v is v // 32.

Reading a histogram:

  • Most pixels on the left: a dark image. On the right: a bright one.
  • Pixels in a narrow band: low contrast, a dull, flat look.
  • Two separate humps: usually an object and a background, which the thresholding lesson will use.

Contrast stretching. If the darkest pixel is lo and the brightest is hi, the linear map

new = (v − lo) × 255 / (hi − lo)

sends lo to 0 and hi to 255 and spreads everything in between. The histogram keeps its shape but becomes wider. In whole numbers, (v - lo) * 255 // (hi - lo). One very dark or very bright pixel can spoil this, so real tools often take lo and hi from percentiles (such as the 1st and 99th) and clamp the values outside.

Histogram equalisation. Stretching keeps crowded levels crowded. Equalisation instead tries to give every output level the same number of pixels. It uses the cumulative distribution: cdf(v) is the number of pixels with level at most v. The standard mapping is

new(v) = round((cdf(v) − cdf_min) × 255 / (N − cdf_min))

where N is the number of pixels and cdf_min is the cdf of the darkest level present. Levels shared by many pixels make the cdf jump, so they are pushed further apart. The result uses the full range and usually shows more detail, though it can also make noise more visible.

Example

img = [[100 + 5 * (r + c) for c in range(6)] for r in range(4)]


def histogram(img, width=32):
    counts = [0] * (256 // width)
    for row in img:
        for v in row:
            counts[v // width] += 1
    return counts


def show(counts, width=32):
    for i, n in enumerate(counts):
        print(f"  {i * width:3}-{i * width + width - 1:3} {'#' * n}")


lo = min([min(row) for row in img])
hi = max([max(row) for row in img])
print("original: levels", lo, "to", hi)
show(histogram(img))

stretched = [[(v - lo) * 255 // (hi - lo) for v in row] for row in img]
print("stretched: top row", stretched[0])
show(histogram(stretched))

counts = {}
for row in img:
    for v in row:
        counts[v] = counts.get(v, 0) + 1
cdf, running = {}, 0
for v in sorted(counts):
    running += counts[v]
    cdf[v] = running
n, first = running, cdf[lo]
lut = {v: round((cdf[v] - first) * 255 / (n - first)) for v in cdf}
print("equalisation table:", lut)
print("top row equalised:", [lut[v] for v in img[0]])
Open in compiler

Line by line

  1. The 4 × 6 image is a smooth ramp from 100 to 140: dull and grey.
  2. histogram counts pixels into eight bins 32 wide. All 24 pixels land in just two bins, 96 to 127 and 128 to 159.
  3. The stretch maps 100 to 0 and 140 to 255. The top row becomes 0, 31, 63, 95, 127, 159, and the histogram now covers all eight bins.
  4. For equalisation, counts tallies each level and cdf accumulates them in order: 1 pixel at 100, 3 at or below 105, 6 at or below 110, and so on up to 24.
  5. lut (a look-up table) applies the formula. Level 105 has cdf 3, so it maps to round(2 × 255 / 23) = 22.
  6. The middle levels, which hold the most pixels, are pushed furthest apart: 115 becomes 100 and 120 becomes 144.

Expected result

original: levels 100 to 140
    0- 31 
   32- 63 
   64- 95 
   96-127 ##################
  128-159 ######
  160-191 
  192-223 
  224-255 
stretched: top row [0, 31, 63, 95, 127, 159]
    0- 31 ###
   32- 63 ###
   64- 95 ####
   96-127 ####
  128-159 ####
  160-191 ###
  192-223 ##
  224-255 #
equalisation table: {100: 0, 105: 22, 110: 55, 115: 100, 120: 144, 125: 188, 130: 222, 135: 244, 140: 255}
top row equalised: [0, 22, 55, 100, 144, 188]

In the real world

Cameras show a live histogram so you can set exposure. Medical images are equalised so doctors can see faint structures, and document scanners stretch contrast to make ink black and paper white. A refined version, CLAHE (contrast-limited adaptive histogram equalisation), equalises small tiles separately and limits how much it boosts noise.

In OpenCV (shown as text; it does not run on this site):

import cv2

grey = cv2.imread("scan.png", cv2.IMREAD_GRAYSCALE)
hist = cv2.calcHist([grey], [0], None, [256], [0, 256])        # 256 counts
stretched = cv2.normalize(grey, None, 0, 255, cv2.NORM_MINMAX)
equalised = cv2.equalizeHist(grey)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8)).apply(grey)

Common mistakes

  • Dividing by zero when every pixel has the same value (hi equals lo). Check for it and leave the image unchanged.
  • Letting one outlier pixel decide the stretch. A single white speck keeps hi at 255 and the stretch does nothing.
  • Equalising colour channels separately, which shifts colours. Equalise brightness only (for example, the V of HSV).
  • Forgetting that equalisation boosts noise in flat areas such as sky.

Best practices

  • Look at the histogram before and after every contrast change.
  • Use percentiles instead of the true minimum and maximum when the image may have outliers.
  • Build a look-up table once (256 entries) and apply it to every pixel, as the example does.
  • Prefer CLAHE for images with both dark and bright regions.

Summary

A histogram counts pixels per level or per bin and shows exposure and contrast. Contrast stretching maps lo to 0 and hi to 255 with (v − lo) × 255 / (hi − lo). Histogram equalisation maps each level through the cumulative count, spreading crowded levels apart so the whole range is used.

Quick check

1. A histogram has all its pixels between 110 and 140. What does the image look like?
2. With lo = 50 and hi = 150, where does contrast stretching send the value 100?
3. What does cdf(v) count?
4. Why can histogram equalisation make an image look noisier?

Key takeaways

  • A histogram shows exposure and contrast at a glance: bunched to the left is dark, bunched in a narrow band is dull.
  • Contrast stretching is (v − lo) × 255 / (hi − lo): it keeps the shape of the histogram but widens it.
  • Equalisation maps each level through the cumulative histogram, giving more output range to crowded levels.

Practice problems for this lesson

My notes

Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.