Write a NumPy function that converts an image array from height, width, channel layout to channel-first layout without copying pixel data. It tests axis reordering, how views and strides work, and what a non-contiguous array means for downstream code.
Write `hwc_to_chw(img)` that converts an image of shape `(H, W, C)` to channel-first shape `(C, H, W)`. The last axis moves to the front while the spatial axes keep their relative order.
```python
img = np.zeros((32, 48, 3)) # (H, W, C)
out = hwc_to_chw(img)
out.shape # (3, 32, 48)
```
```hint Look at the metadata
An axis reorder can be described entirely by the array's shape and strides. Check which NumPy functions return a view of the existing buffer.
```
### Constraints & Assumptions
- Use `np.moveaxis` or an equivalent `transpose`. The result must be a view, with no element-wise copying.
- No Python loops over pixels or channels.
- The input is a valid 3D array, so validation is out of scope.
### What a Strong Answer Covers
- The correct axis move: the last axis goes to position 0 and height and width stay in order
- Why the result is a view and costs the same regardless of image size
- How `np.moveaxis` relates to the equivalent `transpose` permutation
- What a non-contiguous result means for code that needs contiguous memory
### Follow-up Questions
- What's the difference between `np.moveaxis` and `img.transpose(2, 0, 1)` here?
- The result is a view but not C-contiguous. Why might that matter downstream?
- How would you change the function so it also handles a batch of shape `(N, H, W, C)`?
Overview: Write a NumPy function that converts an image array from height, width, channel layout to channel-first layout without copying pixel data. It tests axis reordering, how views and strides work, and what a non-contiguous array means for downstream code.
Write hwc_to_chw(img) that converts an image of shape (H, W, C) to channel-first shape (C, H, W). The last axis moves to the front while the spatial axes keep their relative order.
img = np.zeros((32, 48, 3)) # (H, W, C)
out = hwc_to_chw(img)
out.shape # (3, 32, 48)
Constraints & Assumptions
Use
np.moveaxis
or an equivalent
transpose
. The result must be a view, with no element-wise copying.
No Python loops over pixels or channels.
The input is a valid 3D array, so validation is out of scope.
What a Strong Answer Covers Guidance
The correct axis move: the last axis goes to position 0 and height and width stay in order
Why the result is a view and costs the same regardless of image size
How
np.moveaxis
relates to the equivalent
transpose
permutation
What a non-contiguous result means for code that needs contiguous memory
Follow-up Questions Guidance
What's the difference between
np.moveaxis
and
img.transpose(2, 0, 1)
here?
The result is a view but not C-contiguous. Why might that matter downstream?
How would you change the function so it also handles a batch of shape
(N, H, W, C)
?