Sub topic 8
Working Out Raw Image Size
Prerequisites and the basic formula
Assume you can read simple Python and understand arrays, bits, and bytes. An image is a grid with a width, a height, and one or more channels. A channel stores one value for each pixel, such as red, green, or blue.
The uncompressed size is:
\text{raw bytes} =
\text{width} \times \text{height} \times \text{channels}
\times \frac{\text{bits per channel}}{8}This formula assumes that samples are packed without extra padding.
For an 8-bit RGB image, each pixel has three channels, and each channel uses one byte:
\text{bytes} = W \times H \times 3 \times 1An RGBA image has four channels because it includes an alpha channel. Alpha usually describes opacity. It therefore needs one-third more storage than an otherwise identical RGB image.
| Image type | Channels | Bits per channel | Bytes per pixel |
|---|---|---|---|
| Grayscale | 1 | 8 | 1 |
| RGB | 3 | 8 | 3 |
| RGBA | 4 | 8 | 4 |
| RGB, high precision | 3 | 16 | 6 |
A worked calculation
A 1920 × 1080 RGB image with 8 bits per channel contains:
1920 \times 1080 \times 3 = 6{,}220{,}800bytes. This is about 5.93 MiB, where 1 MiB is \(1024^2\) bytes.
width, height = 1920, 1080
channels = 3
bits_per_channel = 8
raw_bytes = width * height * channels * bits_per_channel // 8
mib = raw_bytes / (1024 * 1024)
print(f"{raw_bytes:,} bytes")
print(f"{mib:.2f} MiB")For 16-bit samples, multiply the 8-bit result by two. A 16-bit channel can represent \(2^{16} = 65{,}536\) values, compared with \(2^8 = 256\) values for an 8-bit channel. More values can preserve subtle intensity changes, but they require more memory.
Padding and real memory use
Hardware and libraries sometimes add unused bytes at the end of each row. This is called row padding. The number of bytes from the start of one row to the start of the next is the stride.
Therefore, actual allocated memory may be:
\text{stride} \times \text{height}rather than the tightly packed raw size. Inspect an array's shape, data type, and strides instead of assuming every row is packed.
Exercise
How many bytes does a 640 × 480 RGBA image use when each channel is 8 bits?
Show answer
640 × 480 × 4 × 8 ÷ 8 = 1,228,800 bytes, or about 1.17 MiB.