cv3.draw.rectangle

cv3.draw.rectangle(img, x0, y0, x1, y1, mode='xyxy', rel=None, color=None, t=None, line_type=None, fill=None, copy=False)[source]

Draw a rectangle on an image.

Parameters:
  • img (numpy.ndarray) – Input image to draw on.

  • x0 (int or float) – X-coordinate of the first point.

  • y0 (int or float) – Y-coordinate of the first point.

  • x1 (int or float) – X-coordinate of the second point.

  • y1 (int or float) – Y-coordinate of the second point.

  • mode (str, optional) – Coordinate mode. One of ‘xyxy’, ‘xywh’, ‘ccwh’. Defaults to ‘xyxy’.

  • rel (bool, optional) – Whether to use relative coordinates. Defaults to None.

  • color – Color of the rectangle (default: opt.COLOR).

  • t – Thickness of the rectangle lines (default: opt.THICKNESS).

  • line_type – Type of line for drawing (default: opt.LINE_TYPE).

  • fill (bool, optional) – Whether to fill the rectangle. If True, draws a filled rectangle regardless of thickness. If False, draws an outlined rectangle. If None, uses the thickness parameter to determine fill behavior. Defaults to None.

  • copy (bool) – Whether to copy the image before drawing (default: False).

Returns:

Image with the rectangle drawn on it.

Return type:

numpy.ndarray

Note

The coordinate modes are: - ‘xyxy’: Two corner points (x0, y0) and (x1, y1) - ‘xywh’: Top-left corner (x0, y0) and width (x1), height (y1) - ‘ccwh’: Center point (x0, y0) and width (x1), height (y1)

Relative coordinates are in the range [0, 1] where 0 is the top/left and 1 is the bottom/right of the image.

When fill=True, the rectangle is filled regardless of the thickness value. When fill=False, the rectangle is outlined with the specified thickness. When fill=None (default), the rectangle is filled if t=-1, otherwise outlined.

Example

>>> import cv3
>>> img = cv3.zeros(100, 100, 3)
>>> # Draw a rectangle using absolute coordinates
>>> img = cv3.rectangle(img, 10, 10, 90, 90, color='red', t=2)
>>> # Draw a filled rectangle
>>> img = cv3.rectangle(img, 20, 20, 80, 80, color='blue', fill=True)
>>> # Draw a rectangle using relative coordinates
>>> img = cv3.rectangle(img, 0.2, 0.2, 0.8, 0.8, rel=True, color='green')
>>> # Draw a rectangle using xywh mode
>>> img = cv3.rectangle(img, 10, 10, 80, 80, mode='xywh', color='yellow')