Skip to content
Tutorials Center
My learning

Topics

Lesson 8 of 54 ยท Pixels and Color

Data Types, Ranges and Saturation

Learn why uint8 pixels wrap around, how OpenCV saturates instead, when to use float32 images in the 0-1 range, and how convertScaleAbs and normalize rescale values.

An 8-bit image stores every channel value in one byte, so each pixel value is a whole number from 0 to 255. That is compact and fast, but it is also a trap: what should 200 + 100 be? Mathematics says 300, a byte cannot hold 300, and the answer you get depends on which library does the adding.

This lesson explains the data types you meet in OpenCV code, the difference between wraparound (NumPy) and saturation (OpenCV functions), when to switch to floating point, and how convertScaleAbs and normalize bring values back into a displayable range. If you want a refresher on arrays and dtype first, read Images Are NumPy Arrays and NumPy Data Types.

What runs here: the cv2 calls below are shown in read-only code blocks, because opencv-python cannot run in the browser. Every idea also has a live NumPy stand-in that you can edit and run. The stand-ins reproduce the rules OpenCV follows (round, clip, cast); they are not OpenCV's own optimized code.

The data types you will meet

Most images you load are uint8. Many OpenCV functions also accept or produce other types, and the type decides what values are legal.

Four dtypes you will see

uint8 0 to 255. Normal photos and video frames.
uint16 0 to 65535. Depth maps and some cameras.
float32 Fractions. Filtering and math, often 0 to 1.
int16 / int32 Signed. Derivatives can go negative.

The dtype tells you the range. Check it before you do math.

1 / 2

In Python an OpenCV image is just a NumPy array, so img.dtype tells you the type. uint8 is by far the most common. Signed types appear when a result can be negative, for example the output of a derivative filter (you will meet those in Gradients, Sobel and Laplacian).

Wraparound: what NumPy does

NumPy arithmetic on uint8 arrays stays in uint8. When a result does not fit, NumPy keeps only the lowest 8 bits, which is the same as taking the result modulo 256. A bright pixel plus a bright pixel becomes a dark pixel, and a subtraction that goes below zero jumps to a large number.

Python uint8 wraparound 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.

Look at the second pixel pair: 100 + 100 is 200, which fits. The third, 200 + 100, is really 300, and the stored answer is 44, because 300 minus 256 is 44. The last pair 250 + 10 becomes 4. In an image this shows up as a bright region that suddenly turns black, which is exactly what makes this a favorite bug (see Common Mistakes and Debugging).

Saturation: what OpenCV does

OpenCV's arithmetic functions use saturation arithmetic: compute the true result, then clip it to the legal range of the output type. For uint8 that range is 0 to 255, so 200 + 100 gives 255 and 10 - 20 gives 0. Bright stays bright and dark stays dark.

Python
import cv2
import numpy as np

a = np.array([[200]], dtype=np.uint8)
b = np.array([[100]], dtype=np.uint8)

print(a + b)            # NumPy: [[44]]  (wraps)
print(cv2.add(a, b))    # OpenCV: [[255]]  (saturates)
print(cv2.subtract(b, a))  # [[0]]  (clips at zero)

The cv2 calls above are read-only here. Below is a stand-in that does what saturation does: widen, compute, clip, cast back.

Python A saturating add and subtract

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 pattern "widen, compute, clip, cast" is the one to remember. It is also how you should write your own pixel math in NumPy when you want OpenCV-like behavior.

Warning: img + 50 in NumPy does not saturate. If you add a Python integer to a uint8 array, the result stays uint8 and wraps. Use cv2.add(img, 50) or the widen-and-clip pattern. Note that cv2.add(img, 50) with a bare scalar has a historical quirk (a scalar is treated as a four-value tuple, so only the first channel changes on a color image). Passing a full array such as np.full_like(img, 50) avoids it.

Float images in the 0 to 1 range

Integer images are great for storage, but awkward for math. Multiplying by 0.5 gives fractions that must be rounded, and repeated steps accumulate rounding error. The common fix is to convert to float32, scale to the range 0 to 1, do the work, and convert back at the end.

Python
import cv2
import numpy as np

img = cv2.imread("photo.jpg")                 # uint8, 0..255
f = img.astype(np.float32) / 255.0            # float32, 0..1
f = f ** 0.8                                  # gamma, no rounding yet
out = np.clip(f * 255.0, 0, 255).astype(np.uint8)

Two things deserve care. First, clip before casting: converting a float such as 300.7 to uint8 is undefined for out-of-range values, and negative floats are no better. Second, round, do not truncate: astype truncates toward zero, so 127.9 becomes 127. Use np.round (or add 0.5) when you want the nearest integer.

Python uint8 to float32 and back

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.

Notice that the brightened value for 255 is 1.4, which is past the legal 1.0 for a float image. Many OpenCV functions do not clip floats for you; the clip happens when you convert back. When you display a float image with imshow, OpenCV assumes the range is 0 to 1; with imwrite, you must convert to uint8 first.

convertScaleAbs: scale, shift, absolute value, saturate

cv2.convertScaleAbs(src, alpha=1, beta=0) computes |alpha * src + beta|, rounds, saturates to uint8 and returns an 8-bit image. It is the standard way to turn a signed or float result into something you can show, and also a one-line contrast and brightness control (alpha is contrast, beta is brightness).

Python
bright = cv2.convertScaleAbs(img, alpha=1.0, beta=40)   # brighter
punchy = cv2.convertScaleAbs(img, alpha=1.5, beta=0)    # more contrast
edges8 = cv2.convertScaleAbs(sobel_x)                   # signed -> 8-bit
Python A convertScaleAbs stand-in

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 absolute value is the surprising part: a strong negative derivative (a dark-to-light edge in one direction) and a strong positive one (the other direction) both come out bright, which is what you want when you only care how strong an edge is.

normalize: stretch to fill a range

cv2.normalize rescales values so they fill a target range. With NORM_MINMAX, the smallest input becomes alpha and the largest becomes beta, with everything in between mapped linearly. It is the right tool when a result has an unpredictable range and you want to see it.

Python
vis = cv2.normalize(result, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U)

The formula is out = (x - min) * (beta - alpha) / (max - min) + alpha. A flat image (max equal to min) would divide by zero, so guard that case in your own code.

Python Min-max normalization

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.

normalize stretches contrast but also changes absolute values, so it is for visualization, not for measurements. To compare two images fairly, use the same fixed scale for both.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In NumPy, what is np.uint8(200) + np.uint8(100) stored as in a uint8 array?

    NumPy keeps uint8 arithmetic in uint8 and drops the high bits, so 300 becomes 300 - 256 = 44. OpenCV functions such as cv2.add would give 255 instead.
  2. 2. What does saturation arithmetic do with a result of -15 in a uint8 output?

    Saturation computes the true result, then clips it to the output range. For uint8 that range is 0 to 255, so -15 becomes 0.
  3. 3. Why convert to float32 in the range 0 to 1 before doing several filtering steps?

    Float math keeps fractions and does not wrap, so errors do not pile up. You clip, round and convert back to uint8 only once, at the end.
  4. 4. What does cv2.convertScaleAbs(x, alpha=2, beta=10) compute?

    It scales by alpha, shifts by beta, takes the absolute value, rounds and saturates to 8 bits.

Summary

  • uint8 pixels hold 0 to 255. NumPy arithmetic on them wraps modulo 256; OpenCV functions such as cv2.add and cv2.subtract saturate (clip) instead.
  • To get saturating behavior in NumPy, widen to a larger type, compute, np.clip to 0 to 255, then cast back.
  • Use float32 images in the 0 to 1 range for multi-step math, and clip, round and cast to uint8 only at the end. astype truncates, so round first.
  • convertScaleAbs computes |alpha * x + beta| and saturates to uint8, which is handy for contrast, brightness and signed results.
  • normalize with NORM_MINMAX stretches any range to fill a target range, for viewing rather than measuring.

Next up: draw on your images in Drawing Shapes and Text.