v9.1.1
Menu

Image-like Reshaping

mediumFREEReshaping & StackingNumPy ReshapingNumPy Foundations

Problem Statement

Reshape flat data into image-like 3D arrays and back.

Background

Images are typically 3D arrays: (height, width, channels)

  • Grayscale: (H, W, 1)
  • RGB: (H, W, 3)

Flattening and reshaping is common in deep learning:

  • Flatten for fully-connected layers
  • Reshape for convolutional layers

Your Task

Write a function image_reshape(flat_data, height, width, channels) that:

  1. Reshapes flat data to image shape (H, W, C)
  2. Also returns channel-first format (C, H, W)
  3. Returns flattened form

Output Format

Return a dictionary with:

  • "image": Shape (H, W, C) as list
  • "channels_first": Shape (C, H, W) as list
  • "flat": Flattened as list
  • "shape": Original image shape as list

Example

Input
data = [0..11], height = 2, width = 2, channels = 3
Output
Image shape [2, 2, 3], channels_first shape [3, 2, 2]
Reasoning
  • Inputs: flat_data is the 12 numbers 0,1,…,110, 1, \dots, 11 in one line; height =2=2, width =2=2, channels =3=3; 2×2×3=122 \times 2 \times 3 = 12 slots, one per number.
  • Image layout (H,W,C)(H, W, C): channel varies fastest, then column, then row. The value at row hh, column ww, channel cc is 6h+3w+c6h + 3w + c. Pixel (0,0)(0,0) holds [0, 1, 2], pixel (0,1)(0,1) holds [3, 4, 5], and the second row holds [6, 7, 8] and [9, 10, 11].
  • Channels first (C,H,W)(C, H, W): each channel becomes its own 2×22 \times 2 plane: entry (c,h,w)(c, h, w) equals image entry (h,w,c)(h, w, c). Channel 0 collects 0,3,6,90, 3, 6, 9 → [[0, 3], [6, 9]]; channel 1 is [[1, 4], [7, 10]]; channel 2 is [[2, 5], [8, 11]]. Shape [3, 2, 2].
  • flat and shape: reading the image back in the same order returns 00 through 1111 unchanged; shape is [2, 2, 3].
  • Notice channels-first is not the 12 numbers re-cut in order into a 3×2×23 \times 2 \times 2 block; each value keeps its pixel and channel.

Constraints

  • len(flat_data) == height * width * channels
  • Use np.transpose for axis reordering

More from NumPy Foundations

solution.py

Test results

Sign in to run your code against the test cases.