Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions traditional-face-detection-python/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# Traditional Face Detection With Python

This folder contains the sample code for the Real Python tutorial [Traditional Face Detection With Python](https://realpython.com/traditional-face-detection-python/).

## Setup

You need Python 3.12 or later. Create and activate a virtual environment, then install the dependencies:

```sh
$ python -m venv venv/
$ source venv/bin/activate
(venv) $ python -m pip install -r requirements.txt
```

Make sure you install `opencv-contrib-python` and not `opencv-python`. Starting with OpenCV 5, `CascadeClassifier` lives in the contrib `xobjdetect` module.

## Usage

Pass the path to an image that contains faces:

```sh
(venv) $ python detect_faces.py path/to/your-image.jpg
```

The script draws a green rectangle around each detected face and shows the result in a window. Press any key to close it.

On a machine without a graphical display, pass a second path to save the result to a file instead:

```sh
(venv) $ python detect_faces.py path/to/your-image.jpg detected-faces.jpg
```
50 changes: 50 additions & 0 deletions traditional-face-detection-python/detect_faces.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
"""Detect faces in an image with OpenCV's Viola-Jones classifier.

Usage:
python detect_faces.py path/to/your-image.jpg
python detect_faces.py path/to/your-image.jpg detected-faces.jpg

Pass a second path to save the result instead of opening a window,
for example on a machine without a graphical display.
"""

import sys

import cv2 as cv

if len(sys.argv) < 2:
sys.exit(__doc__)

# Read image from your local file system
original_image = cv.imread(sys.argv[1])
if original_image is None:
sys.exit(f"Couldn't read the image {sys.argv[1]!r}")

# Convert color image to grayscale for Viola-Jones
grayscale_image = cv.cvtColor(original_image, cv.COLOR_BGR2GRAY)

# Load the classifier and create a cascade object for face detection
classifier_path = cv.data.haarcascades + "haarcascade_frontalface_alt.xml"
face_cascade = cv.CascadeClassifier(classifier_path)
if face_cascade.empty():
sys.exit(f"Couldn't load the classifier from {classifier_path!r}")

detected_faces = face_cascade.detectMultiScale(grayscale_image)
print(f"Detected {len(detected_faces)} face(s)")

for column, row, width, height in detected_faces:
cv.rectangle(
original_image,
(column, row),
(column + width, row + height),
(0, 255, 0),
2,
)

if len(sys.argv) > 2:
cv.imwrite(sys.argv[2], original_image)
print(f"Saved the result to {sys.argv[2]}")
else:
cv.imshow("Image", original_image)
cv.waitKey(0)
cv.destroyAllWindows()
1 change: 1 addition & 0 deletions traditional-face-detection-python/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
opencv-contrib-python==5.1.0.95
Loading