Face Detection Code - Easy Explanation (Grade 8 Level)
import cv2
- Loads the OpenCV library, which helps us work with images and videos.
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades +
'haarcascade_frontalface_default.xml')
- Loads a face detection model that knows how faces usually look.
cap = cv2.VideoCapture(0)
- Turns on your computer's camera.
while True:
- Start a loop that repeats the next steps forever.
ret, frame = cap.read()
- Takes a picture (frame) from the camera.
if not ret:
break
- If the picture was not taken correctly, stop the loop.
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
- Converts the picture to black and white (grayscale).
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5,
minSize=(30, 30))
- Looks for faces in the grayscale image using the face detection model.
for (x, y, w, h) in faces:
- For each face found, get its position and size.
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
- Draws a blue rectangle around each detected face.
cv2.imshow("Face Detection", frame)
- Shows the image with rectangles in a window.
if cv2.waitKey(1) & 0xFF == ord('q'):
break
- If you press the 'q' key, the loop will stop.
cap.release()
- Turns off the camera.
cv2.destroyAllWindows()
- Closes the camera window.