Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 54 ยท Image Processing

Intensity Transformations: Negative, Log, Gamma and Contrast Stretching

Change brightness and contrast pixel by pixel: negative, log, power-law (gamma), piecewise-linear stretching and lookup tables with cv2.LUT, plus NumPy versions you can run.

Some image operations do not look at a pixel's neighbors at all. They take each pixel value, put it through a function, and write the result back. These are called point operations or intensity transformations, and they are the simplest and fastest way to change how bright, dark or contrasty an image looks. The formula is just s = T(r), where r is the input value, s is the output and T is the transformation.

In this lesson you will learn the four classic transformations (negative, log, power-law or gamma, and piecewise-linear contrast stretching), how to apply any of them in one call with a lookup table and cv2.LUT, and when each one helps. The OpenCV calls are shown read-only; NumPy stand-ins let you run the same math. You should be comfortable with Data Types, Ranges and Saturation first.

The idea: a curve from input to output

Picture a graph where the horizontal axis is the input value (0 to 255) and the vertical axis is the output value. A straight diagonal line means "no change". A curve above the diagonal brightens the image; a curve below it darkens. Every intensity transformation is a different curve.

Because an 8-bit image has only 256 possible values, you do not need to compute the function for every pixel. You compute it 256 times, store the results in a table, and let every pixel look up its answer. That table is a lookup table (LUT).

Python
import cv2
import numpy as np

img = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)

table = np.array([255 - i for i in range(256)], dtype=np.uint8)   # the negative curve
negative = cv2.LUT(img, table)

cv2.LUT(src, table) replaces each pixel v by table[v]. For a color image, a 256-entry table is applied to every channel, or a table of shape (256, 1, 3) can give each channel its own curve. LUTs run at memory speed, so a ten-megapixel image takes a few milliseconds.

Negative

The negative flips the scale: s = 255 - r. Dark becomes bright and bright becomes dark. It is useful for viewing white details on a dark background, for medical images such as X-rays, and for inverting a mask.

Python
negative = 255 - img               # NumPy: works for uint8
negative = cv2.bitwise_not(img)    # OpenCV: same result

Do not write -img on an unsigned array; it wraps around in a confusing way. 255 - img is safe because 255 is the largest possible value, so the result never goes below zero.

Log transformation

The log transformation is s = c * log(1 + r). It expands dark values and compresses bright ones. A tiny difference between two dark pixels becomes a visible difference, which is why it is used to display data with a huge range, such as the Fourier spectrum of an image, where a few pixels are enormous and the rest are tiny.

The constant c scales the result so the largest output is 255: c = 255 / log(1 + max).

Python
img_f = img.astype(np.float32)
c = 255 / np.log(1 + img_f.max())
log_img = (c * np.log(1 + img_f)).astype(np.uint8)

The inverse operation, the exponential (anti-log) transform, does the opposite: it spreads out the bright values and squeezes the dark ones.

Power-law (gamma) transformation

The most useful curve in practice is the power-law or gamma transformation:

s = 255 * (r / 255) ** gamma

Notice that we first scale r to the range 0 to 1, raise it to a power, then scale back. The exponent gamma decides the effect:

gamma Effect Typical use
below 1 (for example 0.5) Brightens, especially the shadows Lift detail in a dark photo
exactly 1 No change
above 1 (for example 2.2) Darkens, especially the highlights Tame an overexposed image

The name comes from displays. Monitors do not produce light in proportion to the signal; they apply roughly a power of 2.2. Gamma correction applies the inverse so that the final result looks right. Today, when you work with a photo from a camera, a gamma below 1 is the quick way to make a dark photo readable without washing out the highlights, which a plain "add 50" would do.

Python
def gamma_lut(gamma):
    return np.array([255 * (i / 255) ** gamma for i in range(256)]).astype(np.uint8)

brighter = cv2.LUT(img, gamma_lut(0.5))
darker   = cv2.LUT(img, gamma_lut(2.2))

Piecewise-linear transformations

Sometimes you want a custom curve built from straight segments. The most common is contrast stretching. A low-contrast image uses only part of the 0 to 255 range, for example 90 to 160. Stretching maps that narrow band to the whole range:

s = (r - r_min) * 255 / (r_max - r_min)

In OpenCV, cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX) does exactly this in one call. A more general form uses two control points (r1, s1) and (r2, s2): values below r1 are compressed, values between r1 and r2 are stretched, and values above r2 are compressed again. Other piecewise curves are thresholding (a step), and intensity-level slicing, which highlights one range of values (say, 100 to 150) and leaves the rest alone or dims it.

Python
stretched = cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX)

For noisy images, stretch using percentiles rather than the true minimum and maximum, because one stray bright pixel would otherwise limit the stretch: lo, hi = np.percentile(img, (2, 98)). Histogram-based methods that choose the curve for you are in Histograms and Equalization.

Choosing a transformation

  • Image too dark, shadows hidden: gamma below 1, or log.
  • Highlights blown out: gamma above 1.
  • Low contrast ("foggy") image: contrast stretching, or equalization.
  • Need to see small differences in huge dynamic range data: log.
  • Want to invert polarity: negative.

All of these are global: the same curve is used for every pixel. If the image has a bright region and a dark region at once, a global curve cannot fix both, and local methods such as CLAHE do better.

Try it: build the curves and apply a LUT

The code below builds each lookup table in NumPy and applies it by indexing, which is exactly what cv2.LUT does. The test image is a gradient strip, so you can read the effect from the numbers.

Python Negative, log and gamma lookup tables

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.

Look at the darkest sample, 32. With gamma 0.5 it jumps to 90, and with the log curve to 110, while the brightest sample, 255, stays at 255 in every brightening curve. That is the "expand the shadows, keep the highlights" behavior.

Try it: contrast stretching and level slicing

Here a low-contrast image occupies only the values 100 to 140. The program stretches it to the full range, using both the min and max and a percentile version that ignores one stray pixel, and then slices out a band of levels.

Python Contrast stretching and intensity slicing

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 naive stretch uses the stray 255 as the maximum, so the real data (about 100 to 140) is squeezed into the lower quarter of the output range. The percentile version ignores that single pixel and spreads the real data across nearly the whole range.

What is real: the formulas, the LUT idea, 255 - img, cv2.LUT and cv2.normalize behave as described. What is the stand-in: the OpenCV calls cannot run in the browser, so NumPy table indexing plays the role of cv2.LUT; results are identical for 8-bit images up to rounding.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which gamma value brightens the dark parts of an image?

    s = 255 * (r/255)**gamma. With gamma below 1 the curve lies above the diagonal, so dark values rise. Above 1 it darkens.
  2. 2. Why is a lookup table fast for 8-bit images?

    There are only 256 possible input values, so you compute the curve once per value and every pixel just indexes the table.
  3. 3. What does the log transformation do to an image?

    log(1 + r) rises steeply for small r, so small differences among dark pixels become visible. It is common for displaying spectra.
  4. 4. What does cv2.normalize(img, None, 0, 255, cv2.NORM_MINMAX) do?

    NORM_MINMAX linearly rescales the range of values, which is contrast stretching.
  5. 5. Why is stretching with percentiles often better than using the true min and max?

    One stray very bright or dark pixel sets the min or max and wastes most of the output range. Percentiles ignore the extreme tails.

Summary

  • An intensity transformation maps each pixel value through a curve s = T(r) without looking at neighbors.
  • Negative is 255 - r; log expands the darks (c * log(1 + r)); gamma is 255 * (r/255) ** gamma (below 1 brightens, above 1 darkens); contrast stretching is a piecewise-linear remap of a narrow band to 0 to 255.
  • For 8-bit images, build a 256-entry table once and apply it with cv2.LUT; use cv2.normalize(..., NORM_MINMAX) for plain stretching.
  • Use percentiles to stay robust against outliers, and CLAHE when brightness varies across the image.

Next: let the data choose the curve in Histograms and Equalization.