一、人脸定位(OpenCV)
- 安装opencv-python :pip install opencv-python
- 需要包: 'Python路径下/Lib/site-packages/ cv2/data/haarcascade_frontalface_default.xml'
demo代码:
import cv2
def detect(filename):
face_cascade = cv2.CascadeClassifier('C:/Users/echoz/AppData/Local/Programs/Python/Python37/Lib/site-packages/cv2/data/haarcascade_frontalface_default.xml')
img = cv2.imread(filename)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.imshow('Person Detected!', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
detect('hello.jpg')
运行结果:
二、人脸定位(face_recognition)
GitHub项目:face_recognition
该项目目前star数超过3万,是GitHub上最主流的人脸识别工具包之一。 Face_recognition主要参考了OpenFace项目以及谷歌的facenet。
世界上最简洁的人脸识别库,可以使用Python和命令行工具提取、识别、操作人脸。 本项目的人脸识别是基于业内领先的C++开源库dlib中的深度学习模型,用Labeled Faces in the Wild人脸数据集进行测试,有高达99.38%的准确率。但对小孩和亚洲人脸的识别准确率尚待提升。
环境:python3.7+opencv+face_recognition
安装命令:
pip install dlib
pip install face_recognition
(若安装dlib库失败,
- pip install Cmake 安装Cmake库
- pip install boost 安装boost库
- pip install dlib )
demo代码:
import face_recognition
import cv2
image = face_recognition.load_image_file("test7.jpg")
face_locations_noCNN=face_recognition.face_locations(image)
# A list of tuples of found face locations in css (top, right, bottom, left) order
# 因为返回值的顺序是这样子的,因此在后面的for循环里面赋值要注意按这个顺序来
print("face_location_noCNN:")
print(face_locations_noCNN)
face_num2=len(face_locations_noCNN)
print(face_num2) # The number of faces
# 到这里为止,可以观察两种情况的坐标和人脸数,一般来说,坐标会不一样,但是检测出来的人脸数应该是一样的
# 也就是说face_num1 = face_num2; face_locations_useCNN 和 face_locations_noCNN 不一样
org = cv2.imread("test7.jpg")
img = cv2.imread("test7.jpg")
cv2.imshow("test7.jpg",img) # 原始图片
for i in range(0,face_num2):
top = face_locations_noCNN[i][0]
right = face_locations_noCNN[i][1]
bottom = face_locations_noCNN[i][2]
left = face_locations_noCNN[i][3]
start = (left, top)
end = (right, bottom)
color = (0,255,255)
thickness = 2
cv2.rectangle(org, start, end, color, thickness)
cv2.imshow("no cnn ",org)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果:
三、人脸特征点检测
Dlib有专门的函数和模型,能够实现人脸68个特征点的定位。找到特征点后,就可以通过图像的几何变换(仿射、旋转、缩放),使各个特征点对齐(将眼睛、嘴等部位移到相同位置)。
- 需要下载包 shape_predictor_68_face_landmarks.dat
demo代码:
#coding=utf-8
import cv2
import dlib
path = "test5.jpg"
img = cv2.imread(path)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
#人脸分类器
detector = dlib.get_frontal_face_detector()
# 获取人脸检测器
predictor = dlib.shape_predictor(r"C:\Users\echoz\AppData\Local\Programs\Python\Python37\Lib\site-packages\shape_predictor_68_face_landmarks.dat\shape_predictor_68_face_landmarks.dat")
dets = detector(gray, 1)
for face in dets:
shape = predictor(img, face) # 寻找人脸的68个标定点
# 遍历所有点,打印出其坐标,并圈出来
for pt in shape.parts():
pt_pos = (pt.x, pt.y)
cv2.circle(img, pt_pos, 2, (0, 255, 0), 1)
cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
运行结果: