Jupyter Snippet CB2nd 05_faces
Jupyter Snippet CB2nd 05_faces
11.5. Detecting faces in an image with OpenCV
import io
import zipfile
import requests
import numpy as np
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
url = ('https://github.com/ipython-books/'
'cookbook-2nd-data/blob/master/'
'family.zip?raw=true')
r = io.BytesIO(requests.get(url).content)
zipfile.ZipFile(r).extractall('data')
img = cv2.imread('data/family.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
path = 'data/haarcascade_frontalface_default.xml'
face_cascade = cv2.CascadeClassifier(path)
for x, y, w, h in face_cascade.detectMultiScale(
gray, 1.3):
cv2.rectangle(
gray, (x, y), (x + w, y + h), (255, 0, 0), 2)
fig, ax = plt.subplots(1, 1, figsize=(8, 6))
ax.imshow(gray, cmap=plt.cm.gray)
ax.set_axis_off()