import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier(‘cascade_files/haarcascade_frontalface_alt.xml’)
if face_cascade.empty():
raise IOError(‘Unable to load the face cascade classifier xml file’)
cap = cv2.VideoCapture(0)
scaling_factor = 0.5
while True:
# Capture the current frame and resize it
ret, frame = cap.read()
frame = cv2.resize(frame, None, fx=scaling_factor, fy=scaling_factor,
interpolation=cv2.INTER_AREA)
# 图像转化为灰度图像
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# 灰度图像上运行人脸检测器
face_rects = face_cascade.detectMultiScale(gray, 1.3, 5)
# 在脸部画矩形框
for (x,y,w,h) in face_rects:
cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 3)
# 展示输出的图像
cv2.imshow('Face Detector', frame)
# 检测是否按下ESC键
c = cv2.waitKey(1)
if c == 27:
break