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
