Sub topic 5
Grayscale and binary images
This chapter assumes you can read short NumPy snippets. It also assumes you know that an 8-bit value ranges from 0 to 255 and that an image array has a height and a width. Earlier chapters covered pixels, resolution, bit depth and channels. Here those ideas are applied to the simplest case: images with a single channel.
One number per pixel
A grayscale image has one channel. Each pixel stores a single number for brightness, with no hue. Low values are dark and high values are bright. In an 8-bit image, 0 is black, 255 is white, and the 254 values between are shades of gray.
The array shape is (height, width). There is no channel axis.
import numpy as np
gray = np.array([[0, 64, 128],
[192, 255, 32]], dtype=np.uint8)
print(gray.shape, gray.dtype, gray.nbytes) # (2, 3) uint8 6The raw size follows the formula from the size chapter with channels = 1: 2 × 3 × 1 × 1 = 6 bytes. A grayscale image is one third the size of an RGB image with the same dimensions and bit depth.
Gray levels and bit depth
The bit depth sets how many distinct gray levels exist.
| Bit depth | Levels | Typical use |
|---|---|---|
| 1 | 2 | Binary masks, scanned text |
| 8 | 256 | Most photos, web images, model inputs |
| 12 to 14 | 4,096 to 16,384 | Camera sensors, stored in 16-bit containers |
| 16 | 65,536 | Medical imaging, astronomy, depth maps |
Eight bits is enough for most display purposes, but smooth gradients can show visible bands. Medical and scientific images keep 12 to 16 bits because the small intensity differences carry measurements.
A 12-bit sensor value is usually stored in a 16-bit integer. Unless the file says otherwise, the largest value is 4095, not 65535. Dividing by 255 or by 65535 without checking the real range gives a dark, wrong result.
Getting gray from colour
Converting RGB to gray means collapsing three numbers into one. A plain average treats all channels equally, but the eye is most sensitive to green and least to blue. The standard fix is a weighted sum. This example uses the Rec. 601 luma weights.
import numpy as np
rgb = np.array([[[255, 0, 0], [0, 255, 0]],
[[0, 0, 255], [255, 255, 255]]], dtype=np.uint8)
weights = np.array([0.299, 0.587, 0.114]) # Rec. 601 luma weights
gray = (rgb @ weights).round().astype(np.uint8)
print(gray) # [[ 76 150]
# [ 29 255]]Pure green comes out about twice as bright as pure red, and pure blue is the darkest. The weights sum to 1.0, so white stays at 255.
Different standards use different weights. HDTV (Rec. 709) uses 0.2126, 0.7152 and 0.0722. The results differ by a few levels, which matters when you compare outputs from different libraries.
The weights are applied to gamma-encoded values, not to linear light. The result is called luma, and it only approximates true luminance. For most vision work this is the accepted convention, and the gamma chapter explains the gap. Do not use the plain .mean(axis=2) shortcut and expect it to match a library's grayscale conversion.
Binary images
A binary image has only two values, usually called foreground and background. It records a yes-or-no answer for each pixel, such as "is this ink?" or "is this part of the object?".
The usual way to make one is thresholding. You compare each gray value with a cutoff.
import numpy as np
gray = np.array([[76, 150],
[29, 255]], dtype=np.uint8)
mask = gray > 127
print(mask) # [[False True]
# [False True]]
print(mask.dtype) # boolA fixed cutoff such as 127 fails when lighting varies across the image. Two standard alternatives exist. Otsu's method picks one global threshold automatically from the histogram. Adaptive thresholding computes a separate threshold for each local neighbourhood.
How binary images are stored
"One bit per pixel" describes the information, not necessarily the storage. NumPy stores a bool array with one byte per element. Libraries and file formats often use one of three conventions:
boolarray:FalseandTrue, 1 byte per pixel in memory.uint8with 0 and 255: convenient because it displays directly as black and white.uint8with 0 and 1: convenient for counting and indexing, but it looks almost black if you display it.
Truly packed storage uses 8 pixels per byte.
import numpy as np
mask = np.zeros((8, 8), dtype=bool)
mask[:, ::2] = True # alternate columns: True, False, True, ...
packed = np.packbits(mask, axis=1)
print(mask.nbytes, packed.nbytes) # 64 8
print(packed[0]) # [170] (binary 10101010)That is an 8× saving. Formats such as TIFF and PBM can store 1-bit images this way. Fax-style compression then shrinks long runs of identical pixels much further.
Edge cases to watch
- Shape
(H, W)versus(H, W, 1). Some libraries return grayscale with a trailing channel axis of length 1. Code that expects one form fails on the other. Useimg.squeeze()orimg[..., None]to convert. - Gray stored as three channels. A file can hold an RGB array where every pixel has R = G = B. It looks gray but takes three times the memory. Check
img.ndim, not only how the image looks. - Overflow in
uint8. Arithmetic wraps around instead of saturating.
import numpy as np
a = np.array([200], dtype=np.uint8)
print(a + 100) # [44] (300 wraps to 44)
safe = np.clip(a.astype(np.int16) + 100, 0, 255).astype(np.uint8)
print(safe) # [255]- Inverted polarity. Some formats, such as DICOM's MONOCHROME1 mode, define 0 as white. Check the metadata before assuming 0 is black.
- Display scaling. A 16-bit image shown as if it were 8-bit looks almost entirely white or black. Rescale to the actual range first.
Exercise
A 1000 × 1000 binary mask is held in a NumPy bool array. How many bytes does it use in memory, and how many after np.packbits? Then give one reason you might still keep the bool array during processing.
Show answer
The bool array uses 1 byte per pixel: 1,000 × 1,000 = 1,000,000 bytes. Packed at 8 pixels per byte it needs 1,000,000 / 8 = 125,000 bytes. You might keep the bool array because it supports direct indexing, logical operations and counting, such as mask.sum(). A packed array needs unpacking first.
Exercise
A grayscale value is stored as uint8 200. A script adds 100 to the array and the result is 44. Explain why, and give a fix.
Show answer
uint8 can hold only 0 to 255, so 300 wraps around modulo 256 and gives 44. Convert to a wider type first, such as int16, add, clip to 0 to 255 with np.clip, and convert back to uint8.