Sub topic 9
Drawing conventions: coordinates, colors, thickness
This chapter covers the rules that every OpenCV drawing function shares. You will use them in the next chapters on lines, rectangles, circles, text, and polygons. I assume you can read an image with cv2.imread, know that it is a NumPy array, and know that its channels are in BGR order.
Why conventions come first
OpenCV drawing functions look simple, but they follow rules that differ from NumPy indexing. Most drawing bugs come from four sources:
- Points in
(x, y)order where array indexing uses(row, column). - Colors in BGR order, not RGB.
- Coordinates that are floats or the wrong integer type.
- Drawing directly on the original image, which changes it in place.
This chapter treats each in turn. Learning them once means you can read any drawing call and know what it does.
The coordinate system
The origin (0, 0) is the top-left pixel. The x value grows to the right. The y value grows downward. This differs from a math graph, where y grows upward.
OpenCV drawing functions take points as (x, y). NumPy indexing uses img[row, column], which is img[y, x]. The two orders are opposite, so you must convert when you move between them.
| Task | Order | Example |
|---|---|---|
| Read a pixel with NumPy | `[y, x]` | `img[50, 100]` |
| Draw a circle center | `(x, y)` | `(100, 50)` |
| Crop a region | `[y1:y2, x1:x2]` | `img[50:200, 100:300]` |
| Rectangle corners | `(x1, y1), (x2, y2)` | `(100, 50), (300, 200)` |
| Size in `cv2.resize` | `(width, height)` | `(w // 2, h // 2)` |
The pixel at img[50, 100] is the same pixel a drawing call reaches with the point (100, 50).
Valid coordinate ranges
For an image with h rows and w columns, valid pixel positions run from 0 to w - 1 for x and from 0 to h - 1 for y. Drawing functions do not raise an error for points outside this range. They clip the shape to the image. A circle centered outside the image can still draw its visible part. A shape fully outside draws nothing, and no warning tells you so. If a shape does not appear, print its coordinates and compare them with img.shape.
Integer points
Drawing functions need integer coordinates. Python int values work. A float such as 100.5 raises an error in current OpenCV versions, so convert first.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
cx, cy = 150.7, 125.2
center = (round(cx), round(cy)) # tuple of Python ints
canvas = img.copy()
cv2.circle(canvas, center, 30, (0, 0, 255), 2)Use a tuple of Python ints. NumPy integer scalars usually work. A NumPy array row such as pts[0] may fail, so call tuple(pts[0]) or tuple(int(v) for v in pts[0]) when in doubt. Values from NumPy float arrays need round or astype(int) first.
Colors
A color is a tuple with one value per channel. For a standard image from cv2.imread, the order is (blue, green, red), each from 0 to 255 for uint8 images.
| Color | BGR tuple |
|---|---|
| Blue | `(255, 0, 0)` |
| Green | `(0, 255, 0)` |
| Red | `(0, 0, 255)` |
| Yellow | `(0, 255, 255)` |
| White | `(255, 255, 255)` |
| Black | `(0, 0, 0)` |
If you write (255, 0, 0) expecting red, you get blue. The tuple always follows the image's channel order. If you converted the image to RGB with cv2.cvtColor, the same tuple would then mean red. Draw before converting, or match the tuple to the current order.
Grayscale images
A grayscale image has one channel and its array has shape (h, w). The color is then a single number, such as 255 for white. If you pass a three-value tuple to a grayscale image, OpenCV uses only the first value. The result is a shape drawn in a gray level you did not intend.
import cv2
import numpy as np
gray = np.zeros((200, 300), dtype=np.uint8)
cv2.rectangle(gray, (20, 20), (150, 100), 255, 2) # a single value for one channel
cv2.imwrite("gray_rect.png", gray)A common mistake is drawing a colored annotation on a grayscale image. The color is lost because there is only one channel. Convert first with cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR), then draw.
import cv2
gray = cv2.imread("photo.jpg", cv2.IMREAD_GRAYSCALE)
if gray is None:
raise FileNotFoundError("Could not read photo.jpg")
color_canvas = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
cv2.rectangle(color_canvas, (50, 50), (250, 200), (0, 0, 255), 2)
cv2.imwrite("gray_with_red_box.png", color_canvas)Alpha and other channel counts
A four-channel image, such as a PNG loaded with cv2.IMREAD_UNCHANGED, has BGRA order. A color tuple needs four values, and the fourth is alpha. With a three-value tuple, the alpha channel stays untouched or takes a default. Drawing functions do not blend with transparency. They write the values you give. For visible semi-transparent effects, use the overlay technique in a later chapter.
Value range and data type
For uint8 images, color values are 0 to 255. A float32 image usually holds values in the range 0.0 to 1.0, so white is (1.0, 1.0, 1.0). If you draw (255, 255, 255) on such an image, the shape is far brighter than the range and appears as pure white after clipping on display, but it will skew later math. Match the tuple to the dtype of the array.
Thickness
Most shapes take a thickness argument, measured in pixels.
- A positive value draws an outline with that width.
- The value
-1fills the shape. The constantcv2.FILLEDequals-1and reads more clearly. - A value of
0is not a good choice. Avoid it.
Thickness applies to rectangles, circles, ellipses, and polygons. For lines and polylines, the value must be positive. Text uses thickness for stroke width.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
canvas = img.copy()
cv2.rectangle(canvas, (20, 20), (120, 100), (0, 255, 0), 1) # thin outline
cv2.rectangle(canvas, (140, 20), (240, 100), (0, 255, 0), 6) # thick outline
cv2.rectangle(canvas, (260, 20), (360, 100), (0, 255, 0), cv2.FILLED) # filled
cv2.imwrite("thickness.png", canvas)A thick outline is centered on the shape's edge. Half the width falls inside and half falls outside. A rectangle from (20, 20) to (120, 100) with thickness 6 therefore extends about 3 pixels beyond those corners. This matters when you need a box to stay inside a region. Shrink the corners by half the thickness.
Rectangle corners are inclusive. Both (x1, y1) and (x2, y2) are drawn. For a full-image border you pass (0, 0) and (w - 1, h - 1). Passing (w, h) places the corner just outside the image.
Line type and anti-aliasing
Many functions accept lineType. Three values exist.
| Constant | Meaning | Use |
|---|---|---|
| `cv2.LINE_4` | 4-connected line | Fast, blocky |
| `cv2.LINE_8` | 8-connected line | Default |
| `cv2.LINE_AA` | Anti-aliased line | Smooth edges, slightly slower |
The default is cv2.LINE_8, which gives jagged diagonals. Use cv2.LINE_AA for text and for shapes shown to people. Anti-aliasing blends edge pixels with the background, so it is not suited to drawing into masks. For masks you want crisp values of exactly 0 and 255, so use the default.
The `shift` argument
Several shape functions accept a shift parameter. It treats coordinates as fixed-point numbers with shift fractional bits. With shift=4, the value 1600 means 100.0, since 1600 / 16 = 100. This gives sub-pixel placement of circles and ellipses. Most code never needs it. Know that it exists so a stray extra argument is not a mystery.
Drawing happens in place
Every drawing function modifies the array you pass in. It also returns that same array. Calling cv2.circle(img, ...) changes img even if you ignore the return value.
This has two consequences:
- The original image is damaged if you draw on it directly.
- Assigning the result, as in
out = cv2.circle(img, ...), does not create a copy.outandimgrefer to the same array.
Draw on a copy when you still need the clean image.
import cv2
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
annotated = img.copy()
cv2.circle(annotated, (150, 125), 40, (0, 0, 255), 2)
print((img == annotated).all()) # False: only the copy changedA crop made with slicing is a view into the original. Drawing on a view without copying writes into the source image. Call .copy() on the crop first when you want it independent.
Drawing also requires a writable, contiguous-compatible array. If you pass a read-only array or an oddly sliced view, OpenCV can raise a layout error. Calling np.ascontiguousarray(arr) or .copy() fixes this.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Shape is the wrong color | RGB tuple used with a BGR image | Reverse the tuple |
| Shape is missing | Coordinates outside the image, or `(row, col)` swapped | Print the points and `img.shape` |
| `TypeError` about a point | Float or array used for a point | Use `(round(x), round(y))` |
| Colored shape appears gray | Grayscale image | Convert with `COLOR_GRAY2BGR` |
| Original image is marked up | Drew without `.copy()` | Draw on `img.copy()` |
| Box extends past its region | Thickness centered on the edge | Shrink the corners by half the thickness |
Putting the conventions together
This helper draws a labeled box and applies each rule: integer points, BGR color, explicit thickness, anti-aliased text, and a copy so the input stays intact.
import cv2
def draw_box(image, x, y, w, h, label, color=(0, 255, 0), thickness=2):
out = image.copy()
x1, y1 = round(x), round(y)
x2, y2 = round(x + w), round(y + h)
cv2.rectangle(out, (x1, y1), (x2, y2), color, thickness)
cv2.putText(out, label, (x1, max(y1 - 6, 12)),
cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 1, cv2.LINE_AA)
return out
img = cv2.imread("photo.jpg")
if img is None:
raise FileNotFoundError("Could not read photo.jpg")
result = draw_box(img, 100.4, 50.2, 200, 150, "object")
cv2.imwrite("boxed.jpg", result)The label sits above the box. The max(y1 - 6, 12) keeps it on the image when the box touches the top edge.
Summary
- The origin is top-left, x grows right, y grows down.
- Drawing takes points as
(x, y). NumPy indexing takes[y, x]. - Colors follow the channel order of the array, which is BGR for
cv2.imread. - Thickness is in pixels,
-1orcv2.FILLEDfills, and outlines are centered on the edge. - Use
cv2.LINE_AAfor smooth display graphics, and the default for masks. - Drawing changes the array in place, so draw on a copy.
Exercise
An image has shape (400, 600, 3). You want a filled red circle at column 500, row 100, radius 20. Write the call, and say what happens if you swap the coordinates to (100, 500).
Show answer
Use cv2.circle(canvas, (500, 100), 20, (0, 0, 255), -1). The point is (x, y) = (column, row), and red in BGR is (0, 0, 255). If you pass (100, 500), x is 100 and y is 500. Since the image has only 400 rows, y = 500 is outside the image, and the circle (radius 20, reaching up to y = 480) is clipped away entirely. Nothing is drawn and no error is raised.
Exercise
You draw a rectangle from (50, 50) to (150, 150) with thickness 10, and need the outline to stay entirely inside that square. What corners do you pass instead?
Show answer
A thick outline is centered on the edge, so 5 pixels fall outside on each side. Shrink the corners by half the thickness: use (55, 55) and (145, 145). The outline then spans from about 50 to 150 on both axes.
Exercise
You load a photo with cv2.IMREAD_GRAYSCALE and draw a blue rectangle with color (255, 0, 0). The rectangle appears white. Why, and how do you get a blue one?
Show answer
A grayscale array has one channel, so only the first value of the tuple is used. That value is 255, which is white. Convert the image with cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR) before drawing, then (255, 0, 0) is blue.