Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 54 ยท Pixels and Color

Drawing Shapes and Text

Draw lines, rectangles, circles, polygons and text on images with OpenCV, understand thickness, filled shapes, anti-aliasing, and rebuild rectangle and line drawing in NumPy.

Detecting something is only half the job; you usually want to show it. Drawing a box around a face, a line along a lane, a label next to an object, or a dot on a keypoint is how computer-vision results become visible. OpenCV ships a small set of drawing functions for exactly this: line, rectangle, circle, ellipse, polylines, fillPoly and putText.

In this lesson you will learn the argument pattern they all share, the coordinate and color conventions that trip people up, and how thickness, filling and anti-aliasing work. Because the real cv2 cannot run in the browser, the calls are shown read-only, and then you rebuild the core of rectangle, line and circle on a plain NumPy array so you can see how the pixels actually change. Make sure you are comfortable with Images Are NumPy Arrays and Accessing and Modifying Pixels first.

The shared pattern

Every drawing function draws in place on the array you give it and also returns that same array. It does not make a copy, so draw on a copy if you want to keep the original.

Python
import cv2
import numpy as np

canvas = np.zeros((200, 300, 3), dtype=np.uint8)   # black, 200 rows, 300 columns

cv2.line(canvas, (20, 20), (280, 20), (255, 255, 255), 2)
cv2.rectangle(canvas, (40, 50), (140, 120), (0, 255, 0), 3)
cv2.circle(canvas, (220, 100), 40, (0, 0, 255), -1)
cv2.putText(canvas, "Hello", (40, 170), cv2.FONT_HERSHEY_SIMPLEX,
            1.0, (255, 255, 0), 2, cv2.LINE_AA)

Rules every draw call follows

Points are (x, y) Column first, then row. Opposite of indexing.
Colors are BGR (255, 0, 0) is blue, not red.
Integers only Float coordinates raise an error.
Draws in place The array you pass is changed.

Four rules cause most drawing bugs.

1 / 2

The two conventions that matter most are the point order and the color order. A point is (x, y), meaning column then row, which is the reverse of NumPy indexing img[row, column]. A color is (blue, green, red). On a grayscale image the color is a single number such as 255. More on the color order is in Color Spaces: BGR, RGB, Gray and HSV.

The functions at a glance

Python
cv2.line(img, pt1, pt2, color, thickness=1, lineType=cv2.LINE_8)
cv2.rectangle(img, pt1, pt2, color, thickness=1)       # opposite corners
cv2.circle(img, center, radius, color, thickness=1)
cv2.ellipse(img, center, (ax1, ax2), angle, start, end, color, thickness)
cv2.polylines(img, [pts], isClosed, color, thickness)  # pts: int32, shape (N, 1, 2)
cv2.fillPoly(img, [pts], color)
cv2.putText(img, text, org, fontFace, fontScale, color, thickness, lineType)

A few details worth knowing:

  • rectangle takes two opposite corners: top-left and bottom-right are the usual choice. Both corner pixels are drawn, so the rectangle covers x2 - x1 + 1 columns.
  • circle takes a center and an integer radius. A thickness of -1 fills it.
  • polylines and fillPoly take a list of point arrays, so you can draw several polygons in one call. The array must have type int32; np.array(points, dtype=np.int32).reshape(-1, 1, 2) is the safe way to build one.
  • putText places the text with org as the bottom-left corner of the first character, not the top-left. The built-in Hershey fonts cover plain ASCII only; accented letters and non-Latin scripts show as question marks. For those, draw with Pillow instead.
  • cv2.getTextSize(text, font, scale, thickness) returns the width and height the text will take, so you can center it or draw a background box behind it.

Warning: Passing floats such as (10.5, 20.0) as a point raises an error in current OpenCV 4 builds. Round first: tuple(np.round(p).astype(int)). Also, NumPy integer types inside a tuple are fine, but convert to plain int if you ever see a type complaint.

More shapes and options

Ellipses and arcs. cv2.ellipse(img, center, axes, angle, startAngle, endAngle, color, thickness) takes the half-lengths of the two axes (a, b), a rotation angle of the whole ellipse, and the start and end angles of the arc in degrees measured clockwise from the x axis. 0 to 360 draws the full ellipse; 0 to 180 draws the lower half of an upright one.

Python
cv2.ellipse(canvas, (150, 100), (80, 40), 0, 0, 360, (255, 200, 0), 2)      # full ellipse
cv2.ellipse(canvas, (150, 100), (60, 60), 0, 0, 180, (0, 200, 255), 3)      # half circle (an arc)
cv2.ellipse(canvas, (150, 100), (80, 30), 45, 0, 360, (0, 255, 0), -1)      # rotated and filled

Arrows. cv2.arrowedLine(img, start, end, color, thickness, line_type, shift, tipLength) draws a line with an arrowhead at the end. tipLength is the head size as a fraction of the line length: 0.1 is a small head, 0.5 a big one. It is the natural way to show motion vectors from optical flow.

Polylines and polygons. cv2.polylines takes a list of point arrays, each of shape (N, 1, 2) and type int32, and an isClosed flag. cv2.fillPoly fills them. A common mistake is passing a plain (N, 2) list or a float array.

Python
pts = np.array([[20, 150], [100, 40], [180, 150]], dtype=np.int32).reshape(-1, 1, 2)
cv2.polylines(canvas, [pts], isClosed=True, color=(0, 255, 255), thickness=2)    # triangle outline
cv2.fillPoly(canvas, [pts], (0, 120, 255))                                         # filled triangle

# centroid of the triangle: the mean of its vertices
cx, cy = pts[:, 0, 0].mean(), pts[:, 0, 1].mean()
cv2.circle(canvas, (int(cx), int(cy)), 4, (255, 255, 255), -1)

For a triangle (or any polygon you want the center of) cv2.moments on the contour is more general; see Contour Features.

Text flags. cv2.putText(img, text, org, font, fontScale, color, thickness, lineType, bottomLeftOrigin): the last argument is False by default. Setting it to True tells OpenCV that the image origin is at the bottom-left, so the text comes out flipped vertically; it is only useful if you flip the image yourself. fontScale multiplies the font's base size, so 0.5 to 1 is typical on a 640-pixel-wide image.

Markers. cv2.drawMarker(img, position, color, markerType=cv2.MARKER_CROSS, markerSize=20, thickness=2) is a quick way to mark a point with a cross, diamond or star.

Rebuilding rectangle on an array

A rectangle is only slicing. A filled rectangle assigns a value to a block of rows and columns; an outline assigns it to four thin strips. Writing this yourself shows what thickness=-1 really means. This stand-in treats the thickness as extra pixels drawn inward from each edge, which is a simplification of how OpenCV centers thick lines on the boundary.

Python Rectangle with slicing

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.

The first rectangle is an outline from column 1 to 10, row 1 to 7. The second is solid. Notice that the last line indexes the canvas as [row, column] while the function took (x, y): the same pixel, written two ways.

Rebuilding line and circle

A line between two points cannot be a slice, because it is diagonal. The classic answer is Bresenham's algorithm, which walks from one end to the other using only integer arithmetic and picks the pixel closest to the true line at each step. OpenCV's LINE_8 mode draws an 8-connected line in the same spirit. A circle can be drawn by testing which pixels lie within a distance of the center.

Python Bresenham line and a filled circle

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.

np.ogrid builds a row vector and a column vector that broadcast against each other, so the distance test runs for every pixel without a Python loop (see Broadcasting). The same trick builds any "inside the shape" mask, which you can later use with masking techniques from Arithmetic, Bitwise Ops and Masking.

Anti-aliasing

A one-pixel line drawn by the rules above looks jagged on a diagonal because each pixel is fully on or off. lineType=cv2.LINE_AA draws an anti-aliased line instead: pixels near the edge get a partial brightness that matches how much of the pixel the line covers. Edges look smooth, at a small speed cost. It works on 8-bit images, and is the best choice for text and for circles you will look at.

Python Why anti-aliasing looks smoother

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.

This is only an illustration of the idea (real OpenCV uses its own filtered line algorithm), but it shows the principle: instead of two values, 0 and 255, the edge pixels take in-between values, and your eye reads a smooth line. Anti-aliased drawing also means the output contains grays even if you drew in a single color, which matters if you later threshold the image to find your drawing.

Practical tips

  • Draw on a copy of the frame: vis = img.copy(). Drawing on the original changes the pixels you may still want to analyze.
  • Draw last. Run detection on the clean image, then annotate. A green box drawn first can become a "feature" in later steps.
  • Make labels readable. Use getTextSize and draw a filled rectangle behind the text, or draw the text twice, first in a thick dark color, then thinner in a light one.
  • Clip to the image. OpenCV clips shapes that fall outside the image silently. Your own NumPy stand-ins need explicit bounds checks, as slices past the edge are clipped but single-pixel indexing past the edge raises IndexError.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A point passed to cv2.circle is (40, 100). Which pixel of the array does it refer to?

    OpenCV points are (x, y), meaning column then row. NumPy indexing is [row, column], so the pixel is img[100, 40].
  2. 2. What does a thickness of -1 do in cv2.rectangle and cv2.circle?

    A negative thickness means fill the entire shape with the color.
  3. 3. Where is the org point of cv2.putText placed relative to the text?

    putText anchors the text by its bottom-left corner (the baseline start). If text appears cut off at the top of the image, move org down.
  4. 4. Why should you usually annotate a copy of an image?

    Drawing functions change the array you pass in. Annotate a copy and keep the original clean for detection and measurement.

Summary

  • line, rectangle, circle, ellipse, polylines, fillPoly and putText draw in place and return the same array.
  • Points are (x, y) (column, row) and colors are (B, G, R); coordinates must be integers.
  • Thickness is the outline width in pixels; -1 fills the shape. lineType=cv2.LINE_AA smooths edges.
  • putText anchors at the bottom-left, supports only plain ASCII with the built-in fonts, and getTextSize measures it.
  • A rectangle is a slice assignment, a line is Bresenham's algorithm, and a circle is a distance test. All of them are just ways of choosing which pixels to overwrite.

Next up: change the size and orientation of images in Resizing, Cropping and Flipping.