import face_recognition之后直接调用face_recognition.load_image_file()读入图像,参数给文件名字符串,注意:jpg文件要和程序放在同一个文件夹下。输出图像是rgb格式(opencv中是bgr格式)。
import face_recognition
#加载图像文件
image = face_recognition.load_image_file("your_file.jpg")
Returns an array of bounding boxes of human faces in a image
Parameters:
img – An image (as a numpy array)
number_of_times_to_upsample – How many times to upsample the image looking for faces. Higher numbers find smaller faces.
model – Which face detection model to use. “hog” is less accurate but faster on CPUs. “cnn” is a more accurate deep-learning model which is GPU/CUDA accelerated (if available). The default is “hog”.
Returns:
A list of tuples of found face locations in css (top, right, bottom, left) order
加载图像文件后直接调用face_recognition.face_locations(image),能定位所有图像中识别出的人脸位置信息,返回值是列表形式,列表中每一行是一张人脸的位置信息,包括[top, right, bottom, left],也可理解为每个人脸是一个tuple存储,分别代表框住人脸的矩形中左上角和右下角的坐标(x1,y1,x2,y2)。可遍历列表打印出每张脸的位置信息,也可以通过位置信息截出识别出的人脸的图像显示出来,代码如下:
#定位所有找到的脸的位置
face_locations = face_recognition.face_locations(image)
# 循环找到的所有人脸
for face_location in face_locations:
# 打印每张脸的位置信息
top, right, bottom, left = face_location
print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
# 指定人脸的位置信息,然后显示人脸图片
face_image = image[top:bottom, left:right]
pil_image = Image.fromarray(face_image)
pil_image.show()
加载图像后,调用face_recognition.face_landmarks(image)可识别出人脸关键点信息,包括眼睛、鼻子、嘴巴和下巴等,参数仍是加载的图像image,返回值是包含面部特征字典的列表,列表中每一项对应一张人脸,包括nose_bridge、right_eyebrow、right_eye、chine、left_eyebrow、bottom_lip、nose_tip、top_lip、left_eye几个部分,每个部分包含若干个特征点(x,y),总共有68个特征点。列表长度就是图中识别出的人脸数,可遍历此列表和字典的键值对,打印出所有面部特征点,也可在图像上画出来,代码如下:
from PIL import Image, ImageDraw
face_landmarks_list = face_recognition.face_landmarks(image)
pil_image = Image.fromarray(image)
d = ImageDraw.Draw(pil_image)
for face_landmarks in face_landmarks_list:
#face_landmarks_list中每个元素都包含以下key的字典
#打印此图像中每个面部特征的位置
facial_features = [
'chin',
'left_eyebrow',
'right_eyebrow',
'nose_bridge',
'nose_tip',
'left_eye',
'right_eye',
'top_lip',
'bottom_lip'
]
for facial_feature in facial_features:
print("The {} in this face has the following points: {}".format(facial_feature, face_landmarks[facial_feature]))
#在图像中画出每个人脸特征!
for facial_feature in facial_features:
d.line(face_landmarks[facial_feature], width=5)
pil_image.show