Sub topic 12
Polygons and Polylines
OpenCV draws shapes with more than two corners using cv2.polylines, cv2.fillPoly, and cv2.fillConvexPoly. This chapter covers the point format they expect, the difference between an outline and a fill, and the errors that format causes. It assumes you can already draw on a copy of an image and that you know OpenCV uses (x, y) points and BGR colors. It also assumes you know NumPy shapes and dtypes.
Three functions for multi-point shapes
| Function | Draws | Handles concave shapes | Several shapes per call |
|---|---|---|---|
| `cv2.polylines` | Outline only, open or closed | Yes | Yes |
| `cv2.fillPoly` | Filled area | Yes | Yes |
| `cv2.fillConvexPoly` | Filled area | No, convex only | No, one shape |
All three modify the image in place and return it. As with the other drawing functions, call them on a copy if you still need the original.
The point format
polylines and fillPoly take a list of arrays, not a single array. Each array is one polygon (or one path). A typical call wraps a single polygon in a list: [pts].
Each polygon array should have dtype int32 and shape (N, 1, 2), where N is the number of vertices. Each vertex is (x, y), so the column comes first, as in every other OpenCV drawing function.
import cv2
import numpy as np
canvas = np.zeros((240, 320, 3), dtype=np.uint8)
points = np.array([[40, 40], [280, 60], [240, 200], [60, 180]], dtype=np.int32)
pts = points.reshape(-1, 1, 2)
print(pts.shape, pts.dtype) # (4, 1, 2) int32
open_path = canvas.copy()
cv2.polylines(open_path, [pts], isClosed=False, color=(0, 255, 255), thickness=2)
closed_path = canvas.copy()
cv2.polylines(closed_path, [pts], isClosed=True, color=(0, 255, 255), thickness=2,
lineType=cv2.LINE_AA)
cv2.imwrite("open.png", open_path)
cv2.imwrite("closed.png", closed_path)With isClosed=False, OpenCV connects vertex 1 to 2, 2 to 3, and 3 to 4, and leaves the last gap open. With isClosed=True, it also connects the last vertex back to the first. You do not repeat the first point at the end.
Recent OpenCV versions also accept an (N, 2) int32 array. The (N, 1, 2) shape is the documented convention and works in every version, so this chapter uses it.
Why dtype matters
The drawing functions need integer pixel coordinates. A float array or a default NumPy integer array is the most common reason these calls fail.
np.array([[10, 20], [30, 40]])has dtypeint64on most Linux and macOS systems, which OpenCV rejects.- Coordinates computed by division or scaling are
float64.
The failure is an assertion error from cv::polylines or cv::fillPoly, and it often mentions checkVector(2, CV_32S). The message does not say "wrong dtype", so check the dtype first when you see it.
Round floats before casting. A plain astype truncates toward zero, which shifts shapes by up to one pixel:
import cv2
import numpy as np
canvas = np.zeros((240, 320, 3), dtype=np.uint8)
# Relative coordinates in 0..1, as a detector or annotation tool might give them
relative = np.array([[0.1, 0.2], [0.8, 0.25], [0.7, 0.85], [0.2, 0.8]])
h, w = canvas.shape[:2]
pixels = np.round(relative * [w, h]).astype(np.int32) # x scales by width, y by height
cv2.polylines(canvas, [pixels.reshape(-1, 1, 2)], True, (0, 200, 255), 2, cv2.LINE_AA)
cv2.imwrite("relative.png", canvas)The multiplier [w, h] follows the (x, y) order of the points. Using [h, w] is a frequent bug and gives a stretched or mirrored-looking shape.
Sub-pixel coordinates
If you need sub-pixel placement, the shift argument treats coordinates as fixed-point numbers with that many fractional bits. With shift=4, the integer 165 means 165 / 16 = 10.3125. This is rarely needed. Most code rounds to whole pixels, as above.
Filled polygons
cv2.fillPoly(img, pts, color) fills the interior. It does not take a thickness. To get a fill and an outline, call both functions with the same points.
import cv2
import numpy as np
img = np.full((240, 320, 3), 40, dtype=np.uint8)
tri = np.array([[160, 30], [290, 210], [30, 210]], dtype=np.int32).reshape(-1, 1, 2)
canvas = img.copy()
cv2.fillPoly(canvas, [tri], (60, 160, 60))
cv2.polylines(canvas, [tri], True, (255, 255, 255), 2, cv2.LINE_AA)
cv2.imwrite("triangle.png", canvas)Draw the fill first and the outline second. Otherwise the fill covers the inner half of the outline.
Several polygons in one call
Pass more than one array in the list to draw them all with the same color:
import cv2
import numpy as np
canvas = np.zeros((200, 320, 3), dtype=np.uint8)
left = np.array([[20, 40], [140, 40], [80, 160]], dtype=np.int32).reshape(-1, 1, 2)
right = np.array([[180, 40], [300, 40], [300, 160], [180, 160]], dtype=np.int32).reshape(-1, 1, 2)
cv2.fillPoly(canvas, [left, right], (255, 128, 0))
cv2.imwrite("two_shapes.png", canvas)Each polygon in a fillPoly call is separate, but the filled areas are combined with an even-odd rule. A polygon fully inside another one therefore cuts a hole in it. The OpenCV documentation lists areas with holes and self-intersecting contours as cases fillPoly handles.
import cv2
import numpy as np
canvas = np.zeros((220, 220, 3), dtype=np.uint8)
outer = np.array([[20, 20], [200, 20], [200, 200], [20, 200]], dtype=np.int32).reshape(-1, 1, 2)
inner = np.array([[70, 70], [150, 70], [150, 150], [70, 150]], dtype=np.int32).reshape(-1, 1, 2)
cv2.fillPoly(canvas, [outer, inner], (0, 180, 255))
cv2.imwrite("frame.png", canvas)The output is a square ring with a black center.
Convex fills
cv2.fillConvexPoly(img, points, color) takes one array, not a list, and assumes the shape is convex. It is faster than fillPoly. If you give it a concave shape, the result is not reliable, so use fillPoly when you are unsure.
Polygons as masks
A filled polygon drawn on a single-channel black image is a mask. This is the most common production use of fillPoly, because it selects an arbitrary region of interest, which slicing cannot do.
import cv2
import numpy as np
# A synthetic gradient image so the example runs without any file
img = np.zeros((240, 320, 3), dtype=np.uint8)
img[:, :, 0] = np.linspace(0, 255, 320, dtype=np.uint8)[None, :]
img[:, :, 2] = np.linspace(0, 255, 240, dtype=np.uint8)[:, None]
region = np.array([[160, 20], [300, 120], [160, 220], [20, 120]], dtype=np.int32).reshape(-1, 1, 2)
mask = np.zeros(img.shape[:2], dtype=np.uint8) # (height, width), one channel
cv2.fillPoly(mask, [region], 255)
masked = cv2.bitwise_and(img, img, mask=mask) # pixels outside the polygon become 0
cv2.imwrite("masked.png", masked)
print(int(mask.sum() // 255), "pixels inside the polygon")The mask uses img.shape[:2], which is (height, width). Passing the full three-element shape would give a three-channel mask and bitwise_and would reject it.
Outline plus translucent fill
Combine fillPoly on an overlay copy with cv2.addWeighted, then draw a solid outline on the result. This keeps the outline crisp while the interior stays see-through:
import cv2
import numpy as np
img = np.full((240, 320, 3), 200, dtype=np.uint8)
poly = np.array([[60, 40], [260, 70], [230, 200], [50, 170]], dtype=np.int32).reshape(-1, 1, 2)
overlay = img.copy()
cv2.fillPoly(overlay, [poly], (0, 0, 255))
alpha = 0.35
result = cv2.addWeighted(overlay, alpha, img, 1 - alpha, 0)
cv2.polylines(result, [poly], True, (0, 0, 180), 2, cv2.LINE_AA)
cv2.imwrite("highlight.png", result)Blending the whole image costs more than blending only the region, so for large images, blend a cropped region of interest and write it back.
Common errors
- Passing an array instead of a list.
cv2.polylines(img, pts, ...)with a bare array treats each row as a separate path, so you get unexpected lines or an error. Write[pts]. - Wrong dtype. Use
np.int32. Checkpts.dtypebefore the call. - Drawing on the original. The functions return the same array they modify. Calling
canvas = imgand drawing changesimgtoo. Useimg.copy(). - Swapped axes. Points are
(x, y). Row and column indexing is(y, x). Do not feednp.argwhereresults straight in without flipping the columns, as innp.argwhere(m)[:, ::-1]. - Using
fillConvexPolyon a concave shape. The output can look wrong with no error. - Expecting clipping errors. Points outside the image do not raise errors. OpenCV clips the drawing to the image bounds, so a shape that is entirely off-image silently draws nothing.
- Open outlines. A shape that looks like it is missing an edge usually has
isClosed=False.
Exercises
Exercise
A learner writes pts = np.array([[50, 50], [150, 60], [120, 140]]) and calls cv2.polylines(img, [pts], True, (0, 255, 0), 2). On their system it raises an assertion error. What is the most likely cause, and what is the fix?
Show answer
The array has the default integer dtype, which is int64 on most systems, and OpenCV requires int32 coordinates. Create it with dtype=np.int32 (or call .astype(np.int32)), and optionally reshape it to (-1, 1, 2).
Exercise
You need to keep only the pixels of a photo that lie inside an arbitrary four-point region and set everything else to black. Which drawing function builds the mask, what shape and dtype should the mask have, and which function applies it?
Show answer
Use cv2.fillPoly on a single-channel mask created with np.zeros(img.shape[:2], dtype=np.uint8), filling the region with 255. Then apply it with cv2.bitwise_and(img, img, mask=mask).
Exercise
What does cv2.fillPoly(canvas, [outer, inner], color) produce when inner lies completely inside outer, and why?
Show answer
It produces the outer shape with a hole where the inner shape is. The areas of the polygons in one call are combined with an even-odd rule, so the region covered by both polygons is left unfilled.