#138Image preprocessing — scale and standardizeMediumComputer VisionML System DesignNormalization
Image preprocessing — scale and standardize
Background
Before an image enters a network it's almost always normalized: scale the raw pixels to , then standardize each channel with a per-channel mean and std (the ImageNet recipe):
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 .mean— array-like of lengthC, per-channel means (in scale).std— array-like of lengthC, 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: ; 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: .
Constraints
- Divide by 255 first, then subtract
meanand divide bystd, per channel (broadcast overH, W). - Return shape
(H, W, C).
Notes
meanandstdbroadcast across the spatial dimensions because they have lengthCmatching 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