再来搬运一个人脸检测的例子,是《Python机器学习经典实例》的第10章的例子,书的代码可以从https://github.com/PacktPublishing/Python-Machine-Learning-Cookbook下载,本文为第10章的例子
可以用摄像头采集人的图像然后检测出人脸。代码如下
import cv2
import numpy as np
# Load the face cascade file 按照自己的文件位置加入,如果是下载的原书的程序包那就不用改了
face_cascade = cv2.CascadeClassifier('cascade_files/haarcascade_frontalface_alt.xml')
# Check if the face cascade file has been loaded
if face_cascade.empty():
raise IOError('Unable to load the face cascade classifier xml file')
# Initialize the video capture object
cap = cv2.VideoCapture(0)
# Define the scaling factor
scaling_factor = 0.5
# Loop until you hit the Esc key
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)
# Convert to grayscale
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Run the face detector on the grayscale image
face_rects = face_cascade.detectMultiScale(gray, 1.3, 5)
# Draw rectangles on the image
for (x,y,w,h) in face_rects:
cv2.rectangle(frame, (x,y), (x+w,y+h), (0,255,0), 3)
# Display the image
cv2.imshow('Face Detector', frame)
# Check if Esc key has been pressed
c = cv2.waitKey(1)
if c == 27:
break
# Release the video capture object and close all windows
cap.release()
cv2.destroyAllWindows()
运行该例子就可以看到效果啦。