Kumita← Open visual lesson

Flattening

The code behind the picture

Follow the lesson’s implementation, one code cell at a time.

Choose a language and read the cells in order. These are small teaching examples; the visual lesson runs separately.

Follow the calculation

Same inputs · Same operation · Same result

3 teaching cells · Python standard library · Read-only

  1. 1. Prepare the inputs

    Use these small, explicit inputs to follow the calculation.

    import json
    
    image = [[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]
  2. 2. Choose a reading order

    HWC visits all channels of each pixel. CHW visits every location of one channel before moving to the next. Both retain all twelve values.

    hwc = [v for row in image for pixel in row for v in pixel]
    chw = [image[r][c][k] for k in range(3) for r in range(2) for c in range(2)]
    result = {"HWC": hwc, "CHW": chw}
  3. 3. Inspect the result

    Print the result as JSON so both languages use the same output format.

    print(json.dumps(result))

Expected result

Running the three cells in order produces this result in either language.

{
  "HWC": [
    1,
    2,
    3,
    4,
    5,
    6,
    7,
    8,
    9,
    10,
    11,
    12
  ],
  "CHW": [
    1,
    4,
    7,
    10,
    2,
    5,
    8,
    11,
    3,
    6,
    9,
    12
  ]
}