基于自带haarcascade识别(效果一般)
# 基于harrcascade识别,需要下载人脸特征数据
# 基于Haar特征的cascade分类器(classifiers) 是Paul Viola和 Michael Jone在2001年,论文”Rapid Object Detection using a Boosted Cascade of Simple Features”中提出的一种有效的物品检测(object detect)方法。它是一种机器学习方法,通过许多正负样例中训练得到cascade方程,然后将其应用于其他图片
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to input image")
args = vars(ap.parse_args())
# 读取输入数据,预处理
image = cv2.imread(args["image"])
(h, w) = image.shape[:2]
width = 1024
r = width / float(w)
dim = (width, int(h * r))
image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 人脸检测,识别出来,如果有n张脸,就有n个对象,这里必须用完整路径,切实cv2安装目录的
detector = cv2.CascadeClassifier("E:\Program Files\python37\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml")
detector.load('E:\Program Files\python37\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
faces = detector.detectMultiScale(gray)
# 遍历每张脸,并画出方框
for (x,y,w,h) in faces:
cv2.rectangle(image, (x,y), (x+w, y+h), (0,0,255), 2)
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
基于dlib(效果很好,推荐,可识别五官)
# 导入工具包
import numpy as np
import argparse
import cv2
import dlib
# 基于dlib识别,底层采用深度学习,效果比基于Haar特征的cascade分类器好,推荐
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--image", required=True, help="path to input image")
args = vars(ap.parse_args())
# 读取输入数据,预处理
image = cv2.imread(args["image"])
(h, w) = image.shape[:2]
width = 1024
r = width / float(w)
dim = (width, int(h * r))
image = cv2.resize(image, dim, interpolation=cv2.INTER_AREA)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# 人脸检测,采用dlib
detector = dlib.get_frontal_face_detector()
faces = detector(gray, 1)
# 遍历每张脸,并画出方框
for (k, d) in enumerate(faces): #d返回的是一个位置对象
print(type(d))
print(d)
image = cv2.rectangle(image, (d.left(), d.top()), (d.right(), d.bottom()), (0,0,255), 2)
cv2.imshow('image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
如果是获取摄像头的可以修改代码:
cameraCapture = cv2.VideoCapture(0)
success, frame = cameraCapture.read()
detector = dlib.get_frontal_face_detector()
while success and cv2.waitKey(1) == -1: