KevsRobots Learning Platform
By Kevin McAleer, 3 Minutes

Face detection is the process of finding faces in images or video and working out where they are. (It doesn’t tell you who someone is: that’s face recognition.) In this lesson we’ll detect faces in real time with CVZone.
import cv2
from cvzone.FaceDetectionModule import FaceDetector
cap = cv2.VideoCapture(0)
detector = FaceDetector(minDetectionCon=0.5)
while True:
success, img = cap.read()
if not success:
break
img, faces = detector.findFaces(img)
if faces:
face = faces[0]
print("Centre:", face["center"], "Size:", face["bbox"][2], "x", face["bbox"][3])
cv2.imshow("Face Detection", img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
FaceDetector(minDetectionCon=0.5) loads MediaPipe’s face model. Faces it’s less than 50% sure about are ignoreddetector.findFaces(img) finds every face, draws a box and a confidence score on the image, and returns the image and a list of facesbbox - the box around the face as (x, y, width, height)center - the middle of the box as (x, y)score - how confident the model isdraw=False to findFaces() if you want the data without the drawingsfaces holds every face in the frame, so len(faces) counts peopleface["center"][0] with the middle of the image to tell whether someone is to the left or right. A robot or a pan-tilt camera could turn to follow themcap.set(cv2.CAP_PROP_FRAME_WIDTH, 640) and cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480) after opening the cameraPrint “Left”, “Right” or “Centre” depending on where the face is in the picture. The image width is img.shape[1].
Quick quiz 1 of 2
What’s the difference between face detection and face recognition?
Quick quiz 2 of 2
In CVZone, what does face["bbox"] contain?
bbox is the bounding box. center gives you its middle point.
You can use the arrows ← → on your keyboard to navigate between lessons.
Comments