`detectMultiScale` runs a loaded OpenCV cascade classifier on a prepared image and returns matching object rectangles. For face detection, prepare the camera image by converting it to grayscale and equalizing its histogram, then call the method on that cleaned image. section 9.3.1
Each returned face rectangle contains `x, y, w, h`: the top-left position plus width and height. When at least one match exists, unpack the first rectangle, calculate its center, and use the coordinates to draw a box and center marker on the original frame. section 9.3.1 section 9.3.2
Detect and mark a face
A reusable `detect_face(frame)` function prepares `frame`, calls `face_classifier.detectMultiScale(clean)`, and, for the first result, draws `cv2.rectangle` and `cv2.drawMarker` before returning the face center. The calling code can print that center and display the annotated image. section 9.3.2
For faster repeated detection, shrink the prepared image before calling `detectMultiScale`. Convert the returned `x, y, w, h` values back to full-resolution coordinates by dividing each one by the detection scale, so annotations still align with the original frame. section 9.4.3
Listing 9.3 face.py: Providing a fast face detection library
import cv2
BLUE = (255, 0, 0)
CV2_DIR = cv2.__path__[0]
CLASSIFIER_PATH = f'{CV2_DIR}/data/haarcascade_frontalface_default.xml'
face_classifier = cv2.CascadeClassifier(CLASSIFIER_PATH)
DETECT_SCALE = 0.2
def resize(img, scale):
size = (int(img.shape[1] * scale), int(img.shape[0] * scale))
return cv2.resize(img, size, interpolation=cv2.INTER_AREA)
def get_center(x, y, w, h):
return int(x + (w / 2)), int(y + (h / 2))
def prep_face(frame):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
return cv2.equalizeHist(gray)
def detect_face(frame):
clean = prep_face(frame)
small = resize(clean, DETECT_SCALE)
faces = face_classifier.detectMultiScale(small)
if len(faces) > 0:
x, y, w, h = [int(i / DETECT_SCALE) for i in 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
This reusable face-detection library combines preprocessing, downscaling, `detectMultiScale`, coordinate remapping, and face-center marking. section 9.4.3
