OpenCV is still the first library most Python developers reach for when they need to work with images and video: reading photos, cleaning them up, finding edges, measuring objects and preparing frames for deep learning models. In 2026 it also got its biggest update in years. OpenCV 5.0 arrived in June 2026, the opencv-python 5.1.0 wheels followed on 17 November 2026, and a few familiar things (Haar cascades, cv2.ml) are no longer in the main package. In this OpenCV Python tutorial we build a small computer vision program step by step with OpenCV 5.1.0: load and resize an image, threshold it with Otsu, detect edges with Canny, find contours, name each shape, count objects by color with HSV masks, and finally check what changed between OpenCV 4 and 5. Every output block below is the real output of the script above it.
What you will build
- A reproducible test photo with coins, tiles and triangles in three colors (generated by code, so you can run everything offline).
- A binary mask of all objects using an automatic Otsu threshold and morphology.
- Canny edge detection, contour detection and shape names with
approxPolyDP, drawn back on the image with OpenCV 5's new TrueType text. - Object counting per color with
cv2.inRangeandconnectedComponentsWithStats. - A side-by-side check of OpenCV 4.14 and 5.1 so you know what breaks when you upgrade.
Setup
uv venv -p 3.14 && source .venv/bin/activate
uv pip install "opencv-python-headless==5.1.0.95" numpy
python step1_load.py
Pick one OpenCV package per environment. opencv-python includes GUI functions such as cv2.imshow; opencv-python-headless has no GUI and is the right choice for servers, Docker and notebooks; the -contrib variants add the extra modules. Installing two of them in the same environment is the classic cause of strange import errors. We use the headless build and save results to files instead of opening windows.
Step 1: Load, inspect, resize and crop an image
We draw a test scene with OpenCV's own drawing functions, add a little texture and blur so it behaves like a camera photo, save it as scene.png, and then load it back exactly like you would load any image.
import cv2
import numpy as np
print("OpenCV", cv2.__version__)
# Build a reproducible test photo: coins, tiles and triangles on a light table
rng = np.random.default_rng(7)
img = np.full((480, 720, 3), (225, 230, 235), dtype=np.uint8) # BGR!
img = cv2.add(img, rng.integers(0, 18, img.shape, dtype=np.uint8)) # table texture
for (x, y, r, color) in [(110, 110, 50, (40, 40, 200)), (290, 100, 40, (40, 40, 200)),
(600, 380, 55, (200, 90, 30)), (110, 370, 40, (40, 160, 40))]:
cv2.circle(img, (x, y), r, color, -1, cv2.LINE_AA) # coins
for (x1, y1, x2, y2, color) in [(420, 50, 520, 150, (200, 90, 30)), (250, 250, 400, 330, (40, 40, 200))]:
cv2.rectangle(img, (x1, y1), (x2, y2), color, -1) # tiles
for pts, color in [([(600, 40), (690, 200), (540, 200)], (40, 160, 40)),
([(230, 440), (300, 360), (370, 440)], (200, 90, 30))]:
cv2.fillPoly(img, [np.array(pts, np.int32)], color, cv2.LINE_AA) # triangles
img = cv2.GaussianBlur(img, (5, 5), 0) # camera softness
cv2.imwrite("scene.png", img)
# Load it back like any photo
img = cv2.imread("scene.png") # returns None if the path is wrong
if img is None:
raise FileNotFoundError("scene.png")
h, w, channels = img.shape
print(f"shape={img.shape} dtype={img.dtype} -> {w}x{h} pixels, {channels} channels")
print("pixel at (x=110, y=110) in BGR:", img[110, 110].tolist())
small = cv2.resize(img, (w // 2, h // 2), interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
crop = img[40:160, 410:530] # rows (y) first, then columns (x)
cv2.imwrite("scene_small.jpg", small, [cv2.IMWRITE_JPEG_QUALITY, 90])
cv2.imwrite("scene_gray.png", gray)
print("small:", small.shape, "| gray:", gray.shape, "| crop:", crop.shape)
print("gray mean brightness:", round(float(gray.mean()), 1))
OpenCV 5.1.0
shape=(480, 720, 3) dtype=uint8 -> 720x480 pixels, 3 channels
pixel at (x=110, y=110) in BGR: [40, 40, 200]
small: (240, 360, 3) | gray: (480, 720) | crop: (120, 120, 3)
gray mean brightness: 210.2
Three things trip up every beginner here. First, an image is just a NumPy array of shape (height, width, channels), so a 720x480 photo has shape (480, 720, 3). Second, OpenCV stores colors as BGR, not RGB: the red coin's pixel is [40, 40, 200], with red in the last position. Third, indexing and cropping use rows first, so img[y, x] and img[y1:y2, x1:x2]. cv2.resize takes the size the other way round, as (width, height). Use INTER_AREA when shrinking and INTER_CUBIC or INTER_LINEAR when enlarging. Also note that cv2.imread does not raise an exception for a wrong path; it returns None, so always check it. If you only need simple resizing, cropping and watermarks for a website, Pillow is lighter; see our Pillow image resize and crop guide.
Step 2: Threshold with Otsu and detect edges with Canny
Most classic computer vision pipelines start the same way: convert to grayscale, blur to remove noise, then separate objects from the background. Otsu's method looks at the histogram and picks the best threshold for you, and THRESH_BINARY_INV makes the dark objects white on a black background, which is what contour functions expect. A morphological open removes speckles and a close fills tiny holes.
import cv2
import numpy as np
img = cv2.imread("scene.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0) # remove texture noise first
# Otsu picks the threshold automatically; INV makes the dark objects white
t, mask = cv2.threshold(blur, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
mask = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel) # drop speckles
mask = cv2.morphologyEx(mask, cv2.MORPH_CLOSE, kernel) # fill pin holes
edges = cv2.Canny(blur, 50, 150)
print(f"Otsu threshold: {t:.0f}")
print(f"object pixels: {cv2.countNonZero(mask)} of {mask.size} ({cv2.countNonZero(mask) / mask.size:.1%})")
print(f"edge pixels: {cv2.countNonZero(edges)}")
cv2.imwrite("mask.png", mask)
cv2.imwrite("edges.png", edges)
Otsu threshold: 167
object pixels: 68569 of 345600 (19.8%)
edge pixels: 3244
Otsu chose a threshold of 167 on its own, and 19.8% of the image became object pixels. Canny found 3244 edge pixels: thin one-pixel outlines of every shape. The two Canny numbers (50 and 150) are the low and high hysteresis thresholds; a ratio between 1:2 and 1:3 is a good starting point, and blurring first matters more than fine-tuning them. For segmentation, the filled Otsu mask is usually more useful than Canny edges, because contours of a filled region are closed and have a meaningful area.
Step 3: Find contours, count objects and detect shapes
cv2.findContours traces the outline of every white region in the mask. RETR_EXTERNAL keeps only outer outlines, and CHAIN_APPROX_SIMPLE compresses straight lines into their end points. We drop tiny contours by area, compute each center from image moments, and name the shape by how many corners approxPolyDP finds after simplifying the outline to 3% of its perimeter.
import cv2
img = cv2.imread("scene.png")
mask = cv2.imread("mask.png", cv2.IMREAD_GRAYSCALE)
contours, _ = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
def shape_name(c):
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.03 * peri, True)
if len(approx) == 3:
return "triangle"
if len(approx) == 4:
x, y, w, h = cv2.boundingRect(approx)
return "square" if 0.9 <= w / h <= 1.1 else "rectangle"
return "circle"
font = cv2.FontFace("sans") # OpenCV 5: TrueType text
objects = sorted((c for c in contours if cv2.contourArea(c) > 500),
key=lambda c: cv2.boundingRect(c)[0]) # left to right
print(f"contours found: {len(contours)}, objects kept: {len(objects)}")
print(f"{'#':>2} {'shape':<9} {'area':>7} {'center':>11}")
for i, c in enumerate(objects, 1):
m = cv2.moments(c)
cx, cy = int(m["m10"] / m["m00"]), int(m["m01"] / m["m00"])
name = shape_name(c)
print(f"{i:>2} {name:<9} {cv2.contourArea(c):>7.0f} {str((cx, cy)):>11}")
cv2.drawContours(img, [c], -1, (0, 220, 255), 3)
cv2.putText(img, f"{i} {name}", (cx - 45, cy + 6), (255, 255, 255), font, 18, 700)
cv2.imwrite("annotated.png", img)
print("saved annotated.png")
contours found: 8, objects kept: 8
# shape area center
1 circle 7936 (109, 110)
2 circle 5008 (110, 370)
3 triangle 5656 (300, 413)
4 rectangle 11994 (325, 290)
5 circle 5080 (290, 99)
6 square 9994 (470, 100)
7 triangle 11970 (610, 146)
8 circle 9596 (600, 380)
saved annotated.png
All 8 objects were found and classified correctly: 4 circles, 2 triangles, 1 square and 1 rectangle. The aspect ratio of the bounding box separates the square tile from the rectangle. Areas are in pixels, so if you know the real size of one reference object (for example a coin), you can convert every area to square millimetres. The labels are drawn with cv2.FontFace("sans"), the new OpenCV 5 TrueType text API: you pass the color, a font object and a size in pixels, plus an optional weight (700 = bold). In OpenCV 4 you would use the old signature cv2.putText(img, text, org, cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2), which still works in 5.x.
Step 4: Detect colors with HSV masks
To count objects by color, convert to HSV, where hue describes the color independently of brightness. In OpenCV, hue runs from 0 to 179 (not 0 to 360), and red sits at both ends of the range, so it needs two ranges combined with a bitwise OR. connectedComponentsWithStats then labels each separate blob and returns its area and bounding box in one call.
import cv2
import numpy as np
img = cv2.imread("scene.png")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) # hue is easier than BGR
# OpenCV hue runs 0-179; red wraps around, so it needs two ranges
ranges = {
"red": [((0, 120, 80), (10, 255, 255)), ((170, 120, 80), (179, 255, 255))],
"green": [((40, 120, 80), (80, 255, 255))],
"blue": [((100, 120, 80), (130, 255, 255))],
}
for color, parts in ranges.items():
mask = np.zeros(img.shape[:2], np.uint8)
for lo, hi in parts:
mask |= cv2.inRange(hsv, np.array(lo), np.array(hi))
n, labels, stats, _ = cv2.connectedComponentsWithStats(mask)
big = [s for s in stats[1:] if s[cv2.CC_STAT_AREA] > 500] # skip background row 0
areas = sorted(int(s[cv2.CC_STAT_AREA]) for s in big)
print(f"{color:<5} objects: {len(big)} areas: {areas}")
cv2.imwrite(f"only_{color}.png", cv2.bitwise_and(img, img, mask=mask))
red objects: 3 areas: [5111, 7957, 12227]
green objects: 2 areas: [5035, 12072]
blue objects: 3 areas: [5736, 9620, 10197]
The counts match the scene: 3 red objects (two coins and the rectangle), 2 green objects (a coin and a triangle) and 3 blue objects (a coin, the square and a triangle). Row 0 of stats is always the background, which is why the code starts at stats[1:]. The only_red.png file keeps the original colors only where the mask is white, which is handy for debugging your HSV ranges. Real photos need wider ranges and a minimum saturation to ignore gray shadows and reflections; tune them on a few sample images first.
Step 5: What changed in OpenCV 5 for Python users
Most cv2 functions you know still work unchanged, because the Python bindings hide the internal module reshuffle. But a few things were removed or behave differently. We ran the same script in two virtual environments, one with OpenCV 5.1.0 and one with OpenCV 4.14.0.
import cv2
import numpy as np
print("OpenCV", cv2.__version__)
for name in ("CascadeClassifier", "HOGDescriptor", "ml", "FontFace", "CV_Bool", "FaceDetectorYN"):
print(f" cv2.{name:<18} {'yes' if hasattr(cv2, name) else 'NO'}")
print(" dnn engines:", [n for n in dir(cv2.dnn) if n.startswith("ENGINE_")])
# 1D arrays: a std::vector result is now a real 1D array
hist = cv2.calcHist([np.arange(256, dtype=np.uint8).reshape(16, 16)], [0], None, [4], [0, 256])
print(" calcHist shape:", hist.shape)
# UTF-8 text with the built-in TrueType font (Hershey fonts only knew ASCII)
if hasattr(cv2, "FontFace"):
canvas = np.zeros((60, 360, 3), np.uint8)
cv2.putText(canvas, "Café 25°C ✓", (10, 40), (255, 255, 255), cv2.FontFace("sans"), 28)
print(" UTF-8 text pixels drawn:", cv2.countNonZero(cv2.cvtColor(canvas, cv2.COLOR_BGR2GRAY)))
OpenCV 5.1.0:
OpenCV 5.1.0
cv2.CascadeClassifier NO
cv2.HOGDescriptor NO
cv2.ml NO
cv2.FontFace yes
cv2.CV_Bool yes
cv2.FaceDetectorYN yes
dnn engines: ['ENGINE_AUTO', 'ENGINE_OPENCV', 'ENGINE_ORT']
calcHist shape: (4,)
UTF-8 text pixels drawn: 1143
OpenCV 4.14.0:
OpenCV 4.14.0
cv2.CascadeClassifier yes
cv2.HOGDescriptor yes
cv2.ml yes
cv2.FontFace NO
cv2.CV_Bool NO
cv2.FaceDetectorYN yes
dnn engines: []
calcHist shape: (4, 1)
- Haar cascades and HOG are gone from the main package.
cv2.CascadeClassifierandcv2.HOGDescriptorraiseAttributeErrorin 5.1. They moved toopencv_contrib: in our test,opencv-contrib-python-headless5.1.0 still providesCascadeClassifier,HOGDescriptorandcv2.ml. For new code, use the deep-learningcv2.FaceDetectorYN(still in the main package) or a modern detector such as YOLO26 with Ultralytics. cv2.mlmoved to contrib. For SVMs, k-NN, random forests and friends, OpenCV itself recommends scikit-learn; see our scikit-learn Pipeline tutorial.- True 1D arrays. Functions that return a vector now give a real 1D array:
calcHistreturned shape(4,)in 5.1 instead of(4, 1)in 4.14. Code that indexeshist[i][0]must change tohist[i], or usehist.ravel(), which works in both versions. - TrueType text with UTF-8.
cv2.FontFacedraws accents, symbols and non-Latin scripts; our UTF-8 test string drew 1143 pixels. Hershey fonts only supported ASCII. - New DNN engine.
cv2.dnngot a new inference engine that is tried first. In the 5.1 wheel the choices areENGINE_AUTO,ENGINE_OPENCVandENGINE_ORT. The Caffe and Darknet loaders were removed, so convert those models to ONNX and load them withcv2.dnn.readNetFromONNX. - New data types such as
CV_Bool,CV_16BF(bfloat16) and 64-bit integers, which make masks and AI tensors easier to pass around.
OpenCV vs Pillow vs deep learning: which one to use?
- Pillow: open, resize, crop, convert and save images for web apps and reports.
- OpenCV: fast pixel processing, thresholds, edges, contours, measurements, video frames and camera input, plus running ONNX models.
- Deep learning models (YOLO, segmentation, OCR, background removal): when objects vary in shape, lighting and background so much that hand-tuned rules fail. Even then, OpenCV usually does the pre- and post-processing. Two practical examples on PyInns are OCR to extract text from images and removing image backgrounds with rembg.
Best practices for OpenCV in Python
- Always check the result of
cv2.imreadforNone, and usepathlibpaths converted withstr(). - Convert BGR to RGB with
cv2.cvtColor(img, cv2.COLOR_BGR2RGB)before showing an image in Matplotlib or passing it to Pillow or most AI models. - Blur before thresholding or edge detection, and prefer Otsu or
adaptiveThresholdover a hard-coded number when lighting changes. - Filter contours by area (and aspect ratio) to ignore noise, and work on a resized copy of very large photos for speed.
- Pin the OpenCV version in
requirements.txtand install only one OpenCV wheel per environment. - Use NumPy operations instead of Python loops over pixels; a loop over a 12 MP photo can be thousands of times slower.
Common errors and fixes
- AttributeError: module 'cv2' has no attribute 'CascadeClassifier': you are on OpenCV 5. Install
opencv-contrib-python(or the headless variant) instead ofopencv-python, or switch tocv2.FaceDetectorYN. - error: (-215:Assertion failed) !_src.empty(): the image is empty because
cv2.imreadreturnedNone; OpenCV only logscan't open/read file: check file path/integrity. Fix the path or file name. - Colors look wrong (blue faces, orange skies): you showed a BGR image as RGB. Convert with
COLOR_BGR2RGB. - cv2.imshow does nothing or crashes on a server: the headless package has no GUI. Save with
cv2.imwriteor display with Matplotlib in a notebook. - ImportError: libGL.so.1 in Docker: you installed
opencv-pythonin a slim image. Useopencv-python-headless. - findContours finds one big contour: your mask is inverted (white background). Use
THRESH_BINARY_INVorcv2.bitwise_not.
Conclusion
With about 120 lines of Python and OpenCV 5.1.0, we loaded and resized an image, separated 8 objects from the background with an automatic Otsu threshold of 167, traced their outlines, named every shape correctly and counted them by color. These building blocks (grayscale, blur, threshold, contours, HSV masks) power real projects such as counting parts on a conveyor belt, reading gauges, checking labels and cleaning up images before OCR or a neural network. When you upgrade from OpenCV 4, remember the three big changes: Haar cascades and cv2.ml moved to contrib, vector results are now 1D arrays, and text can finally be drawn with real fonts.
FAQ
How do I install OpenCV for Python? Run pip install opencv-python on a desktop or pip install opencv-python-headless on servers and in Docker, then import cv2. Add -contrib to the package name if you need the extra modules such as Haar cascades in OpenCV 5.
Is OpenCV 5 backward compatible with OpenCV 4 code? Mostly. Common functions like imread, cvtColor, threshold, Canny and findContours work the same. Code that uses Haar cascades, HOG, cv2.ml, Caffe or Darknet models, or assumes (N, 1) shaped results needs changes.
Why does OpenCV use BGR instead of RGB? It is a historical choice from early camera and Windows bitmap formats. OpenCV kept it for compatibility, so convert with cv2.cvtColor when other libraries expect RGB.
How do I count objects in an image with OpenCV? Convert to grayscale, blur, threshold (Otsu), clean the mask with morphology, then call cv2.findContours or cv2.connectedComponentsWithStats and count the regions above a minimum area, exactly as in Steps 2 to 4.
Can OpenCV detect objects like people and cars? Yes, by running a deep learning model through cv2.dnn (ONNX), but for training and easy inference most developers use a dedicated library like Ultralytics YOLO and keep OpenCV for image processing around it.
Tested versions: Python 3.14.10 (CPython), opencv-python-headless 5.1.0 (OpenCV 5.1), numpy 2.5.5 on Linux x86_64 (8 CPU cores); the comparison run uses opencv-python-headless 4.14.0 and the contrib check uses opencv-contrib-python-headless 5.1.0.