Convert an image batch from NHWC to NCHW
Why it matters Every vision pipeline feeding a PyTorch or ONNX model does this conversion.
Image libraries give you (batch, height, width, channels) but PyTorch convolutions want (batch, channels, height, width).
Write to_nchw(x, scale=True). Transpose axes to NCHW and, if scale is True, convert uint8 values to float in [0, 1] by dividing by 255.
def to_nchw(x, scale=True)Example
one 1x2 RGB image [[[[255, 0, 0], [0, 255, 0]]]] becomes shape (1, 3, 1, 2) with red channel [[1, 0]].
Understand the idea
Image loaders such as PIL and OpenCV give arrays shaped (batch, height, width, channels), while PyTorch convolutions expect (batch, channels, height, width). You fix this by reordering the axes, not by reshaping, because a reshape would scramble pixels. Raw pixels are usually uint8 from 0 to 255, and models want floats from 0 to 1. Worked example: a batch of shape (2, 32, 32, 3) becomes (2, 3, 32, 32). The value at [n, h, w, c] moves to [n, c, h, w]. A pixel value 51 becomes 51 / 255 = 0.2, and 255 becomes 1.0. Rule: transpose with axis order (0, 3, 1, 2), which puts channels second and keeps height before width; then, if scale is True, cast to float and divide by 255. Swapping height and width by mistake gives the right shape for square images but silently transposes every picture. Used in: every vision data pipeline that feeds PyTorch, ONNX or TensorRT models.