Sub topic 8
Preprocessing and Postprocessing That Match Training
This chapter assumes you know basic Python, tensors, image preprocessing, and either PyTorch or TensorFlow. The goal is to keep the data transformation used on the device identical to the transformation used during training.
Why matching matters
A model does not receive “an image.” It receives a tensor with a specific shape, color order, value range, data type, and layout. During training, the model learns from those exact properties. A different mobile pipeline can reduce accuracy even when the model file is correct.
Common differences include:
- RGB versus BGR color order.
- Pixel values from 0 to 255 versus values from 0 to 1.
- Different mean and standard-deviation normalization.
- Width-height swaps.
- Center cropping during training but stretching during inference.
- NCHW layout, meaning batch, channels, height, width, versus NHWC, meaning batch, height, width, channels.
- A float32 input expected by the model but a uint8 tensor supplied by the app.
Write the training transformation as a specification. Record every resize, crop, color conversion, normalization step, tensor layout, and output interpretation.
Build the input tensor
For an image classifier trained with ImageNet-style preprocessing, a typical pipeline is:
- Decode the image.
- Convert it to RGB.
- Resize and crop it to the training size.
- Convert pixels to float32.
- Divide by 255 if training used values from 0 to 1.
- Subtract the training mean and divide by the training standard deviation.
- Add a batch dimension and arrange the axes as the model expects.
For a quantized model, the final conversion must also use the model’s quantization parameters. If the scale is s and the zero point is z, convert a real value x to an integer with round(x / s + z), then clamp it to the valid integer range.
from PIL import Image
import numpy as np
MEAN = np.array([0.485, 0.456, 0.406], dtype=np.float32)
STD = np.array([0.229, 0.224, 0.225], dtype=np.float32)
def prepare_input(path, size=(224, 224), scale=None, zero_point=None):
image = Image.open(path).convert("RGB")
image = image.resize(size)
pixels = np.asarray(image, dtype=np.float32) / 255.0
pixels = (pixels - MEAN) / STD
# Convert NHWC to NCHW if the model expects channels first.
tensor = np.transpose(pixels, (2, 0, 1))[None, ...]
if scale is not None and zero_point is not None:
tensor = np.round(tensor / scale + zero_point)
tensor = np.clip(tensor, 0, 255).astype(np.uint8)
else:
tensor = tensor.astype(np.float32)
return tensorThe example assumes the model was trained with the shown mean and standard deviation. Replace them with the values used by your training code. For an int8 model, clamp to -128 through 127 instead of 0 through 255.
Decode the output
Postprocessing also has a contract. A classifier may return logits, which are unnormalized class scores. Apply softmax only if you need probabilities. For detection, convert box coordinates back to the original image size, remove low-confidence boxes, and apply non-maximum suppression when overlapping boxes represent the same object.
Keep coordinate conventions explicit:
| Item | Example |
|---|---|
| Box format | `x_min, y_min, x_max, y_max` |
| Coordinate range | Pixels or normalized values from 0 to 1 |
| Score threshold | 0.5 |
| Class indexing | Zero-based class IDs |
If preprocessing letterboxed the image, undo the padding before drawing boxes. Otherwise, detections will appear shifted or stretched.
Exercise
A model was trained with RGB images normalized by ImageNet mean and standard deviation, but the phone sends BGR pixels in the range 0–255. What should you change?
Show answer
Convert BGR to RGB, divide by 255, and apply the same mean and standard-deviation normalization used during training.