Real-Time Face Detection With Python and OpenCV

by Orange Digital Center in Circuits > Raspberry Pi

10 Views, 0 Favorites, 0 Comments

Real-Time Face Detection With Python and OpenCV

CompressJPEG.Online_img(300x250) (3).jpg

This project was developed within the Orange Digital Center Morocco , a space dedicated to fostering innovation, creativity, and rapid prototyping. At the FabLab, individuals and teams have access to state-of-the-art tools, including 3D printers, laser cutters, and a variety of electronic and mechanical resources. The center provides a collaborative environment where innovators, entrepreneurs, and students can transform their ideas into tangible products. By focusing on sustainable and impactful solutions .

In this project, you’ll build a real-time face detection app using just your computer’s webcam and Python. This project runs fully offline, requires no internet, and works great on Windows, Linux, macOS, and even Raspberry Pi.

Whether you're just getting started with computer vision or want a quick demo for a class or event, this is a perfect, hands-on tutorial.

Supplies

Computer

Python

OpenCV

Terminal or Command Prompt

Install Python and OpenCV

If you don’t have Python installed, download it from python.org.

Then install OpenCV via pip:

pip install opencv-python


Create the Python Script

Create a file called face_detect.py and paste the following code into it:

import cv2

# Load the built-in face detection classifier
face_cascade = cv2.CascadeClassifier(
cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')

# Start the webcam
cap = cv2.VideoCapture(0)

print("📷 Starting camera... Press 'q' to quit.")

while True:
ret, frame = cap.read()
if not ret:
break

# Convert the frame to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

# Detect faces
faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=5)

# Draw green rectangles around faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

# Display the video frame
cv2.imshow('Real-Time Face Detection', frame)

# Exit on 'q' key
if cv2.waitKey(1) & 0xFF == ord('q'):
break

# Release the camera and close window
cap.release()
cv2.destroyAllWindows()


Run Your App

Run the script from your terminal:

python face_detect.py