Sub topic 9
Drawing Conventions: Coordinates, Colors, and Thickness
This chapter assumes basic Python, NumPy array indexing, and OpenCV installation. You should also know that an image has a width, a height, and color channels.
OpenCV drawing functions modify the image array in place. They use image points as (x, y) coordinates:
xis the horizontal position, measured from the left.yis the vertical position, measured from the top.(0, 0)is the top-left corner.- Larger
xvalues move right. - Larger
yvalues move down.
This differs from NumPy indexing. To access a pixel, NumPy uses image[y, x], with the row first and the column second. OpenCV drawing functions use (x, y) in function arguments.
Colors use BGR order
OpenCV normally stores color channels as blue, green, and red, or BGR. A color is therefore written as (blue, green, red).
| Desired color | OpenCV tuple |
|---|---|
| Blue | `(255, 0, 0)` |
| Green | `(0, 255, 0)` |
| Red | `(0, 0, 255)` |
| White | `(255, 255, 255)` |
Each channel usually ranges from 0 to 255 for an 8-bit image. A value of 0 means no intensity for that channel. A value of 255 means full intensity.
Lines, rectangles, and circles
Drawing functions receive a color tuple and a thickness in pixels. A positive thickness draws an outline. The special thickness -1 fills a closed shape such as a rectangle or circle.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
height, width = img.shape[:2]
canvas = img.copy()
# A blue diagonal line, three pixels wide
cv2.line(canvas, (0, 0), (width - 1, height - 1), (255, 0, 0), 3)
# A green rectangle outline
cv2.rectangle(canvas, (50, 50), (250, 200), (0, 255, 0), 2)
# A filled red circle
cv2.circle(canvas, (150, 125), 40, (0, 0, 255), -1)
cv2.imwrite("annotated.jpg", canvas)The rectangle points describe opposite corners: the top-left corner and the bottom-right corner. The circle requires a center point and a radius. All these points use (x, y), not (row, column).
Avoid changing the original accidentally
Because drawing happens in place, assigning canvas = img does not create an independent image. Both names refer to the same array. Use img.copy() when you want to preserve the original.
A thickness larger than the object can cover nearby details. Choose it relative to the image size. A thickness of 2 or 3 pixels works for many medium-sized images, while a small thumbnail may need thickness 1.
Check your coordinate assumptions
When an annotation appears in the wrong location, inspect whether you mixed up (x, y) with image[y, x], or used RGB color values as if they were BGR. These two conventions cause many OpenCV drawing bugs.
Exercise
What color does OpenCV draw for the tuple (255, 0, 0), and where is the point (20, 30)?
Show answer
The tuple produces blue because OpenCV uses BGR order. The point is 20 pixels from the left and 30 pixels from the top.