#136Images as tensors — the shapeEasy

Images as tensors — the shape

Background

A model sees an image as a numeric tensor. The shape depends on the channels:

  • Grayscale → a 2D matrix of shape (H,W)(H, W) — one intensity per pixel.
  • RGB → a 3D tensor of shape (H,W,3)(H, W, 3) — red, green, blue per pixel.

Problem statement

Implement image_shape(H, W, mode) returning the tensor shape for an image of height H, width W, in the given color mode.

Input

  • Hint, image height (rows).
  • Wint, image width (columns).
  • mode"grayscale" or "rgb".

Output

Returns a shape tuple: (H, W) for grayscale, (H, W, 3) for RGB.

Examples

Example 1 — an MNIST digit

Input:  H = 28, W = 28, mode = "grayscale"
Output: (28, 28)

Example 2 — an ImageNet crop

Input:  H = 224, W = 224, mode = "rgb"
Output: (224, 224, 3)

Constraints

  • Grayscale → (H, W); RGB → (H, W, 3).
  • Return a Python tuple.

Notes

  • Frameworks often add a leading batch dimension N and may put channels first ((N, C, H, W) in PyTorch) — but the per-image content is the same pixel grid.
Python
Loading...

▶ Run executes the 3 visible sample tests below in your browser. Submit runs the full suite — including hidden tests — on the server for an official verdict.

  • example grayscale MNIST
  • reference rgb ImageNet crop
  • sample non-square grayscale