Mental model
Computer vision maps pixel arrays into task-specific representations, then turns those representations into class scores, boxes, masks, or embeddings. Reliability depends on color order, resize policy, coordinate frame, label mapping, and thresholds agreeing from data loading through evaluation. CNNs encode local spatial structure with shared filters; Vision Transformers tokenize patches and learn global relationships.
Theory
An image decoder produces a height-by-width grid with channels, commonly RGB. Pixel values still carry a contract: channel order, integer range, color profile, orientation, and alpha handling. A training pipeline may convert bytes to floating point, resize or crop, then normalize each channel using the training distribution. Reusing those exact transforms at inference is part of the model, not a cosmetic preprocessing choice.
A convolution applies a learned kernel over local neighborhoods and shares its weights across locations. Stacked layers build larger receptive fields while strided convolutions or pooling reduce spatial resolution. In a residual block, a learned transformation is added to an identity or projected shortcut; this gives optimization a direct path through depth when input and output shapes are compatible. A Vision Transformer instead partitions an image into fixed-size patches, projects each flattened patch into an embedding, adds position information, and lets attention mix information across tokens. Neither family is automatically superior: local bias can help with limited image data, while patch attention makes global interactions explicit but can grow expensive as resolution rises.
Match the head and labels to the task
Classification produces scores for an image or crop. Object detection predicts class scores and boxes in a defined coordinate system, then often applies confidence filtering and non-maximum suppression. Semantic segmentation predicts a class per pixel; instance segmentation additionally separates individual objects. The head changes the target, loss, metrics, and post-processing. A detector trained on boxes cannot be evaluated as though its outputs were pixel masks.
Keep geometry synchronized. If a 1280-by-720 frame is resized to 640-by-640 by direct stretching, horizontal and vertical scales differ. Letterboxing preserves aspect ratio but introduces padding that must be removed when mapping predicted boxes back to the original frame. For masks, resize logits with the intended interpolation mode before thresholding; nearest-neighbor resizing is usually appropriate for discrete label maps, while bilinear interpolation is useful for continuous logits. Training annotations must receive the same spatial transform as their image.
Trade-offs
Consider a Vision Transformer using 16-by-16 patches. A 224-by-224 input creates 196 image tokens plus a class token. At 384-by-384 it creates 576 image tokens plus a class token. The sequence is about 2.93 times longer, while the pairwise attention matrices are about 8.58 times larger. For embedding width 768, the two attention products alone require approximately 59.6 million versus 511 million multiply-adds per block, before projections and feed-forward layers. Raising resolution may recover small-object detail, but it can violate a latency budget or reduce batch size. Measure task quality and end-to-end latency on the target device rather than inferring performance from model names.
Here and are input height and width in pixels, is patch width in pixels, the added token is the class token, and is embedding width. and are counts; estimates multiply-add operations for the query-key and attention-value products in one layer, excluding linear projections.
Evaluation and deployment
A single top-1 accuracy number can conceal the errors that matter. A medical screening model may need sensitivity at a fixed false-positive rate; an inspection model may need recall on rare defects; a detector may use average precision across intersection-over-union thresholds. Report per-class results, confidence calibration, and slices for lighting, camera, geography, and object size. The validation split should reflect deployment conditions and keep correlated frames or near-duplicate images in the same partition to avoid leakage.
Thresholds are operating choices. A score of 0.8 is not automatically an 80 percent probability of correctness, and a global threshold can hide poor calibration for a rare class. For detection, overlapping boxes may describe one object, but non-maximum suppression can erase two adjacent instances when the IoU threshold is too aggressive. A resize change, label-map update, quantization pass, or new camera can shift the score distribution even when the checkpoint has not changed. Version the preprocessing configuration with the weights and rerun slice metrics after any change.
The following inference path pins torchvision's named ImageNet V2 weights and uses their packaged transform. That keeps resize, crop, and normalization consistent with the checkpoint’s expected input and avoids a moving DEFAULT alias. Softmax ranks classes here; it does not by itself calibrate confidence for a production threshold.
pythonimport torchfrom PIL import Imagefrom torchvision.models import ResNet50_Weights, resnet50weights = ResNet50_Weights.IMAGENET1K_V2model = resnet50(weights=weights).eval()preprocess = weights.transforms()labels = weights.meta["categories"]image = Image.open("inspection-frame.jpg").convert("RGB")batch = preprocess(image).unsqueeze(0)with torch.inference_mode():logits = model(batch)probabilities = logits.softmax(dim=1)[0]scores, indices = probabilities.topk(5)for score, index in zip(scores.tolist(), indices.tolist()):print(f"{labels[index]}: {score:.3f}")
Failure modes and misconceptions
A common failure is training with center crops but serving full frames whose important objects sit at the edges. Another is evaluating random neighboring video frames in both train and test sets, which inflates apparent generalization. In detection, padding can be mistaken for valid image content if coordinates are not unletterboxed. Class imbalance can make aggregate accuracy look healthy while a rare but safety-critical category is missed. Test these cases explicitly with recorded examples and label the condition, expected geometry, model revision, and post-processing configuration.
Higher resolution preserves detail but increases memory and inference work. A larger backbone may improve aggregate accuracy while making latency tails worse. Tiling large images can recover tiny objects, but adds overlap, duplicate detections, and merge logic. Quantization reduces storage and may improve throughput, yet can shift confidence near a decision threshold. Choose the smallest pipeline that meets per-class quality and latency requirements on representative production hardware, and retain a rollback path when a new preprocessing version changes output distributions.
Decision scenario
A warehouse inspection team has an 80 ms p95 inference budget and a new camera that misses small defects near the image edge. Direct stretching improves recall but produces distorted boxes; letterboxing preserves shape but leaves less image area, while tiling may exceed the budget. Compare all three on camera-separated clips, invert each resize or padding transform before scoring boxes, and report recall by defect size beside p95 latency. Ship the smallest change that meets both limits, with the old preprocessing revision available for rollback.
Learning outcomes
- Trace how image geometry and preprocessing affect the features and coordinate frame seen by a vision model.
- Compare residual convolutional features with patch-token attention and estimate the resolution cost.
- Select task-specific metrics and tests for classification, detection, or segmentation failures.