# Preprocessing Consistency — Computer Vision

Source: https://www.skillbyai.com/en/computer-vision/r-prep

> Small mismatches, big errors.

## Same pipeline in training and serving

Many production failures are preprocessing mismatches: **BGR instead of RGB** (OpenCV's default), wrong normalisation, different resize methods, wrong channel order, or images rotated by EXIF orientation in one pipeline but not another. The model receives inputs unlike its training data and quietly gets worse. Package preprocessing with the model, test the serving path with known images and expected outputs, and log input statistics in production.

## Feeding BGR to a model trained on RGB, run

I ran this on CPU with Python 3, OpenCV 5.0.0, scikit-image 0.26.0, PyTorch 2.14.1 and torchvision 0.29.1, using scikit-image's bundled sample photos and torchvision's published pretrained weights. The coffee photo in the correct RGB order is classified as espresso with 0.85 confidence. The same photo in BGR order, as returned by cv2.imread, becomes cup with only 0.20 confidence.

```python
import torch, cv2
from torchvision.models import resnet18, ResNet18_Weights
from skimage import data
weights = ResNet18_Weights.DEFAULT
model = resnet18(weights=weights).eval(); prep = weights.transforms(); cats = weights.meta["categories"]
rgb = data.coffee()
bgr = cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)      # what cv2.imread returns for a file
for name, img in [("RGB (correct)", rgb), ("BGR passed as RGB", bgr)]:
    with torch.no_grad():
        p = model(prep(torch.tensor(img).permute(2, 0, 1))[None]).softmax(1)[0]
    print(f"{name:<18} -> {cats[p.argmax()]} ({p.max().item():.2f})")
```

Output:

```
RGB (correct)      -> espresso (0.85)
BGR passed as RGB  -> cup (0.20)
```

## Add a golden-image test

Keep a few reference images with expected predictions and run them against every deployed version.

**Quiz:** What does cv2.imread return by default?

- [ ] Grayscale only
- [ ] Pixels in RGB order
- [ ] A PyTorch tensor
- [x] Pixels in BGR channel order

*Answer:* Pixels in BGR channel order. Convert to RGB if your model expects it.
