Sub topic 3
Lines, rectangles, and circles
This chapter assumes you can load an image with cv2.imread, that you know images are NumPy arrays indexed as [row, column], and that you know OpenCV stores color channels in BGR order. Each drawing function changes the array it receives, so you will draw on a copy to keep the original image intact.
Drawing lines, rectangles, and circles
All drawing functions take points as (x, y) pairs, colors as BGR tuples, and a thickness in pixels. A thickness of -1 fills the shape.
import cv2
import numpy as np
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)
pts = np.array([[100, 50], [250, 80], [220, 200], [80, 180]], dtype=np.int32)
cv2.polylines(canvas, [pts.reshape(-1, 1, 2)], isClosed=True, color=(0, 255, 255), thickness=2)
cv2.putText(canvas, "Label", (50, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2, cv2.LINE_AA)
cv2.imwrite("annotated.jpg", canvas)cv2.polylines expects a list of point arrays shaped (N, 1, 2) with int32 values. Setting isClosed=True connects the last point back to the first.
Adding text labels
cv2.putText places text with its bottom-left corner at the given (x, y) point. The font scale controls size, and cv2.LINE_AA gives smoother edges.
Drawing on a copy
Every draw call modifies its input. Calling img.copy() first keeps the loaded image unchanged, so you can draw several versions from it.
> Note: a slice such as img[50:200, 100:300] is a view, not a copy. Drawing on a view changes the original array.
Semi-transparent overlays
Draw a filled shape on a copy, then mix that copy with the original using cv2.addWeighted. The weights should add up to 1.
overlay = img.copy()
cv2.rectangle(overlay, (50, 50), (250, 200), (0, 255, 0), -1)
blended = cv2.addWeighted(overlay, 0.4, img, 0.6, 0)Exercise
Why does the overlay example call img.copy() before drawing the filled rectangle, and what would change if it drew on img directly?
Show answer
Drawing on img directly would change the original array. The blend then mixes the rectangle with an already-modified image, and the original pixels are lost. Copying first keeps img as the untouched source for addWeighted.