QuiddityML

Classical image processing: brightness, contrast, clipping, and thresholding

How to brighten an image, stretch its contrast and turn it into a black and white mask with one rule per pixel, what clipping destroys along the way, and the PyTorch code for each step.

Computer VisionBy · 3 December 2026 · 10 min read

Classical image processing is changing or measuring an image with fixed rules written by hand, with no training involved. A grayscale image is a grid of numbers, one per pixel, and each rule is arithmetic on those numbers. These rules brighten photos, clean up masks and prepare images before a neural network sees them. The simplest ones change each pixel using only its own value. That family covers brightness, contrast, clipping and thresholding.

What fixed rules can do

A grayscale image usually stores one number per pixel from 0 for black to 255 for white. A fixed rule turns those numbers into new numbers and gives the same answer every time it runs. For example, slide a small 3 by 3 grid of weights over the image. Depending on its nine numbers, it blurs the image, sharpens it or marks its edges.

Neural networks for images read pixels with the same kind of sliding grid. The difference is where the nine numbers come from. A network learns them from data, and a classical filter uses numbers a person chose.

Three 3 by 3 grids of weights labelled blur, sharpen and edges, with a note that fixed filters use nine numbers chosen by hand and neural networks learn their nine numbers from data.

Fixed rules are still in daily use. They clean up rough masks, measure and count objects, and prepare images before a model sees them. They also help with debugging, since the output of a simple rule shows exactly what that rule can find in the pixels.

Five uses of fixed filters: clean up rough masks, measure object sizes, count objects, prepare images for a model and debugging.

Point operators

A point operator computes each output pixel only from the input pixel at the same position. Neither the pixel's position nor its neighbors affect the result.

Brightening, changing contrast and thresholding are point operators. Blurring and edge detection are not, because they read the surrounding pixels too.

A 5 by 5 patch where every value gets 40 added, with 120 becoming 160, above two grids showing that a point operator reads 1 input pixel and a blur reads 9.

For example, take a grayscale row of five pixels, $[10, 60, 120, 200, 250]$. Add 30 to each and clamp the result to the range 0 to 255, so that anything above 255 becomes 255:

  • $10 + 30 = 40$
  • $60 + 30 = 90$
  • $120 + 30 = 150$
  • $200 + 30 = 230$
  • $250 + 30 = 280 \rightarrow 255$

The result is $[40, 90, 150, 230, 255]$. Each output used only the one input above it. The brightest pixel lost information at the clamp, because every input from 225 up now comes out as 255.

The row 10, 60, 120, 200, 250 passed through out = in + 30, giving 40, 90, 150, 230 and a clamped 255.

A point operator is a curve

A point operator turns one number into one number, so you can plot it with the input value on the x-axis and the output value on the y-axis. That one curve says what the operator does to every pixel in the image. In the plot below, the dashed diagonal is the curve that leaves each pixel unchanged.

A curve of output against input from 0 to 255, bending below the dashed diagonal in the darks and above it in the brights.

The same operator as a lookup table

An 8-bit pixel can take only 256 values. So a point operator on 8-bit images is fully described by a table of 256 entries, where lut[v] is the output for the input value v. This table is called a lookup table, or LUT. Build it once, and processing each pixel becomes one array lookup.

import torch

# (2, 3)
img = torch.tensor(
    [[10, 60, 120], [200, 250, 5]],
    dtype=torch.uint8)
# (256,)
lut = torch.clip(
    torch.arange(256, dtype=torch.int16) + 30,
    0, 255).to(torch.uint8)
out = lut[img.long()]                 # (2, 3), uint8
print(out)
# tensor([[ 40,  90, 150],
#         [230, 255,  35]], dtype=torch.uint8)

torch.arange(256) lists every possible pixel value, and adding 30 and clipping turns that list into the table. lut[img.long()] uses each pixel value as an index into lut. The .long() is needed because PyTorch does not accept a uint8 tensor as a list of positions. The output has the same shape and dtype as the image, and the cost stays at one lookup per pixel however complicated the curve is. The same steps as a function:

def brighten_lut(img, k):
    ramp = torch.arange(256, dtype=torch.int16) + k
    lut = torch.clip(ramp, 0, 255).to(torch.uint8)
    return lut[img.long()]

print(brighten_lut(img, 30))
# tensor([[ 40,  90, 150],
#         [230, 255,  35]], dtype=torch.uint8)

A lookup table with entries lut[5] = 35 up to lut[250] = 255, applied to six pixels, with 250 clamped to 255.

Min-max scaling

A raw image from a 16-bit sensor can hold values in the thousands. Min-max scaling maps an image's actual range onto 0 to 1:

$$out = \frac{in - \min}{\max - \min}$$

Here $\min$ and $\max$ are the smallest and largest pixel values in the image. The darkest pixel becomes 0 and the brightest becomes 1. For example, a patch from a 16-bit sensor holds $[1200, 1800, 2400, 4000]$. The minimum is 1200 and the range is $4000 - 1200 = 2800$.

  • $(1200 - 1200) / 2800 = 0$
  • $(1800 - 1200) / 2800 \approx 0.214$
  • $(2400 - 1200) / 2800 \approx 0.429$
  • $(4000 - 1200) / 2800 = 1$

The gaps between values keep their size relative to the range. In code:

def min_max_scale(img):
    lo = img.min()
    hi = img.max()
    return (img - lo) / (hi - lo)

patch = torch.tensor([1200., 1800., 2400., 4000.])
print(min_max_scale(patch))
# tensor([0.0000, 0.2143, 0.4286, 1.0000])

Four 16-bit sensor values 1200, 1800, 2400 and 4000 with min 1200, max 4000 and range 2800, scaled to 0.00, 0.214, 0.429 and 1.00.

Brightness and contrast

A brightness change adds the same constant $b$ to every pixel:

$$out = in + b$$

A positive $b$ makes the whole image lighter, and a negative $b$ makes it darker. A histogram of an image counts how many pixels have each value. A brightness change slides that histogram sideways.

A contrast change scales how far each value sits from the middle gray of 128. The scale factor is $a$:

$$out = a \cdot (in - 128) + 128$$

With $a > 1$, darks get darker and brights get brighter, so the histogram spreads out. With $a < 1$, each value moves toward gray and the histogram gets narrower.

Three histograms against the original drawn as a white line: brightness slides it sideways, contrast with a above 1 spreads it out, and contrast with a below 1 squeezes it toward 128.

Contrast on four pixels

Take the pixels $[64, 118, 138, 210]$ and raise the contrast with $a = 1.5$:

  • $1.5 \cdot (64 - 128) + 128 = 32$
  • $1.5 \cdot (118 - 128) + 128 = 113$
  • $1.5 \cdot (138 - 128) + 128 = 143$
  • $1.5 \cdot (210 - 128) + 128 = 251$

The two midtones near 128 barely moved, to 113 and 143. The dark and bright pixels were pushed apart, from 64 to 32 and from 210 to 251.

Four dots at 64, 118, 138 and 210 on a line from 0 to 255, moving away from the midpoint 128 to 32, 113, 143 and 251 with a = 1.5.

Brightness and contrast in PyTorch

Deep learning code usually stores pixels as decimals from 0 to 1, so the middle gray becomes 0.5 instead of 128. Both changes are one line each, followed by a clip that keeps the result between 0 and 1:

import torch

# pixels in [0, 1]
x = torch.tensor([0.10, 0.46, 0.54, 0.82], dtype=torch.float32)

def adjust(x, contrast, brightness):
    scaled = (x - 0.5) * contrast + 0.5
    shifted = scaled + brightness
    return torch.clip(shifted, 0.0, 1.0)

print(adjust(x, contrast=1.5, brightness=0.0))
# tensor([0.0000, 0.4400, 0.5600, 0.9800])
print(adjust(x, contrast=1.0, brightness=0.2))
# tensor([0.3000, 0.6600, 0.7400, 1.0000])

contrast scales the distance from 0.5, and brightness shifts every value by the same amount. With contrast 1.5, the 0.10 pixel would land at $-0.1$, so the clip sets it to 0. With brightness 0.2, the 0.82 pixel would reach 1.02, so the clip sets it to 1. The final clip is where shadows and highlights are lost when either setting is pushed too far.

Four gray swatches 0.10, 0.46, 0.54 and 0.82 after contrast 1.5, with 0.10 clipped to 0.0, and after brightness +0.2, with 0.82 clipped to 1.0.

Revealing or destroying detail

Raising contrast on a flat, low-contrast image can separate an object from a background that looked the same. Brightening an underexposed photo can bring a dark subject into a readable range. Push either too far and detail turns into pure black or pure white. A change that reveals one region can clip another.

The same room photographed twice: the original keeps the trees outside the window, and the brightened version makes the dark corner readable while the window clips to flat white.

Brightness, contrast and a trained model

Changing brightness and contrast at random during training teaches a model to ignore the lighting level. This is called augmentation. The same change made by accident, such as a preprocessing step that differs between training and use, sends the model inputs unlike the ones it learned from. Comparing the histograms of the training images with those of the images in use shows whether the brightness has shifted.

Top: darker, normal and brighter copies of a mountain lake all labelled mountain lake by a model trained with augmentation. Bottom: a model trained only on normal images labels the too-dark copy night sky and the too-bright copy snowfield.

Clipping

Clipping forces any value below the minimum up to the minimum, and any value above the maximum down to the maximum. Values inside the range pass through unchanged. For 8-bit pixels the range is 0 to 255:

$$out = \min(255,\ \max(0,\ in))$$

A camera sensor clips when it collects more light than it can count. A clip step in code does the same whenever a calculation produces a value outside the range.

The clipping curve: a flat red line at 0 for inputs below 0, a straight teal line from 0 to 255, and a flat red line at 255 for inputs above 255.

For example, take $[-30, 40, 150, 260, 300]$ from a contrast stretch that went too far and clip it to 0 to 255:

  • $-30 \rightarrow 0$
  • $40 \rightarrow 40$
  • $150 \rightarrow 150$
  • $260 \rightarrow 255$
  • $300 \rightarrow 255$

The two different inputs 260 and 300 now both read 255. Their original values are gone.

Five input values -30, 40, 150, 260 and 300 mapped to 0, 40, 150, 255 and 255, with 260 and 300 both landing on 255.

Clipped detail does not come back

When a bright region clips, every pixel in it reads the same maximum value. The folds on a white shirt or the wisps of cloud in a bright sky disappear. A face in deep shadow that clips to 0 becomes a flat black shape.

Clipping can happen at capture, in a contrast step that overshoots or in a random brightness change that pushes highlights past the limit. The original values are not stored anywhere afterward, so software that claims to recover clipped highlights is guessing.

The true light across a bright shirt rises above 255 with two fold peaks, while the stored pixels sit flat at 255 across that whole stretch.

Thresholding

Thresholding turns a value into a yes or no: 1 above a cutoff and 0 below it. The value can be a brightness, one color channel or a model's score for each pixel. The result is a mask, an image of 0s and 1s that marks which pixels belong to the object.

A global threshold uses one cutoff $T$ for the whole image, so every pixel brighter than $T$ becomes foreground. It works when the object and the background are cleanly separated by value across the entire frame.

A step function: output 0 for values below the threshold T and 1 above it, on an input axis from 0 to 255.

For example, take this 3 by 3 patch of intensities:

$$\begin{bmatrix} 40 & 55 & 60 \\ 120 & 200 & 210 \\ 90 & 205 & 195 \end{bmatrix}$$

Set each pixel to 1 if it is above 127 and to 0 otherwise:

$$\begin{bmatrix} 0 & 0 & 0 \\ 0 & 1 & 1 \\ 0 & 1 & 1 \end{bmatrix}$$

The four pixels above 127 became foreground and the five below became background. One number turned a grid of intensities into a grid of decisions.

The 3 by 3 patch of intensities next to its mask, with the four pixels above 127 set to 1.

In PyTorch:

import torch

patch = torch.tensor([[ 40,  55,  60],
                      [120, 200, 210],
                      [ 90, 205, 195]], dtype=torch.uint8)

# (3, 3), values 0 or 1
mask = (patch > 127).to(torch.uint8)
print(mask)
# tensor([[0, 0, 0],
#         [0, 1, 1],
#         [0, 1, 1]], dtype=torch.uint8)
print(mask.sum())   # tensor(4), 4 foreground pixels

patch > 127 gives a tensor of True and False values, and .to(torch.uint8) turns it into a mask of 0s and 1s. Summing the mask counts the foreground pixels. The same steps as a function:

def threshold(patch, t):
    above = patch > t
    mask = above.to(torch.uint8)
    return mask

Adaptive thresholding

When the lighting changes across an image, one cutoff fails. A value that counts as foreground in a bright corner is background in a dark one. Adaptive thresholding computes a separate cutoff for each region from the pixels around it, such as the mean of a small window centered on each pixel.

A page with a dark shadow in one corner, the same page after a global threshold with the shadowed corner turned solid black, and after an adaptive threshold with all the text readable.

Where thresholding works

Thresholding turns a model's score map into a mask, separates ink from paper in a scanned document and isolates a bright defect in an inspection image. It reads only each pixel's value, with no sense of shape or context. It handles the cases where value alone separates the object from the background. When the two share the same values, the mask mixes them together.

Ink on paper thresholded into a clean mask, and a gray mug on a gray wooden table thresholded into a mask that mixes the mug with stripes of wood grain.

When to use these, and common mistakes

Use a point operator when the change depends only on each pixel's value: brightening, adjusting contrast, rescaling a raw sensor image or turning a score map into a mask. When the change depends on structure, such as blurring or finding edges, you need a filter that reads the neighboring pixels too.

  • Pushing contrast or brightness until values clip. Count how many pixels sit at 0 or 255 after the change. Clipped detail cannot be recovered later.
  • Changing brightness or contrast in preprocessing at test time only. The model then sees inputs unlike its training images. Apply the same preprocessing in both places, and use random changes during training if the lighting varies in use.
  • Using one global threshold on an unevenly lit image. Switch to adaptive thresholding, which picks a cutoff per region.
  • Expecting a threshold to find an object by its shape. It compares values only, so it fails when the object and the background have the same brightness.
  • Indexing a lookup table with a uint8 tensor. Convert the image with .long() first.

Point operators read one pixel. Neighborhood operators read a small window around each pixel, and blurring, sharpening and edge detection all work that way. Image convolution explained covers the sliding window, kernels, padding and stride. Image blurring and denoising covers the box, Gaussian and median filters. Image normalization for deep learning covers pixel ranges, mean and std standardization, and spotting clipping in a histogram.

QuiddityML teaches these ideas in the classical image processing unit of its Computer Vision track, where the exercises include writing a lookup-table brightener and spotting the bug in a threshold function (QuiddityML).