Sub topic 5
Grayscale and Binary Images
Assume you know basic Python and understand arrays, bytes, pixels, and bit depth. This chapter focuses on how colour images become grayscale or binary images, and when each representation is useful.
Grayscale images
A grayscale image has one channel per pixel instead of separate red, green, and blue channels. The channel stores brightness.
For an 8-bit grayscale image, each sample uses 8 bits, or 1 byte. It can represent:
2^8 = 256values, from 0 for black to 255 for white. A value such as 128 represents a middle brightness value in the stored encoding.
A grayscale array commonly has shape (height, width):
import numpy as np
gray = np.array([
[0, 64, 128],
[192, 224, 255]
], dtype=np.uint8)
print(gray.shape) # (2, 3)
print(gray.nbytes) # 6Some libraries represent the same image with shape (height, width, 1). The final dimension means “one channel.” Check the library's convention before indexing or passing the array to a model.
Converting RGB to grayscale
A simple average of red, green, and blue is usually a poor brightness estimate because human vision is more sensitive to green than to blue. A common conversion uses Rec. 601 luma weights:
Y = 0.299R + 0.587G + 0.114BHere, Y is the grayscale value. The result is often rounded and stored as an integer.
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])
gray = np.rint(rgb @ weights).astype(np.uint8)
print(gray)
# [[ 76 150]
# [ 29 255]]The red, green, and blue pixels do not become equally bright. Green produces the largest grayscale value because of its largest weight.
Binary images and thresholding
A binary image has only two possible values. It is often stored as 0 and 1, or as 0 and 255 when saved as an 8-bit image. Binary images are useful for masks, document text, object silhouettes, and yes-or-no decisions.
Thresholding converts grayscale values into binary values:
B(x,y) =
\begin{cases}
1 & \text{if } G(x,y) \geq T \\
0 & \text{otherwise}
\end{cases}T is the threshold. A fixed threshold works when lighting is consistent. Adaptive thresholding is often better when different parts of an image have different illumination.
import numpy as np
gray = np.array([[20, 100, 180],
[70, 130, 240]], dtype=np.uint8)
threshold = 128
binary = (gray >= threshold).astype(np.uint8)
print(binary)
# [[0 0 1]
# [0 1 1]]A binary result removes gradual brightness information. Pixels near an object boundary can therefore switch abruptly between background and foreground. Anti-aliased edges, shadows, and uneven lighting can make a thresholded mask noisy.
Exercise
An 8-bit grayscale image contains 640 × 480 pixels. How many bytes does its raw pixel array use, ignoring metadata and padding?
Show answer
It uses 640 × 480 × 1 = 307,200 bytes, because each pixel has one 8-bit, or one-byte, sample.