OpenCV Cheat Sheet
OpenCV computer vision reference covering image I/O, filtering, edge detection, contours, drawing, and video capture in Python.
Read, Write & Display
Load, convert, and save images.
import cv2img = cv2.imread("photo.jpg") # loaded in BGR order, not RGBgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)resized = cv2.resize(img, (640, 480))cv2.imwrite("output.jpg", resized)cv2.imshow("Window", img)cv2.waitKey(0)cv2.destroyAllWindows()
Filtering & Thresholding
Common preprocessing operations.
blurred = cv2.GaussianBlur(img, (5, 5), sigmaX=0)edges = cv2.Canny(gray, threshold1=100, threshold2=200)_, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))dilated = cv2.dilate(thresh, kernel, iterations=1)
Contours & Drawing
Detect shapes and annotate images.
contours, hierarchy = cv2.findContours( thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)cv2.drawContours(img, contours, -1, (0, 255, 0), 2)cv2.rectangle(img, (10, 10), (100, 100), (255, 0, 0), 2)cv2.circle(img, (50, 50), 20, (0, 0, 255), -1)cv2.putText(img, "Label", (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
Core Functions
Building blocks used across most CV pipelines.
- cv2.imread / imwrite- load/save images (BGR channel order)
- cv2.cvtColor- convert color spaces (BGR2GRAY, BGR2RGB, BGR2HSV)
- cv2.GaussianBlur / medianBlur- noise reduction filters
- cv2.Canny- edge detection
- cv2.findContours- detect object outlines in a binary image
- cv2.VideoCapture- read frames from a camera or video file
- cv2.CascadeClassifier- Haar cascade face/object detection
Keypoint Detection & Matching
Detect ORB features and match them between two images for stitching or alignment.
orb = cv2.ORB_create(nfeatures=1000)kp1, des1 = orb.detectAndCompute(img1_gray, None)kp2, des2 = orb.detectAndCompute(img2_gray, None)bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)matches = sorted(bf.match(des1, des2), key=lambda m: m.distance)matched_img = cv2.drawMatches(img1, kp1, img2, kp2, matches[:30], None, flags=cv2.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)
Homography & Perspective Warp
Compute a homography from matched points and warp one image into another's plane.
src_pts = np.float32([kp1[m.queryIdx].pt for m in matches[:20]]).reshape(-1, 1, 2)dst_pts = np.float32([kp2[m.trainIdx].pt for m in matches[:20]]).reshape(-1, 1, 2)H, mask = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, ransacReprojThreshold=5.0)h, w = img1.shape[:2]warped = cv2.warpPerspective(img1, H, (w, h))# 4-point crop/deskew, e.g. document scanningM = cv2.getPerspectiveTransform(src_quad, dst_quad)deskewed = cv2.warpPerspective(img, M, (target_w, target_h))
DNN Module Inference
Run an ONNX/Caffe object detector through OpenCV's built-in inference engine, no separate framework needed.
net = cv2.dnn.readNetFromONNX("yolov8n.onnx")net.setPreferableBackend(cv2.dnn.DNN_BACKEND_OPENCV)net.setPreferableTarget(cv2.dnn.DNN_TARGET_CPU)blob = cv2.dnn.blobFromImage(img, scalefactor=1/255.0, size=(640, 640), mean=(0, 0, 0), swapRB=True, crop=False)net.setInput(blob)outputs = net.forward()indices = cv2.dnn.NMSBoxes(boxes, scores, score_threshold=0.5, nms_threshold=0.4)
Optical Flow & Object Tracking
Estimate motion between video frames and track objects with a built-in tracker.
flow = cv2.calcOpticalFlowFarneback( prev_gray, next_gray, None, pyr_scale=0.5, levels=3, winsize=15, iterations=3, poly_n=5, poly_sigma=1.2, flags=0,)mag, ang = cv2.cartToPolar(flow[..., 0], flow[..., 1])tracker = cv2.TrackerCSRT_create()tracker.init(frame, bbox) # bbox = (x, y, w, h)ok, bbox = tracker.update(next_frame)
Advanced Modules
Specialized submodules beyond core image processing.
- cv2.dnn- run ONNX/TensorFlow/Caffe models for detection, segmentation, classification
- cv2.ml- classic ML: SVM, k-NN, decision trees, EM, operating on OpenCV Mat data
- cv2.calib3d- camera calibration, stereo vision, solvePnP for pose estimation
- cv2.aruco- ArUco/AprilTag marker detection for robotics and AR
- cv2.bgsegm / createBackgroundSubtractorMOG2- background subtraction for motion detection in video
- cv2.KalmanFilter- predict/correct object trajectories under noisy measurements
- cv2.Stitcher_create- automatic multi-image panorama stitching pipeline
OpenCV loads and stores images in BGR channel order, not RGB — convert with cv2.cvtColor(img, cv2.COLOR_BGR2RGB) before displaying with matplotlib or passing images to most deep-learning frameworks.