Computer Vision in Practice · Lesson 2 of 15 · 2 min read · 5 min video
Image preprocessing with OpenCV
Resize, crop, convert colours and clean up images before a model sees them.
📄 Download slides (PDF)Models are picky. They expect images of a fixed size, with a certain colour order and value range. Preprocessing gets raw photos into that shape, and OpenCV is the standard toolkit for it.
The basics
import cv2
img = cv2.imread("auto.jpg") # careful: OpenCV loads BGR, not RGB
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # convert to RGB for most models
img = cv2.resize(img, (224, 224)) # the size the model expects
img = img.astype("float32") / 255.0 # scale pixels to 0–1Common steps
- Resize: models take a fixed size, such as 224 × 224 or 640 × 640
- Keep the aspect ratio: resize the longer side and pad the rest (letterboxing), so objects don't get squashed
- Crop: cut out the region you care about
- Colour conversion: BGR → RGB, or to grayscale when colour doesn't matter
- Normalise: scale pixel values, and often subtract the mean and divide by the standard deviation the model was trained with
Classic image processing
Before deep learning, vision used hand-built operations, and they're still useful for quick tasks:
- Blur to remove noise:
cv2.GaussianBlur - Thresholding to separate dark text from a light background
- Edge detection to find outlines:
cv2.Canny - Contours to find and measure shapes
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
edges = cv2.Canny(gray, 100, 200) # white lines where brightness changes sharplySame steps in training and serving
Use exactly the same preprocessing in training and in production. A model trained on RGB images and served BGR images will quietly perform worse, with no error.
In one line
Preprocessing resizes, converts and normalises images into exactly what the model expects, and OpenCV does it, as long as training and serving use the same steps.
Share with a friend