import cv2
# Load the pre-trained face detection model
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
# Initialize the video capture object
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
# Convert the frame to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Detect faces in the frame
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
# Draw rectangles around the faces
for (x, y, width, height) in faces:
cv2.rectangle(frame, (x, y), (x+width, y+height), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('Face Recognition', frame)
# Break the loop if 'q' is pressed
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release the video capture object and close all windows
video_capture.release()
cv2.destroyAllWindows()
To run this code, make sure you have the haarcascade_frontalface_default.xml file which contains the pre-trained model for face detection. You can find this XML file in the OpenCV GitHub repository or download it from the official OpenCV website.