Sub topic 2
Colour from red, green, and blue
This chapter assumes you can read Python, index a NumPy array, and read binary values. Here, uint8 means an 8-bit unsigned integer, which holds values from 0 to 255.
Colour from red, green, and blue
A screen makes colour by mixing red, green, and blue light. Each pixel stores one number per primary. Setting all three to 255 gives white, and setting all three to 0 gives black.
import numpy as np
img = np.zeros((1, 3, 3), dtype=np.uint8)
img[0, 0] = (255, 0, 0) # red
img[0, 1] = (0, 255, 0) # green
img[0, 2] = (0, 0, 255) # blue
print(img[0])[[255 0 0]
[ 0 255 0]
[ 0 0 255]]The alpha channel and transparency
An alpha channel is an extra value per pixel that sets opacity. A value of 255 is fully opaque, and 0 is fully transparent. An RGBA image stores four channels per pixel.
Working out raw image size
Raw size is width × height × channels × bytes per sample. For a 1920 × 1080 image at 8 bits per sample:
width, height, channels, bytes_per_sample = 1920, 1080, 3, 1
raw_bytes = width * height * channels * bytes_per_sample
print(raw_bytes) # 6220800Adding an alpha channel makes the same image RGBA, with four channels, and 8294400 bytes.
How pixels are arranged in memory
Most libraries store an image row by row, with the channels of each pixel next to each other. The strides tell NumPy how many bytes to step along each axis.
import numpy as np
img = np.zeros((2, 3, 3), dtype=np.uint8)
print(img.shape) # (2, 3, 3): height, width, channels
print(img.strides) # (9, 3, 1)Stepping one row moves 9 bytes, one pixel moves 3 bytes, and one channel moves 1 byte.
RGB versus BGR and other channel orders
OpenCV stores channels in BGR order. Reversing the last axis converts between RGB and BGR.
bgr = img[..., ::-1]This creates a view, not a copy. Call .copy() if a library needs a contiguous array.
What a colour space defines
Numbers alone do not give a colour. A colour space defines what each value means, including its primaries, white point, and transfer curve. The triple (255, 0, 0) is a different red in sRGB than in Adobe RGB. sRGB values are gamma encoded, so a stored value of 128 carries about 22% of full light, not half.
Exercise
Exercise
A 640 × 480 RGBA image uses 8 bits per sample. How many raw bytes does it need?
Show answer
640 × 480 × 4 × 1 = 1228800 bytes.