This project calculates the distance between a face and the camera in real-time using OpenCVβs Haar Cascade face detector and focal length estimation.
- Real-time face detection via webcam ποΈβπ¨οΈ
- Calculates camera focal length using a reference image π―
- Estimates distance from camera to detected face in centimeters π
- Displays distance on live video feed π₯οΈ
- Python 3.x π
- OpenCV (
opencv-python) π§° - Webcam π·
- Reference face image (
rf.png) with known face width and distance πΌοΈ - Haar Cascade XML file (
haarcascade_frontalface_default.xmlindata/directory) π
-
Clone or download the repo. π₯
-
Install OpenCV:
pip install opencv-python- Download Haar Cascade XML from OpenCV GitHub and put it in the data/ folder. π
- Update the script with your known reference values:
Know_distance = 30 # Known distance (cm) π
Know_width_face = 14.3 # Known real face width (cm) π€- Run the script:
python your_script_name.py- Press q to quit. β
- Calculates the focal length using the known reference distance and face width. π―
- Detects faces in the webcam feed. ποΈβπ¨οΈ
- Measures the face width in pixels and estimates distance with the formula:
[ \text{Distance} = \frac{\text{Real Face Width} \times \text{Focal Length}}{\text{Face Width in Image}} ]
- Use the same camera for calibration and live detection. π·
- Adjust Haar Cascade parameters if needed for better face detection. π§
- Good lighting improves detection accuracy. π‘
Open source, free to use. π
