Skip to content
Tutorials Center
My learning

Topics

Lesson 54 of 54 ยท Practice and Review

OpenCV Cheat Sheet

A one-page OpenCV Python cheat sheet: functions grouped by task, argument order, shape and dtype reminders, and flag tables, with small runnable numpy checks.

You have now met most of OpenCV. This page is the quick-reference version: functions grouped by task with their argument order, the shape and dtype rules that cause most bugs, and flag tables. Use it when you remember that a function exists but not how its arguments are arranged. Each group links back to the lesson that explains the details.

The function calls are shown in read-only blocks because cv2 cannot run on this site. Two live examples at the end use numpy to confirm the shape and dtype rules, which are properties of numpy arrays and behave identically in real OpenCV code. Everything here assumes OpenCV 4.x with import cv2 and import numpy as np.

Five rules that prevent most bugs

BGR order Not RGB, unless you convert.
(h, w, c) Shape is rows first.
(x, y) Points and sizes are columns first.
uint8 0 to 255, saturating in cv2.

Hue is 0 to 179 in 8-bit OpenCV, not 0 to 359.

1 / 2

Shapes, types and indexing

Fact Detail
Color image (height, width, 3), uint8, channels B, G, R
Gray image (height, width), uint8
Index a pixel img[y, x] (row, column)
Point or size argument (x, y) and (width, height)
Region of interest img[y1:y2, x1:x2] is a view, not a copy
Safe copy img.copy()
Hue / saturation / value 0 to 179 / 0 to 255 / 0 to 255 for uint8
Float images usually 0.0 to 1.0 or 0.0 to 255.0, you choose

See Images Are NumPy Arrays, Accessing and Modifying Pixels and Data Types, Ranges and Saturation.

Input and output

Python
img  = cv2.imread("a.png")                       # BGR, or None on failure
gray = cv2.imread("a.png", cv2.IMREAD_GRAYSCALE)
cv2.imwrite("out.png", img)                      # returns True or False
cv2.imshow("title", img); cv2.waitKey(0); cv2.destroyAllWindows()   # needs a GUI build
Flag Meaning
IMREAD_COLOR 3 channels, drops alpha (default)
IMREAD_GRAYSCALE one channel
IMREAD_UNCHANGED keep alpha and original depth

Video: cap = cv2.VideoCapture(path_or_index), then ok, frame = cap.read() until ok is false, and finish with cap.release(). To write: cv2.VideoWriter(filename, fourcc, fps, (width, height)), where the size is (w, h) and must match the frames. See Reading, Showing and Saving Images and Reading and Writing Video.

Color and arithmetic

Python
cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)       # also COLOR_BGR2RGB, COLOR_BGR2HSV, COLOR_HSV2BGR
cv2.split(img)                              # b, g, r
cv2.merge([b, g, r])
cv2.add(a, b)                               # saturating; a + b in numpy wraps
cv2.subtract(a, b)
cv2.addWeighted(a, alpha, b, beta, gamma)   # alpha*a + beta*b + gamma
cv2.convertScaleAbs(a, alpha=1.0, beta=0)   # |alpha*a + beta|, saturated to uint8
cv2.normalize(a, None, 0, 255, cv2.NORM_MINMAX)
cv2.inRange(hsv, lower, upper)              # 255 where every channel is inside the range
cv2.bitwise_and(a, b, mask=mask)            # also bitwise_or, bitwise_xor, bitwise_not

The grayscale conversion uses weights 0.299 for red, 0.587 for green and 0.114 for blue. See Color Spaces and Arithmetic, Bitwise Ops and Masking.

Drawing

Python
cv2.line(img, (x1, y1), (x2, y2), (b, g, r), thickness)
cv2.rectangle(img, (x1, y1), (x2, y2), color, thickness)    # thickness -1 fills
cv2.circle(img, (cx, cy), radius, color, thickness)
cv2.putText(img, "text", (x, y), cv2.FONT_HERSHEY_SIMPLEX, scale, color, thickness)
cv2.polylines(img, [pts], isClosed, color, thickness)

Drawing functions modify the image in place, so draw on a copy if you still need the original. Colors are (b, g, r). See Drawing Shapes and Text.

Geometry

Python
cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)
cv2.resize(img, None, fx=0.5, fy=0.5)
cv2.flip(img, flipCode)                       # 1 horizontal, 0 vertical, -1 both
cv2.rotate(img, cv2.ROTATE_90_CLOCKWISE)
M = cv2.getRotationMatrix2D((cx, cy), angle, scale)           # 2x3, positive angle = counterclockwise
cv2.warpAffine(img, M, (out_w, out_h))
H = cv2.getPerspectiveTransform(src4, dst4)                   # float32 4x2 arrays, 3x3 result
cv2.warpPerspective(img, H, (out_w, out_h))
Interpolation Use for
INTER_NEAREST masks and label images, fastest
INTER_LINEAR default, good for enlarging
INTER_CUBIC smoother enlargement, slower
INTER_AREA shrinking, avoids aliasing
INTER_LANCZOS4 high quality enlargement

See Resizing, Cropping and Flipping, Translation, Rotation and Affine Transforms and Interpolation and Image Quality.

Filtering and thresholds

Python
cv2.blur(img, (5, 5))                         # box
cv2.GaussianBlur(img, (5, 5), 0)              # sigma 0 means "derive from the kernel size"
cv2.medianBlur(img, 5)                        # odd int, best for salt-and-pepper noise
cv2.bilateralFilter(img, 9, 75, 75)           # d, sigmaColor, sigmaSpace
cv2.filter2D(img, -1, kernel)                 # -1 keeps the input depth; computes correlation
ret, bw = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY)
ret, bw = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
bw = cv2.adaptiveThreshold(gray, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 11, 2)
eq = cv2.equalizeHist(gray)
hist = cv2.calcHist([gray], [0], None, [256], [0, 256])
Threshold type Output
THRESH_BINARY max value where pixel > threshold, else 0
THRESH_BINARY_INV the opposite
THRESH_TRUNC values above the threshold are capped at it
THRESH_TOZERO keep values above the threshold, zero the rest
THRESH_TOZERO_INV keep values at or below the threshold
THRESH_OTSU, THRESH_TRIANGLE combine with a type to pick the threshold automatically

See Thresholding, Histograms and Equalization, Blurring and Noise Reduction and Kernels and filter2D.

Morphology

Python
k = cv2.getStructuringElement(cv2.MORPH_RECT, (5, 5))    # also MORPH_ELLIPSE, MORPH_CROSS
cv2.erode(bw, k, iterations=1)
cv2.dilate(bw, k, iterations=1)
cv2.morphologyEx(bw, cv2.MORPH_OPEN, k)                  # remove specks
cv2.morphologyEx(bw, cv2.MORPH_CLOSE, k)                 # fill small holes

Other operations for morphologyEx: MORPH_GRADIENT (outline), MORPH_TOPHAT (small bright details) and MORPH_BLACKHAT (small dark details). See Morphological Operations.

Edges, contours and shapes

Python
gx = cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)          # dx=1, dy=0
lap = cv2.Laplacian(gray, cv2.CV_64F)
edges = cv2.Canny(gray, 100, 200)                        # low, high thresholds
contours, hierarchy = cv2.findContours(bw, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)   # OpenCV 4
cv2.drawContours(img, contours, -1, (0, 255, 0), 2)      # -1 draws all
area = cv2.contourArea(c)
perim = cv2.arcLength(c, True)
x, y, w, h = cv2.boundingRect(c)
approx = cv2.approxPolyDP(c, 0.02 * perim, True)
hull = cv2.convexHull(c)
lines = cv2.HoughLinesP(edges, 1, np.pi / 180, 50, minLineLength=40, maxLineGap=10)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1.2, 30, param1=100, param2=40)
Contour option Meaning
RETR_EXTERNAL outermost contours only
RETR_LIST all contours, no hierarchy
RETR_CCOMP two-level hierarchy (outer and holes)
RETR_TREE full nesting hierarchy
CHAIN_APPROX_NONE keep every boundary point
CHAIN_APPROX_SIMPLE compress straight runs to their end points

findContours changes what it returns between major versions, so a two-value unpack is correct for OpenCV 4 only. Use a binary image with white objects on black. See Gradients, Sobel and Laplacian, Canny Edge Detection, Finding and Drawing Contours, Contour Features and Detecting Lines, Circles and Shapes.

Features, matching and detection

Python
res = cv2.matchTemplate(gray, templ, cv2.TM_CCOEFF_NORMED)
_, max_val, _, max_loc = cv2.minMaxLoc(res)              # best match is the max for the NORMED correlation modes
orb = cv2.ORB_create(1000)
kp, des = orb.detectAndCompute(gray, None)
bf = cv2.BFMatcher(cv2.NORM_HAMMING)                     # NORM_L2 for SIFT descriptors
matches = bf.knnMatch(des1, des2, k=2)
H, inliers = cv2.findHomography(src_pts, dst_pts, cv2.RANSAC, 5.0)
corners = cv2.goodFeaturesToTrack(gray, 200, 0.01, 10)
blob = cv2.dnn.blobFromImage(img, 1 / 255.0, (640, 640), swapRB=True)
net = cv2.dnn.readNet("model.onnx"); net.setInput(blob); out = net.forward()

For TM_SQDIFF and TM_SQDIFF_NORMED the best match is the minimum, and for the correlation modes it is the maximum. See Template Matching, Corners and Keypoints, Feature Matching and Homography and The dnn Module.

Calibration, speed and debugging

Python
ret, K, dist, rvecs, tvecs = cv2.calibrateCamera(obj_points, img_points, (w, h), None, None)
undistorted = cv2.undistort(img, K, dist)
cv2.setNumThreads(4)
t0 = cv2.getTickCount()
# ... work ...
seconds = (cv2.getTickCount() - t0) / cv2.getTickFrequency()

Quick checks when something looks wrong: print img.shape and img.dtype, confirm img is not None, check for an odd kernel size, and ask whether a function wants gray or color. See Camera Calibration and Undistortion, Making OpenCV Fast and Common Mistakes and Debugging.

Runnable shape and dtype checks

Python Shapes, slicing and size order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Saturation, grayscale weights and hue range

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. You call cv2.resize(img, (200, 100)). What size does the result have?

    The size argument is (width, height), but the resulting array shape is (height, width), so (100, 200).
  2. 2. Which interpolation flag is usually best for shrinking an image?

    INTER_AREA averages the source pixels that map to each output pixel, which avoids aliasing when reducing.
  3. 3. For cv2.TM_SQDIFF, where is the best match in the result map?

    SQDIFF measures squared differences, so a perfect match gives 0, the minimum. The normalized correlation modes use the maximum.
  4. 4. What is the hue range of an 8-bit HSV image in OpenCV?

    Hue is stored as degrees divided by two so that it fits in a uint8, giving 0 to 179.

Summary

  • Shape is (h, w, c), indexing is [y, x], but points and sizes in function arguments are (x, y) and (w, h).
  • Colors are B, G, R, uint8 math in numpy wraps and cv2.add saturates, and 8-bit hue runs 0 to 179.
  • Gray input is required by thresholding, Canny, contours (after thresholding) and the Hough functions.
  • Pick the interpolation to match the job: INTER_AREA to shrink, INTER_LINEAR or INTER_CUBIC to enlarge, INTER_NEAREST for masks.
  • findContours returns two values in OpenCV 4, and template matching treats TM_SQDIFF as a minimum search.
  • When in doubt, print shape and dtype, and check for None after imread.

You have reached the end of the OpenCV tutorial. A good next step is to rebuild one of the projects, starting with the document scanner, from memory.