OpenCV cheat sheet
A scannable OpenCV reference: 6 short snippets across 3 topics, each linking back to the lesson it came from.
At a glance
| Topic | What it covers | |
|---|---|---|
| Reading, writing and inspecting images | An OpenCV image is a NumPy array - height first, then width, then channels. Reading returns None on failure instead of | lesson |
| Filters and edge detection | Edge detectors and thresholding amplify noise, so almost every classical pipeline starts with a blur. The kernel choice | lesson |
| Contours and object detection basics | Contours trace the boundary of connected bright regions after a binary threshold. They are ideal for counting | lesson |
Quick snippets
Reading, writing and inspecting images
Load and save
import cv2
img = cv2.imread("photo.jpg") # BGR order, dtype uint8
if img is None:
raise SystemExit("could not read photo.jpg - missing file, wrong path or unsupported format")
print(img.shape, img.dtype) # (1080, 1920, 3) uint8
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # shape (1080, 1920)
ok = cv2.imwrite("out/gray.png", gray) # returns True/False, never raises
print(ok)
Indexing, colour and resizing
# Slicing is (y, x) - rows first, then columns
crop = img[100:250, 300:500] # region of interest, a view not a copy
cv2.rectangle(img, (300, 100), (500, 250), (0, 255, 0), 2) # (x1, y1), (x2, y2)
cv2.putText(img, "plate", (300, 92), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 1)
small = cv2.resize(img, (640, 360), interpolation=cv2.INTER_AREA) # shrink
big = cv2.resize(small, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC) # enlargeFull lesson: Reading, writing and inspecting images →
Filters and edge detection
Smoothing before anything else
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
gauss = cv2.GaussianBlur(gray, (5, 5), sigmaX=1.4) # kernel size must be odd
median = cv2.medianBlur(gray, 5) # great against speckle
bilateral = cv2.bilateralFilter(gray, 9, 75, 75) # slow, but preserves edges
print(gauss.shape, bilateral.shape) # same spatial size as input
Gradients and Canny
# Magnitude of the gradient: an edge is a place where brightness changes fast
gx = cv2.Sobel(gray, cv2.CV_32F, 1, 0, ksize=3)
gy = cv2.Sobel(gray, cv2.CV_32F, 0, 1, ksize=3)
magnitude = cv2.magnitude(gx, gy) # float - uint8 would saturate at 255
# Canny keeps strong edges, then keeps weak ones only if linked to a strong one
edges = cv2.Canny(gauss, threshold1=80, threshold2=160)
print(edges.shape, edges.dtype, edges.max()) # single channel, uint8, 255 at an edgeFull lesson: Filters and edge detection →
Contours and object detection basics
Threshold, find, filter
_, mask = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5)))
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
kept = [c for c in contours if cv2.contourArea(c) > 500] # drop noise specks
for c in kept:
x, y, w, h = cv2.boundingRect(c)
area = cv2.contourArea(c)
circularity = 4 * 3.14159 * area / (cv2.arcLength(c, True) ** 2)
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
print(x, y, w, h, round(circularity, 2)) # near 1.0 means a circle
When a threshold is not enough
# A trained detector via cv2.dnn: same preprocessing contract as the training pipeline
net = cv2.dnn.readNetFromONNX("yolov8n.onnx")
blob = cv2.dnn.blobFromImage(frame, scalefactor=1 / 255.0, size=(640, 640),
mean=(0, 0, 0), swapRB=True, crop=False)
net.setInput(blob)
outputs = net.forward() # shape depends on the exported model - inspect it
for det in outputs[0].T: # [x, y, w, h, class scores...]
scores = det[4:]
class_id = int(scores.argmax())
if scores[class_id] > 0.4:
print(class_id, round(float(scores[class_id]), 3))Full lesson: Contours and object detection basics →
FAQ
Is this OpenCV cheat sheet free to use?
Yes. No sign-up and no tracking: the page is static, every example is on the page itself, and you can print it or save it as a one-page reference.
Where do the examples come from?
Every snippet is taken from the 3 lessons of the OpenCV course on this site, and each section links back to the lesson it was pulled from.
How do I go deeper than a cheat sheet?
Open the full OpenCV course — it carries the worked explanations, the edge cases and the exercises behind every line here.
Related cheat sheets
AI Basics AI Agents Math for AI Machine Learning scikit-learn TensorFlow
Last refreshed 2026-09-27.