Providing face detection code
The user wants a straightforward Python code for real-time face detection using OpenCV. I won't provide lengthy explanations, just the code. They need to have OpenCV installed with video support. I'll go with Haar cascades for simplicity. The code will include importing cv2, loading the cascade, setting up VideoCapture(0), the processing loop, grayscale conversion, detectMultiScale, drawing rectangles, imshow, breaking on 'q', and cleaning up at the end. I'll also briefly mention installing OpenCV with pip install opencv-python.Drafting face detection code
Here's the Python code for real-time face detection using OpenCV:
import cv2
def main():
face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')
if face_cascade.empty():
print("Error loading cascade")
return
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Cannot open camera")
return
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5, minSize=(30, 30))
for (x,y,w,h) in faces:
cv2.rectangle(frame, (x,y), (x+w, y+h), (0,255,0), 2)
cv2.imshow('Real-time Face Detection', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
main()
I might consider adding error messages or tailored settings for different systems, but this should be a solid starting point! ```python
"""
Real-time face detection using OpenCV and Haar cascades.
Press 'q' to quit the video window.
"""
import cv2
def main():
# Load the pre-trained Haar Cascade for frontal face detection
face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
)
if face_cascade.empty():
print("Error: Could not load face cascade.")
return
# Open the default camera (0). Change the index if you have multiple cameras.
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Error: Could not open camera.")
return
while True:
ret, frame = cap.read()
if not ret:
print("Error: Failed to grab frame.")
break
# Convert the frame to grayscale (Haar cascades work on grayscale images)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Detect faces in the image
faces = face_cascade.detectMultiScale(
gray,
scaleFactor=1.3, # How much the image size is reduced at each image scale
minNeighbors=5, # How many neighbors each candidate rectangle should have to retain it
minSize=(30, 30) # Minimum possible face size
)
# Draw rectangles around detected faces
for (x, y, w, h) in faces:
cv2.rectangle(
frame,
(x, y),
(x + w, y + h),
(0, 255, 0), # Green rectangle
2 # Thickness
)
# Display the resulting frame
cv2.imshow("Real-time Face Detection", frame)
# Exit on 'q' key
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release resources
cap.release()
cv2.destroyAllWindows()
if name == "main":
main()
To run this, make sure you have OpenCV installed:
```bash
pip install opencv-python
Then save the script (e.g., face_detection.py) and run:
python face_detection.py