Sub topic 12
Polygons and Polylines in OpenCV
Prerequisites and the point format
This chapter assumes that you know basic Python, NumPy array indexing, and how OpenCV loads images with cv2.imread. An OpenCV image is a NumPy array. Drawing functions change that array in place, so work on a copy when you need to preserve the original image.
A polygon is a shape made from connected straight-line segments. A polyline is also a sequence of connected segments, but it does not have to form a closed shape. OpenCV draws both with cv2.polylines.
Each point uses Cartesian-style image coordinates:
xincreases from left to right.yincreases from top to bottom.- A point is written as
(x, y). - Coordinates are usually stored as integer values.
This differs from NumPy indexing, where the order is [y, x].
Drawing a polygon outline
cv2.polylines expects a sequence of points. A convenient NumPy representation has shape (number_of_points, 1, 2). The last dimension contains the x and y coordinates.
The following example draws a closed quadrilateral:
import cv2
import numpy as np
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
points = np.array(
[[100, 50], [250, 80], [220, 200], [80, 180]],
dtype=np.int32,
)
# OpenCV commonly receives points with shape (N, 1, 2).
contour = points.reshape(-1, 1, 2)
canvas = img.copy()
cv2.polylines(
canvas,
[contour],
isClosed=True,
color=(0, 255, 255),
thickness=2,
)
if not cv2.imwrite("polygon_outline.jpg", canvas):
raise OSError("Could not save polygon_outline.jpg")The second argument is a list because OpenCV can draw several polylines in one call. isClosed=True adds a final segment from the last point back to the first point. With isClosed=False, OpenCV leaves that final connection open.
The color (0, 255, 255) is yellow in OpenCV's BGR order. The thickness value is measured in pixels.
Several polygons
You can pass multiple point arrays in the same list. OpenCV draws each one using the same color and thickness:
triangle = np.array(
[[40, 40], [140, 40], [90, 130]],
dtype=np.int32,
).reshape(-1, 1, 2)
rectangle = np.array(
[[180, 40], [300, 40], [300, 130], [180, 130]],
dtype=np.int32,
).reshape(-1, 1, 2)
canvas = img.copy()
cv2.polylines(
canvas,
[triangle, rectangle],
isClosed=True,
color=(255, 0, 0),
thickness=3,
)
cv2.imwrite("multiple_polygons.jpg", canvas)For a filled polygon, use cv2.fillPoly instead of cv2.polylines. This is useful for masks or highlighted areas. A filled shape still uses the same point format and coordinate convention.
Common errors
- Using
(row, column)values as(x, y)swaps the horizontal and vertical positions. - Passing floating-point coordinates can cause type errors or unexpected conversions. Use an integer NumPy dtype such as
np.int32. - Forgetting the list around the contour, such as passing
contourinstead of[contour], gives OpenCV the wrong collection structure. - Using
isClosed=Falsewhen outlining a region leaves a visible gap. - Drawing outside the image bounds can place points beyond the visible image. OpenCV clips much of the result, but it is safer to validate coordinates first.
Exercise
What is the effect of changing isClosed from True to False in a four-point polygon?
Show answer
OpenCV stops after drawing the segment from the third point to the fourth point. It does not draw the final segment from the fourth point back to the first.