Sub topic 5
Preprocessing and Postprocessing Around the Model
Assume you know basic Python and NumPy, have used PyTorch or a similar framework, and understand image-classification models. The ONNX model does not receive an image file. It receives a tensor with an exact shape, data type, layout, and value range. Preprocessing must create that tensor. Postprocessing must turn the model's raw output into a useful prediction.
The model's input contract
A common ResNet-50 export expects a four-dimensional tensor in NCHW layout:
- N is the batch size.
- C is the number of channels, usually 3 for red, green, and blue.
- H and W are the image height and width.
- The data type is usually float32.
The model may also expect ImageNet preprocessing. Each pixel is scaled from 0–255 to 0–1, then each channel is normalized with a fixed mean and standard deviation.
| Step | Example result |
|---|---|
| Decode and convert | RGB image |
| Resize and crop | 224 × 224 pixels |
| Scale | float32 values from 0 to 1 |
| Normalize and transpose | 1 × 3 × 224 × 224 tensor |
A mismatch in any step can produce plausible-looking but incorrect predictions. Use the same resize policy, channel order, normalization values, and crop behavior used during training and export.
A complete classification pipeline
from pathlib import Path
import numpy as np
import onnxruntime as ort
from PIL import Image, ImageOps
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(image_path: str, size: int = 224) -> np.ndarray:
image = Image.open(image_path).convert("RGB")
image = ImageOps.fit(image, (size, size), method=Image.Resampling.BILINEAR)
pixels = np.asarray(image, dtype=np.float32) / 255.0
pixels = (pixels - MEAN) / STD
tensor = np.transpose(pixels, (2, 0, 1))
return tensor[None, ...].astype(np.float32)
def postprocess(logits: np.ndarray) -> tuple[int, float]:
scores = logits[0]
scores = scores - np.max(scores)
probabilities = np.exp(scores) / np.exp(scores).sum()
class_id = int(np.argmax(probabilities))
return class_id, float(probabilities[class_id])
session = ort.InferenceSession(
"resnet50.onnx",
providers=["CPUExecutionProvider"],
)
input_name = session.get_inputs()[0].name
batch = preprocess("image.jpg")
logits = session.run(None, {input_name: batch})[0]
class_id, confidence = postprocess(logits)
print(f"class={class_id}, confidence={confidence:.3f}")The model usually returns logits, which are unnormalized class scores. Softmax converts them into values that sum to one. These values can be displayed as confidence scores, but they are not automatically calibrated probabilities.
Postprocessing for other vision tasks
Classification returns class scores. Detection models commonly return boxes, class scores, and class IDs. Postprocessing may filter low scores, convert box coordinates back to the original image size, and apply non-maximum suppression. Segmentation models return a mask for each pixel, which may need resizing to the original image dimensions.
Coordinate conversion is especially easy to get wrong. If preprocessing center-crops an image, record the crop offset and scale. Use those values to map detected boxes back to the source image.
Exercise
Why can a model produce wrong predictions even when its input tensor has the correct shape?
Show answer
The values may still use the wrong channel order, scale, normalization, resize policy, or crop. Shape alone does not define the model's input contract.