This project implements real-time face and eye detection using OpenCV and Haar Cascade classifiers. The program captures video from a webcam and detects faces and eyes using pre-trained Haar cascade XML files.
- Real-time face detection using
haarcascade_frontalface_default.xml - Real-time eye detection using
haarcascade_eye.xml - Uses OpenCV for image processing
- Adjustable detection parameters
Ensure you have the following installed:
- Python (>=3.7)
- OpenCV library (
opencv-python) - Haar Cascade XML files for face and eye detection
Run the following command to install OpenCV:
pip install opencv-pythonUse SSH (if set up):
git clone git@github.com:NurulBashar/RealTimeFaceDetectionUsingHaarCascade.gitOr use HTTPS:
git clone https://github.com/NurulBashar/RealTimeFaceDetectionUsingHaarCascade.gitDownload the required Haar cascade XML files and place them in your project directory:
Run the script using:
python main.py- The webcam will open and start detecting faces and eyes.
- Press 'q' to exit the program.
- Capture Video from Webcam:
cap = cv2.VideoCapture(0) cap.set(4, 640) # Set width cap.set(4, 480) # Set height
- Load Haar Cascade Files:
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") eye_cascade = cv2.CascadeClassifier("haarcascade_eye.xml")
- Face & Eye Detection in Real-Time:
faces = face_cascade.detectMultiScale(img_gray, 1.3, 2) for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
- Display Output:
cv2.imshow("Face and Eye Detection", img)
The script will detect faces and eyes and highlight them using rectangles:
- Face: Red rectangle 🟥
- Eyes: Green rectangle 🟩
-
Error: Face cascade file not loaded!
- Ensure the
haarcascade_frontalface_default.xmlfile is in the correct directory.
- Ensure the
-
No face detected?
- Adjust
detectMultiScale()parameters:scaleFactorandminNeighbors.
- Adjust
-
Webcam not working?
- Change
cv2.VideoCapture(0)tocv2.VideoCapture(1)if multiple cameras exist.
- Change
This project is open-source and released under the MIT License.
- OpenCV: https://opencv.org
- Haar Cascade Classifiers: OpenCV GitHub
Nurul Bashar