#138Image preprocessing — scale and standardizeMedium

Image preprocessing — scale and standardize

Background

Before an image enters a network it's almost always normalized: scale the raw [0,255][0, 255] pixels to [0,1][0, 1], then standardize each channel with a per-channel mean and std (the ImageNet recipe):

out,,c=img,,c255μcσc\text{out}_{\cdot,\cdot,c} = \frac{\dfrac{\text{img}_{\cdot,\cdot,c}}{255} - \mu_c}{\sigma_c}

This centers and rescales the inputs so optimization behaves well.

Problem statement

Implement normalize_image(img, mean, std) that scales by 255 then standardizes per channel.

Input

  • img — array-like of shape (H, W, C), raw pixel values in [0,255][0, 255].
  • mean — array-like of length C, per-channel means (in [0,1][0,1] scale).
  • std — array-like of length C, per-channel std deviations.

Output

Returns an np.ndarray of shape (H, W, C): the normalized image.

Examples

Example 1

Input:  img = full 2×2×3 of 255, mean = [0.5, 0.5, 0.5], std = [0.5, 0.5, 0.5]
Output: all 1.0

Explanation: 255/255=1255/255 = 1; (10.5)/0.5=1(1 - 0.5)/0.5 = 1 for every channel.

Example 2 — black pixels

Input:  img = full 2×2×3 of 0, mean = [0.5, 0.5, 0.5], std = [0.5, 0.5, 0.5]
Output: all -1.0

Explanation: (00.5)/0.5=1(0 - 0.5)/0.5 = -1.

Constraints

  • Divide by 255 first, then subtract mean and divide by std, per channel (broadcast over H, W).
  • Return shape (H, W, C).

Notes

  • mean and std broadcast across the spatial dimensions because they have length C matching the last axis.
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 all-white with 0.5/0.5 -> 1.0
  • Reference all-black with 0.5/0.5 -> -1.0
  • Sample per-channel broadcasting