liveBook · Manning

Rectangle function

As explained in Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi

The OpenCV rectangle function draws a rectangular outline or filled rectangle on an image.

The OpenCV rectangle function draws a rectangular box directly onto an image. Supply two opposite corner coordinates and a color; the resulting image can then be displayed or processed further. section 8.3.2

Use the function with the same image and BGR color conventions as other OpenCV drawing calls:

  • Pass the destination image as the first argument. section 8.3.2
  • Specify opposite corners with pt1 and pt2; (50, 250) and (350, 350) produce a box 300 pixels wide and 100 pixels high. section 8.3.2
  • Provide a BGR color, not RGB; BLUE is represented as (255, 0, 0). section 8.3.2
  • In face detection, add a thickness value such as 2 to outline the detected region. section 9.3.2

Draw a rectangle on a preview image

import numpy as np import cv2 BLUE = (255, 0, 0) img = np.zeros(shape=(480, 640, 3), dtype=np.uint8) cv2.rectangle(img, (50, 250), (350, 350), BLUE) cv2.imshow('preview', img) cv2.waitKey() section 8.3.2

Mark a detected face

x, y, w, h = faces[0] center = get_center(x, y, w, h) cv2.rectangle(frame, (x, y), (x + w, y + h), BLUE, 2) cv2.drawMarker(frame, center, BLUE) return center section 9.3.2

cv2.rectangle(img, pt1=(50, 250), pt2=(350, 350), color=BLUE)

Inspect the minimal OpenCV call that draws a blue rectangle between two image coordinates. section 8.3.2

def detect_face(frame):
    clean = prep_face(frame)
    faces = face_classifier.detectMultiScale(clean)
    if len(faces) > 0:
        x, y, w, h = faces[0]
        center = get_center(x, y, w, h)
        cv2.rectangle(frame, (x, y), (x + w, y + h), BLUE, 2)
        cv2.drawMarker(frame, center, BLUE)
        return center

Inspect the reusable face-detection function that calculates a face center, draws its rectangle, and returns the coordinates. section 9.3.2

How Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi covers it

How deep it goes
Explains image arguments, corner coordinates, BGR colors, and face-box thickness, without descending into OpenCV internals.
Examples
Demonstrates a blue box on a black image and a blue rectangle with a center marker around a detected face.
What it assumes
Uses NumPy image arrays and OpenCV image-display calls as the immediate setup for drawing.
What you can do after
Apply it via OpenCV to annotate synthetic images or mark detected faces with reusable Python functions.
How it connects
Connects OpenCV drawing, NumPy image arrays, BGR color encoding, face detection, and image display.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Build Your Own Robot: Using Python, CRICKIT, and Raspberry Pi. The section links point to the parts of the book it draws on.