Sub topic 8
Preprocessing and Postprocessing That Match Training
This chapter assumes you can read Python and NumPy, know what a convolutional classifier or detector outputs, and have already exported a model to TensorFlow Lite or ONNX. You should also know the difference between float32 and int8 tensors.
A model is a function trained on inputs prepared in one exact way. If the app prepares the pixels differently, the model still runs and still returns numbers, but those numbers are worse. Nothing crashes. This is why preprocessing mismatches are among the most common causes of "the model works in Python but not on the phone."
Why Preprocessing Is Part of the Model
During training, an input pipeline turns a file into a tensor. That pipeline makes decisions the weights depend on:
- Image decoding and color order (RGB or BGR).
- Resize method and target size.
- Crop or pad strategy.
- Value scaling and normalization.
- Memory layout (NCHW or NHWC) and data type.
Exporting the network does not export these decisions. Most converters capture only the graph from the input tensor onward. You must reproduce the rest on the device, and you should treat it as a written contract that ships with the model.
Postprocessing is the matching work on the output side: turning raw tensors into labels, boxes, or masks.
The Preprocessing Contract
Record these items for every model. Put them in a small JSON file next to the model, or in the model's metadata.
| Item | Typical values | Failure if wrong |
|---|---|---|
| Color order | RGB (most PyTorch, Keras) or BGR (some OpenCV-trained models) | Colors swapped, accuracy drops quietly |
| Input size | 224x224, 320x320, 640x640 | Shape error, or silent stretching if you resize wrongly |
| Resize method | Bilinear, bicubic, area, nearest | Small but real accuracy loss |
| Aspect ratio | Stretch, center crop, or letterbox | Objects distorted or cut off |
| Scaling | 0 to 1, -1 to 1, or 0 to 255 | Saturated or tiny activations |
| Mean and std | ImageNet: mean (0.485, 0.456, 0.406), std (0.229, 0.224, 0.225) | Shifted input distribution |
| Layout | NCHW (PyTorch) or NHWC (TensorFlow Lite) | Garbage output or shape error |
| Dtype | float32, uint8, int8 | Wrong magnitudes |
Where Preprocessing Lives in the Pipeline
Each stage before the model must produce what training produced. Each stage after the model must interpret the output the way the loss function defined it.
Walking Through a Classifier
Suppose you trained a PyTorch classifier with this transform:
from torchvision import transforms
train_eval_transform = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(), # HWC uint8 -> CHW float32 in [0, 1]
transforms.Normalize(
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225],
),
])The steps are: resize the short side to 256, crop the center 224x224, scale to 0..1, and normalize each channel. A NumPy version for a device-side or test harness looks like this:
import numpy as np
from PIL import Image
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 preprocess(path, size=224, resize_short=256):
img = Image.open(path).convert("RGB")
w, h = img.size
scale = resize_short / min(w, h)
img = img.resize((round(w * scale), round(h * scale)), Image.BILINEAR)
w, h = img.size
left = (w - size) // 2
top = (h - size) // 2
img = img.crop((left, top, left + size, top + size))
arr = np.asarray(img, dtype=np.float32) / 255.0 # HWC, 0..1
arr = (arr - MEAN) / STD # per-channel
return arr[np.newaxis, ...] # NHWC, batch of 1This returns NHWC. A PyTorch-exported ONNX model expects NCHW, so add arr.transpose(0, 3, 1, 2) for that case. A TensorFlow Lite model converted from Keras typically expects NHWC. Read the shape from the model rather than assuming.
Resize Details That Cause Real Errors
Resizing is the most underestimated step. Different libraries implement "bilinear" differently.
- Pillow, OpenCV, TensorFlow, and Android's
Bitmap.createScaledBitmapcan give different pixel values for the same input. - When shrinking a large image, some bilinear implementations ignore most source pixels and alias. Pillow's resize applies a filter that accounts for the scale factor. A naive GPU or
Bitmapbilinear resize may not. - Center crop versus stretch matters. If you trained with a center crop and the app stretches a 4:3 frame to a square, objects look wider than the model has seen.
- Letterboxing (padding to keep the aspect ratio) is common for detectors. The pad color and the offset must be remembered, because you need them to map boxes back to the original frame.
The practical rule is to pick one resize implementation on the device, compare its output to the training-time output on a handful of images, and measure the accuracy difference. If the difference is visible, retrain with the device's resize, or switch the device's resize.
Quantized Input and Output
A fully integer-quantized TensorFlow Lite model, like the one in the quantization chapter, often has a uint8 or int8 input. The model stores a scale and zero point for the input tensor. The mapping is:
real = scale * (quantized - zero_point)
quantized = round(real / scale) + zero_pointYou have two cases:
- The model keeps float32 input and quantizes internally. Feed normalized floats as in training.
- The model has an integer input. Compute the normalized float values first, then quantize them using the input tensor's scale and zero point.
Some models were calibrated so that the quantization parameters already absorb the normalization. For example, a uint8 input in 0..255 with scale 1/255 and zero point 0 represents values in 0..1. Always read the parameters rather than guessing.
import numpy as np
import tensorflow as tf
interpreter = tf.lite.Interpreter(model_path="mobilenet_v2_int8.tflite")
interpreter.allocate_tensors()
inp = interpreter.get_input_details()[0]
out = interpreter.get_output_details()[0]
in_scale, in_zero = inp["quantization"]
out_scale, out_zero = out["quantization"]
def quantize_input(float_batch):
if inp["dtype"] == np.float32:
return float_batch.astype(np.float32)
q = np.round(float_batch / in_scale + in_zero)
info = np.iinfo(inp["dtype"])
return np.clip(q, info.min, info.max).astype(inp["dtype"])
def dequantize_output(raw):
if out["dtype"] == np.float32:
return raw
return (raw.astype(np.float32) - out_zero) * out_scale
float_input = np.random.rand(*inp["shape"]).astype(np.float32)
interpreter.set_tensor(inp["index"], quantize_input(float_input))
interpreter.invoke()
scores = dequantize_output(interpreter.get_tensor(out["index"]))
print("top class:", int(scores.argmax()))The clip before the cast prevents integer wraparound. Without it, a value of 256 stored in uint8 becomes 0.
Camera Frames Add Their Own Problems
Training data is usually upright RGB images. Camera output is not.
- Rotation. Android camera frames often arrive rotated 90 degrees relative to the display. iOS frames carry an orientation flag. Rotate to upright before the model, or the model sees sideways faces.
- Pixel format. Android's
ImageAnalysisand Camera2 often give YUV420888. iOS gives BGRA or YUV pixel buffers. Convert to RGB explicitly. Mixing up BGRA and RGBA swaps the red and blue channels. - Row stride. Image planes can have padding at the end of each row. Reading width times height bytes without honoring the row stride produces a slanted, corrupted image.
- Mirroring. Front cameras are mirrored in the preview. Decide whether the model should see the mirrored or the true image. Training data was probably not mirrored.
- Premultiplied alpha. PNGs with transparency can darken colors if alpha is applied unexpectedly.
Postprocessing for Classification
For a classifier, the output is usually logits or softmax probabilities. Check which one your export produces.
- Applying softmax to values that are already probabilities flattens them.
- Taking the argmax needs no softmax, since softmax preserves order.
- Confidence thresholds need real probabilities, so apply softmax to logits first.
import numpy as np
def softmax(x):
x = x - np.max(x, axis=-1, keepdims=True) # numerical stability
e = np.exp(x)
return e / e.sum(axis=-1, keepdims=True)
def top_k(logits, labels, k=5):
probs = softmax(logits.reshape(-1))
idx = np.argsort(probs)[::-1][:k]
return [(labels[i], float(probs[i])) for i in idx]Keep the label file versioned with the model. A reordered label list produces confident wrong names. Some Keras ImageNet models also have 1000 outputs, while others have 1001 with a background class at index 0, which shifts every label by one.
Postprocessing for Detection
Detectors need more work, and the details depend on the architecture.
- Decode. Anchor-based models output offsets relative to anchor boxes. You apply the anchors and the model's scale factors to get box coordinates. Anchor-free models may output boxes directly.
- Score. Convert class logits to scores, using sigmoid for multi-label heads or softmax for single-label heads.
- Threshold. Drop boxes below a confidence cutoff.
- Non-maximum suppression (NMS). Remove overlapping boxes of the same class, keeping the highest-scoring one.
- Map back. Undo the resize or letterbox so the boxes line up with the original frame.
A simple NMS in NumPy:
import numpy as np
def iou(box, boxes):
x1 = np.maximum(box[0], boxes[:, 0])
y1 = np.maximum(box[1], boxes[:, 1])
x2 = np.minimum(box[2], boxes[:, 2])
y2 = np.minimum(box[3], boxes[:, 3])
inter = np.clip(x2 - x1, 0, None) * np.clip(y2 - y1, 0, None)
area_a = (box[2] - box[0]) * (box[3] - box[1])
area_b = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1])
return inter / (area_a + area_b - inter + 1e-9)
def nms(boxes, scores, iou_thresh=0.5):
order = np.argsort(scores)[::-1]
keep = []
while order.size > 0:
i = order[0]
keep.append(int(i))
if order.size == 1:
break
rest = order[1:]
order = rest[iou(boxes[i], boxes[rest]) < iou_thresh]
return keepBoxes are [x1, y1, x2, y2]. Check whether your model outputs corners or [cx, cy, w, h], and whether coordinates are normalized to 0..1 or in pixels of the input size.
Mapping a letterboxed box back to the original frame:
def unletterbox(box, scale, pad_x, pad_y, orig_w, orig_h):
x1 = (box[0] - pad_x) / scale
y1 = (box[1] - pad_y) / scale
x2 = (box[2] - pad_x) / scale
y2 = (box[3] - pad_y) / scale
return [
max(0.0, min(x1, orig_w)),
max(0.0, min(y1, orig_h)),
max(0.0, min(x2, orig_w)),
max(0.0, min(y2, orig_h)),
]Some exported detectors include NMS inside the graph. That is convenient, but NMS is a frequent source of unsupported operators or CPU fallback on accelerators. If NMS causes trouble, export without it and run NMS in app code, which the troubleshooting chapter covers.
Postprocessing Cost
Postprocessing is not free. A detector with 8,400 candidate boxes per frame, processed in a slow loop on the main thread, can cost more than the network on a fast accelerator. Keep the following in mind:
- Filter by score before NMS so the loop touches fewer boxes.
- Use native or vectorized code on the device, not per-box object allocation.
- Reuse buffers between frames to avoid garbage collection pauses.
- Run pre- and postprocessing off the UI thread.
Include these stages in your benchmark, not only the invoke() call.
Moving Preprocessing Into the Model
You can sometimes bake normalization and resize into the exported graph. This reduces the chance of a mismatch.
import torch
import torch.nn as nn
class WithNormalization(nn.Module):
def __init__(self, model):
super().__init__()
self.model = model
self.register_buffer(
"mean", torch.tensor([0.485, 0.456, 0.406]).view(1, 3, 1, 1)
)
self.register_buffer(
"std", torch.tensor([0.229, 0.224, 0.225]).view(1, 3, 1, 1)
)
def forward(self, x):
# x: NCHW float32 in [0, 1]
return self.model((x - self.mean) / self.std)The app then only needs to resize, convert to RGB, and scale to 0..1. The trade-off is that fused operations are fine for simple arithmetic but risky for resize ops, which differ across runtimes and delegates. Keep the contract file even when you fuse steps, so you know what the app is still responsible for.
Verifying That Device Preprocessing Matches Training
Use a golden test.
- Pick 20 to 50 representative images, including hard cases such as dark, tilted, or cluttered ones.
- Run the reference pipeline (training framework, original float model) and save the outputs.
- Run the device pipeline (app code, converted model) on the same files and save the outputs.
- Compare the top-1 agreement, the maximum absolute difference in scores, and for detectors the box IoU between the two.
A float model with the correct preprocessing should track the reference closely. A quantized model will differ more. Separating the two causes matters: first test the device preprocessing with the float converted model, then add quantization. If you test only the final quantized model, you cannot tell whether a drop comes from preprocessing or from quantization.
Common Failures
| Symptom | Likely cause | Check |
|---|---|---|
| All outputs near uniform | Wrong scaling, such as 0..255 fed to a model that expects 0..1 | Print min and max of the input tensor |
| Wrong class but plausible scores | Color order swapped | Compare channel order with the reference |
| Works on stills, fails on live camera | Rotation, stride, or mirroring | Dump the preprocessed frame |
| Boxes shifted or stretched | Letterbox offsets not undone | Draw boxes on the model input, then on the original |
| Labels off by one | 1001-class model with a 1000-line label file | Check output size against label count |
| Quantized model returns constant output | Float values fed to an integer input without quantizing | Print dtype and the quantization parameters |
| Accuracy drops only on device | Different resize implementation | Compare resized pixels with the reference |
Exercise
A quantized TensorFlow Lite classifier reports an input dtype of uint8 with quantization parameters (scale 0.0078125, zero point 128). Your float preprocessing produces values in the range -1 to 1. What uint8 value represents a float input of 0.5, and what happens if you skip the clip step for an input of 1.2?
Show answer
Quantized value = round(0.5 / 0.0078125) + 128 = 64 + 128 = 192. For 1.2, round(1.2 / 0.0078125) + 128 = 154 + 128 = 282, which is above 255. Without clipping, casting to uint8 wraps around to 26 (282 minus 256), so a bright input becomes a dark one. Clipping to 255 keeps the value saturated at the maximum.
Exercise
Your detector gives correct boxes on test images but the boxes are consistently shifted right and down on live camera frames, which you letterbox to 320x320. Name two likely causes and how you would confirm each.
Show answer
First, the pad offsets and scale were not subtracted and divided when mapping boxes back to the original frame. Confirm by drawing the raw model boxes on the letterboxed input: if they fit there but not on the original frame, the mapping is wrong. Second, the camera frame is rotated or has a different aspect ratio than the one used to compute the letterbox scale. Confirm by saving the preprocessed input and checking its orientation and padding against the same frame processed in Python.
Exercise
Why should you validate device preprocessing with the float converted model before testing the quantized model?
Show answer
Both preprocessing errors and quantization error lower accuracy. If you test only the quantized model, a drop could come from either cause. The float converted model should match the reference closely, so any large difference points to preprocessing or conversion. Once that matches, a further drop after quantization can be attributed to quantization.