Face Detection With OpenCV on Raspberry Pi 3,4,5

parmarjatin4911@gmail.com - Jan 11 - - Dev Community

In this tutorial, we will explore how to perform face detection using OpenCV on a Raspberry Pi 3,4,5 with a webcam. Face detection is a computer vision task that involves identifying and locating human faces in images or video. OpenCV, a popular computer vision library, provides powerful tools for face detection.

Prerequisites

Before we begin, make sure you have the following:

  • Raspberry Pi 4

  • Webcam connected to the Raspberry Pi 4

  • Power supply (official Raspberry Pi power supply is preferable)

Download the haarcascade_frontalface_default.xml:

Visit the haarcascade xml file and download the haarcascade frontalface and put same folder

Implementation

Now, let's dive into the implementation. We'll use Python and OpenCV to capture video from the webcam and apply face detection. Below is a simple Python script for face detection:

CODE:

import cv2
import sys

cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)

video_capture = cv2.VideoCapture(0)
video_capture.set(3, width)
video_capture.set(4, height)

while True:

Capture frame-by-frame

ret, frame = video_capture.read()

gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)

Draw a rectangle around the faces

for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)

Display the resulting frame

cv2.imshow('Video', frame)

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

When everything is done, release the capture

video_capture.release()
cv2.destroyAllWindows()

Save the above script as a Python file (e.g., face_detection.py) and run it on your Raspberry Pi. The script captures video from the webcam, performs face detection, and displays the live feed with rectangles around detected faces. Press 'q' to exit the application.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player