Sub topic 10
Lines, Rectangles, and Circles
This chapter covers the three basic drawing functions in OpenCV: cv2.line, cv2.rectangle, and cv2.circle. It assumes you can load an image with cv2.imread, know that an image is a NumPy array with shape (height, width, 3) in BGR order, and are comfortable with basic Python functions. You should also know what a pixel and a color channel are.
The working model
All three functions share the same conventions:
- They take the image as the first argument and modify it in place. They also return the same array, so
out = cv2.line(img, ...)andcv2.line(img, ...)both changeimg. - Points are
(x, y)tuples, withxas the column andyas the row. This is the reverse of NumPy indexing, where you writeimg[y, x]. - Colors are tuples in channel order, which is BGR for a color image.
(255, 0, 0)is blue, not red. thicknessis in pixels. A value of-1fills a closed shape. The default is 1.- Coordinates must be integers. Passing floats raises an error in recent OpenCV versions.
| Function | Shape arguments | Fill with `-1`? |
|---|---|---|
| `cv2.line(img, pt1, pt2, color, thickness)` | two end points | no, a line has no interior |
| `cv2.rectangle(img, pt1, pt2, color, thickness)` | two opposite corners | yes |
| `cv2.circle(img, center, radius, color, thickness)` | center point and radius in pixels | yes |
Drawing on a copy
Because the functions write into the array you pass, drawing directly on the image you loaded destroys the original pixels. If you later want to crop, compare, or run a detector on that image, it now contains your lines. Make the copy first and draw on it.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
h, w = img.shape[:2]
canvas = img.copy()
cv2.line(canvas, (0, 0), (w - 1, h - 1), (255, 0, 0), 3)
cv2.rectangle(canvas, (50, 50), (250, 200), (0, 255, 0), 2)
cv2.circle(canvas, (150, 125), 40, (0, 0, 255), -1)
cv2.imwrite("annotated.jpg", canvas)This example draws a blue diagonal from the top-left to the bottom-right pixel. It also draws a green rectangle outline and a filled red circle. Note w - 1 and h - 1: pixel indices run from 0 to size - 1, so the last pixel is at w - 1. Using w still works because OpenCV clips shapes to the image, but the habit of using w - 1 keeps your arithmetic aligned with array indexing.
A slice of an image is a view, not a copy. If you crop with roi = img[50:200, 100:300] and then draw on roi, you also change img. Call .copy() on the crop when you want an independent array.
Lines
cv2.line connects two points. Order does not matter, since swapping pt1 and pt2 draws the same line.
import cv2
import numpy as np
canvas = np.zeros((200, 300, 3), dtype=np.uint8)
cv2.line(canvas, (10, 10), (290, 10), (255, 255, 255), 1)
cv2.line(canvas, (10, 40), (290, 40), (255, 255, 255), 5)
cv2.line(canvas, (10, 80), (290, 180), (0, 255, 255), 2, cv2.LINE_AA)
cv2.line(canvas, (10, 80), (290, 180), (0, 0, 255), 2)
cv2.imwrite("lines.png", canvas)This uses a black canvas built with np.zeros, which is a convenient way to test drawing code without a photo. The last two calls draw the same diagonal twice. The yellow one uses cv2.LINE_AA, which is anti-aliased and looks smooth. The red one uses the default cv2.LINE_8, which produces a staircase edge. Open the saved file and zoom in to see the difference.
Line types
The optional lineType argument (the sixth positional argument for line, rectangle, and circle) accepts three values:
cv2.LINE_8: 8-connected line. This is the default and the fastest.cv2.LINE_4: 4-connected line, which uses only horizontal and vertical steps and looks blockier.cv2.LINE_AA: anti-aliased. It blends edge pixels with the background for a smoother look, at a small speed cost.
Use LINE_AA for output that people will look at. Use the default when you draw thousands of shapes per frame or when you need hard, unblended pixel values, for example when drawing a mask that another step will read.
Rectangles
cv2.rectangle takes two opposite corners, usually top-left and bottom-right. It is the function you will use most, because bounding boxes from detectors are drawn with it.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
x, y, bw, bh = 100, 50, 200, 150 # a box stored as x, y, width, height
canvas = img.copy()
cv2.rectangle(canvas, (x, y), (x + bw, y + bh), (0, 255, 0), 2)
cv2.imwrite("box.jpg", canvas)Many OpenCV functions return boxes as (x, y, width, height), but cv2.rectangle wants two corners. You must compute the second corner as (x + bw, y + bh). Passing (bw, bh) directly is a common bug: the rectangle then runs from (x, y) to a point that is really a size, and it ends up in the wrong place.
Other pipelines produce (x1, y1, x2, y2) boxes, which map directly to the two arguments. Check which format your source uses before you draw.
Thickness and the border
For outline shapes, the stroke is centered on the geometric boundary. A rectangle with thickness 10 therefore extends about 5 pixels outside and 5 pixels inside the corners you gave. If you must keep the stroke entirely inside a region, shrink the corners by half the thickness.
Passing -1 fills the rectangle completely. This is how you black out a region, for instance to hide a license plate:
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
redacted = img.copy()
cv2.rectangle(redacted, (100, 50), (300, 120), (0, 0, 0), -1)
cv2.imwrite("redacted.jpg", redacted)Circles
cv2.circle takes a center (x, y) and an integer radius in pixels. There is no way to draw an ellipse with it. For ellipses, use cv2.ellipse.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
canvas = img.copy()
center = (150, 125)
cv2.circle(canvas, center, 40, (0, 0, 255), 2) # outline
cv2.circle(canvas, center, 4, (0, 0, 255), -1) # filled center dot
cv2.circle(canvas, (300, 125), 40, (255, 0, 0), -1, cv2.LINE_AA)
cv2.imwrite("circles.jpg", canvas)A small filled circle is the standard way to mark a point, such as a landmark or a clicked location. Draw it with a radius of 3 to 5 pixels so it stays visible on large images.
If your center or radius comes from a calculation, convert to integers first. Rounding is better than truncating:
cx, cy, r = 150.7, 125.2, 39.6
center = (round(cx), round(cy))
radius = round(r)Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Drawing does nothing visible | Wrong image variable, or you drew on a copy and saved the original | Save or show the same array you drew on |
| Original image has shapes in it | Drew on `img` instead of `img.copy()` | Create the canvas copy before drawing |
| `TypeError` about argument types | Float coordinates, or a list instead of a tuple | Round to `int` and pass a tuple such as `(x, y)` |
| Shape is red when you wanted blue | Color given in RGB order | Use BGR, for example `(255, 0, 0)` for blue |
| Rectangle in the wrong place | Passed `(width, height)` as the second corner | Use `(x + w, y + h)` |
| Colored shape appears gray | Drew a 3-channel color on a single-channel grayscale image | Convert with `cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)` first |
| Shape is cut off or missing | Coordinates outside the image | OpenCV clips silently, so check the coordinates against `img.shape` |
The grayscale case deserves a note. On a 2D array with shape (h, w), only the first value of the color tuple is used as the intensity. If you want to draw a green box on a grayscale image, convert it to BGR first.
import cv2
gray = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)
if gray is None:
raise FileNotFoundError("Could not read photo.jpg")
canvas = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
cv2.rectangle(canvas, (50, 50), (250, 200), (0, 255, 0), 2)
cv2.imwrite("gray_with_green_box.jpg", canvas)Exercises
Exercise
A detector returns a face box as (x, y, w, h) = (120, 80, 60, 90). Write the cv2.rectangle call that draws a red outline with thickness 2 on an image named canvas.
Show answer
cv2.rectangle(canvas, (120, 80), (120 + 60, 80 + 90), (0, 0, 255), 2). The second argument is the top-left corner, the third is the bottom-right corner (180, 170), and red in BGR order is (0, 0, 255).
Exercise
You run cv2.circle(img, (40, 60), 10, (0, 255, 0), -1) and then call cv2.imshow("a", img). Another part of your program later uses img to crop a region and gets a green dot in the crop. What went wrong, and how do you fix it?
Show answer
The drawing functions modify the array in place, so the dot was written into the original img. Create canvas = img.copy() before drawing, draw on canvas, and show or save canvas. The original stays clean for later steps.
Exercise
A gray image has shape (200, 300). You draw a rectangle with color (0, 255, 0) and it appears as a dark or black outline, not green. Why, and what do you change?
Show answer
A single-channel image only uses the first value of the color tuple, which is 0 here, so the outline is black. Convert the image to 3 channels with cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) and draw on the result.