TExcelTAD
Home › Data for ML: Types, Formats, Sources & Quality › Images, Audio and Video as Arrays

Images, Audio and Video as Arrays

Photos, X-rays, satellite tiles, voice recordings, engine noise, security camera footage: these are not tables, but to a computer they are something just as simple, arrays of numbers. Once you see the array behind each medium, its size, its value range and its layout, most of the practical questions (how much memory, which model, what can go wrong) answer themselves.

Images: height × width × channels

A greyscale image is a 2-D array: one number per pixel, its brightness. A colour image adds a third axis with one value per channel, usually red, green and blue (RGB). The sample images that ship with scikit-image show both:

python · try it yourself
from skimage import data

gray = data.camera()
rgb = data.astronaut()
for name, img in [("camera", gray), ("astronaut", rgb)]:
    print(f"{name:9} shape={img.shape}  dtype={img.dtype}  min={img.min()}  max={img.max()}  "
          f"size={img.nbytes / 1024:.0f} KiB")
print("top-left pixel of astronaut (R, G, B):", rgb[0, 0])
print("mean brightness per channel:", rgb.reshape(-1, 3).mean(axis=0).round(1))
camera    shape=(512, 512)  dtype=uint8  min=0  max=255  size=256 KiB
astronaut shape=(512, 512, 3)  dtype=uint8  min=0  max=255  size=768 KiB
top-left pixel of astronaut (R, G, B): [154 147 151]
mean brightness per channel: [141.6 105.8  96.5]

Each value is a uint8, an integer from 0 (dark) to 255 (bright). The array order is (height, width, channels), rows first. Other libraries use other conventions, and mixing them up is a classic bug:

Library Layout of one colour image Channel order
scikit-image, Matplotlib, Pillow → NumPy H × W × C RGB
OpenCV (cv2.imread) H × W × C BGR
PyTorch models C × H × W, batches N × C × H × W RGB

A model expects a fixed size and value range, so images are usually resized and scaled to 0–1 floats. Converting the dtype changes the memory too:

python · try it yourself
import numpy as np
from skimage import data
from skimage.transform import resize

rgb = data.astronaut()
small = resize(rgb, (64, 64), anti_aliasing=True)      # floats in 0..1
print("resized:", small.shape, small.dtype, f"range {small.min():.3f}..{small.max():.3f}")
print("bytes: original", rgb.nbytes, "| resized float64", small.nbytes,
      "| as float32", small.astype(np.float32).nbytes)

batch = np.stack([small, small[:, ::-1]])              # the image and its mirror
print("batch for a model (N, H, W, C):", batch.shape)
print("PyTorch order (N, C, H, W):", batch.transpose(0, 3, 1, 2).shape)
resized: (64, 64, 3) float64 range 0.000..0.982
bytes: original 786432 | resized float64 98304 | as float32 49152
batch for a model (N, H, W, C): (2, 64, 64, 3)
PyTorch order (N, C, H, W): (2, 3, 64, 64)

Audio: samples over time

Sound is air pressure changing over time. A microphone measures it many times per second, the sample rate: 8,000 Hz for telephone speech, 16,000 Hz for most speech models, 44,100 Hz for music CDs. A mono recording is a 1-D array of samples; stereo has two channels. Here is one second of a 440 Hz tone (the musical note A), written to WAV bytes and read back, as it would be from a file:

python · try it yourself
import io
import numpy as np
from scipy.io import wavfile

rate = 16_000
t = np.arange(rate) / rate                       # 1 second of time stamps
tone = 0.5 * np.sin(2 * np.pi * 440 * t)         # floats in -0.5..0.5
pcm = (tone * 32767).astype(np.int16)            # 16-bit PCM, the usual WAV format

buf = io.BytesIO()
wavfile.write(buf, rate, pcm)
print("WAV file size:", len(buf.getvalue()), "bytes (44-byte header + 2 bytes per sample)")

rate_read, samples = wavfile.read(io.BytesIO(buf.getvalue()))
print("sample rate:", rate_read, "| samples:", samples.shape, samples.dtype)
print("duration:", len(samples) / rate_read, "s | peak:", samples.max())
spectrum = np.abs(np.fft.rfft(samples))
print("strongest frequency:", np.argmax(spectrum) * rate_read / len(samples), "Hz")
WAV file size: 32044 bytes (44-byte header + 2 bytes per sample)
sample rate: 16000 | samples: (16000,) int16
duration: 1.0 s | peak: 16383
strongest frequency: 440.0 Hz

The last line uses a Fourier transform to find the dominant frequency, 440 Hz. Audio models rarely use raw samples directly; they usually turn the waveform into a spectrogram, an image of frequency against time, which is why audio and image models share so many ideas.

Video: a stack of images

A video is a sequence of frames, so its array has one more axis: (frames, height, width, channels). The frame rate (frames per second, fps) plays the role of the sample rate. Here is a tiny synthetic clip of a white square moving to the right:

python · try it yourself
import numpy as np

fps, seconds, h, w = 10, 2, 32, 48
frames = np.zeros((fps * seconds, h, w, 3), dtype=np.uint8)
for i in range(len(frames)):
    x = 2 * i
    frames[i, 12:20, x:x + 8] = 255
print("video array:", frames.shape, frames.dtype, f"{frames.nbytes / 1024:.0f} KiB")

cols = [np.nonzero(f[:, :, 0].any(axis=0))[0] for f in frames]
print("square's left edge in frames 0, 5, 10, 19:", [int(cols[i][0]) for i in [0, 5, 10, 19]])

full_hd_minute = 60 * 30 * 1080 * 1920 * 3
print(f"one minute of uncompressed 1080p at 30 fps: {full_hd_minute / 1e9:.1f} GB")
video array: (20, 32, 48, 3) uint8 90 KiB
square's left edge in frames 0, 5, 10, 19: [0, 10, 20, 38]
one minute of uncompressed 1080p at 30 fps: 11.2 GB

The last line explains why video is always stored compressed (MP4/H.264 and similar codecs) and why video datasets are often sampled down to a few frames per second before training.

Seeing the arrays

python · try it yourself
import numpy as np
import matplotlib.pyplot as plt
from skimage import data

fig, axes = plt.subplots(1, 3, figsize=(10, 3))
axes[0].imshow(data.camera(), cmap="gray")
axes[0].set_title("greyscale: 512 x 512")
axes[1].imshow(data.astronaut())
axes[1].set_title("RGB: 512 x 512 x 3")
t = np.arange(400) / 16_000
axes[2].plot(t * 1000, 0.5 * np.sin(2 * np.pi * 440 * t))
axes[2].set_title("audio: first 25 ms of 440 Hz")
axes[2].set_xlabel("ms")
for ax in axes[:2]:
    ax.axis("off")
fig.tight_layout()
plt.show()
print("drew", len(axes), "panels")
drew 3 panels

Pitfalls

  • Layout and channel order: H × W × C vs C × H × W, RGB vs BGR. A model fed BGR images still runs, it just sees blue skies as orange.
  • Value range: uint8 0–255 vs float 0–1. Dividing twice by 255, or not at all, silently ruins inputs.
  • Sample rate mismatch: a model trained on 16 kHz audio given 44.1 kHz audio hears everything at the wrong pitch and speed. Resample first.
  • Size: media is big. Check memory before loading a whole dataset into one array; load in batches instead.
  • Hidden metadata: photos carry EXIF data (camera, time, often GPS position). Strip it when privacy matters.

Practice

  1. How many bytes does one 224 × 224 RGB image take as uint8, and as float32?
Answer

224 × 224 × 3 = 150,528 values: 150,528 bytes as uint8 (about 147 KiB) and 4 times that, 602,112 bytes, as float32.

  1. A stereo recording at 44,100 Hz lasts 3 seconds. What shape does the array have, if channels are the last axis?
Answer

(132300, 2): 44,100 × 3 samples per channel, two channels.

Test yourself

What is the shape of a 480 x 640 colour image loaded with scikit-image?

  1. (640, 480)
  2. (3, 480, 640)
  3. (480, 640, 3)
  4. (480, 640)

OpenCV's imread returns channels in which order?

  1. RGB
  2. BGR
  3. CMYK
  4. Greyscale only

What does a sample rate of 16,000 Hz mean for audio?

  1. The sound is 16,000 Hz high
  2. The pressure is measured 16,000 times per second
  3. The file is 16,000 bytes
  4. There are 16,000 channels

Why are video datasets usually stored compressed and often sampled at a lower frame rate?

  1. Models cannot read uncompressed video
  2. Uncompressed video is enormous: about 11 GB per minute at 1080p and 30 fps
  3. Compression improves accuracy
  4. Frame rates above 5 fps are illegal