(5-2)face_recognition人脸识别:实现基本的人脸检测

在本节的内容中将通过具体实例的实现过程详细讲解使用face_recognition实现基本人脸检测的知识

5.2.1  输出显示指定人像人脸特征

库face_recognition通过facial_features来处理面部特征,包含了如下八个特征:

  1. chin:下巴
  2. left_eyebrow左眉
  3. right_eyebrow:右
  4. nose_bridge鼻梁
  5. nose_tip:鼻子尖;
  6. left_eye左眼
  7. right_eye右眼
  8. top_lip:上唇;
  9. bottom_lip唇。

例如在下面的实例文件shibie01.py中,演示了输出显示指定人像人脸特征的过程。  

实例5-1:输出显示指定人像人脸特征

源码路径:daima\5\5-1\shibie01.py

# 自动识别人脸特征

# 导入pil模块
from PIL import Image, ImageDraw
# 导入face_recogntion模块,可用命令安装 pip install face_recognition
import face_recognition

# 将jpg文件加载到numpy 数组中
image = face_recognition.load_image_file("111.jpg")
	
#查找图像中所有面部的所有面部特征
face_landmarks_list = face_recognition.face_landmarks(image)

print("I found {} face(s) in this photograph.".format(len(face_landmarks_list)))

for face_landmarks in face_landmarks_list:

   #打印此图像中每个面部特征的位置
    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]))

   #让我们在图像中描绘出每个人脸特征!
    pil_image = Image.fromarray(image)
    d = ImageDraw.Draw(pil_image)

    for facial_feature in facial_features:
        d.line(face_landmarks[facial_feature], width=5)

    pil_image.show()

执行后会输出显示图片111.jpg中人像的人脸特征数值:

I found 1 face(s) in this photograph.
The chin in this face has the following points: [(35, 303), (38, 331), (42, 359), (47, 387), (59, 411), (78, 428), (100, 441), (123, 451), (146, 454), (168, 450), (189, 439), (209, 425), (227, 407), (238, 384), (244, 358), (249, 331), (252, 304)]
The left_eyebrow in this face has the following points: [(53, 289), (66, 273), (87, 266), (109, 269), (131, 276)]
The right_eyebrow in this face has the following points: [(162, 277), (181, 269), (203, 266), (224, 271), (236, 286)]
The nose_bridge in this face has the following points: [(144, 303), (144, 319), (144, 334), (143, 351)]
The nose_tip in this face has the following points: [(124, 364), (134, 366), (144, 368), (154, 366), (164, 364)]
The left_eye in this face has the following points: [(77, 304), (89, 299), (103, 300), (115, 310), (102, 313), (87, 311)]
The right_eye in this face has the following points: [(174, 310), (185, 301), (199, 301), (211, 305), (200, 312), (186, 313)]
The top_lip in this face has the following points: [(109, 395), (124, 391), (136, 387), (144, 389), (153, 386), (165, 390), (180, 393), (174, 393), (153, 394), (144, 395), (136, 394), (116, 396)]
The bottom_lip in this face has the following points: [(180, 393), (165, 402), (154, 405), (145, 406), (136, 406), (125, 404), (109, 395), (116, 396), (136, 396), (145, 396), (153, 395), (174, 393)]

并且会使用PIL在人像标记出人脸特征如图5-1所示

图5-1  标记出人脸特征

5.2.2  在指定照片中识别标记出人脸

下面的实例文件shibie.py中,演示了在指定照片中识别标记出人脸的过程。  

实例5-2:在指定照片中识别标记出人脸

源码路径:daima\5\5-2\shibie.py

# 检测人脸
import face_recognition
import cv2

# 读取图片并识别人脸
img = face_recognition.load_image_file("111.jpg")
face_locations = face_recognition.face_locations(img)
print(face_locations)

# 调用opencv函数显示图片
img = cv2.imread("111.jpg")
cv2.namedWindow("原图")
cv2.imshow("原图", img)

# 遍历每个人脸,并标注
faceNum = len(face_locations)
for i in range(0, faceNum):
    top =  face_locations[i][0]
    right =  face_locations[i][1]
    bottom = face_locations[i][2]
    left = face_locations[i][3]

    start = (left, top)
    end = (right, bottom)

    color = (55,255,155)
    thickness = 3
    cv2.rectangle(img, start, end, color, thickness)

# 显示识别结果
cv2.namedWindow("识别")
cv2.imshow("识别", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

执行后将分别显示原始照片111.jpg效果和识别标记处人脸的效果,如图5-2所示

图5-2  原始照片效果和标记人脸效果

5.2.3  识别出照片中的所有人脸

假设我们有一张照片888.jpg,如图5-3所示

图5-3  照片888.jpg

实例5-3识别出指定照片中的人脸

这是一幅3人合影照,我们应该如何识别出这张照片中的人脸呢?在下面的实例文件shibie02.py中,演示了提取出照片888.jpg中所有人脸的过程。  

源码路径:daima\5\5-3\shibie02.py

#  识别图片中的所有人脸并显示出来
# filename : shibie02.py
# 导入pil模块
from PIL import Image
# 导入face_recogntion模块,可用命令安装 pip install face_recognition
import face_recognition

# 将jpg文件加载到numpy 数组中
image = face_recognition.load_image_file("888.jpg")

# 使用默认的给予HOG模型查找图像中所有人脸
# 这个方法已经相当准确了,但还是不如CNN模型那么准确,因为没有使用GPU加速
# 另请参见: find_faces_in_picture_cnn.py
face_locations = face_recognition.face_locations(image)

# 使用CNN模型
# face_locations = face_recognition.face_locations(image, number_of_times_to_upsample=0, model="cnn")

# 打印:我从图片中找到了 多少 张人脸
print("I found {} face(s) in this photograph.".format(len(face_locations)))

# 循环找到的所有人脸
for face_location in face_locations:

        # 打印每张脸的位置信息
        top, right, bottom, left = face_location
        print("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()

执行后首先会输出照片888.jpg中人脸的位置信息:

I found 3 face(s) in this photograph.
Top: 163, Left: 79, Bottom: 271, Right: 187
Top: 125, Left: 182, Bottom: 254, Right: 311
Top: 329, Left: 104, Bottom: 403, Right: 179

然后输出显示识别的三个人脸,如图5-4所示  

图5-4  提取出的3个人脸

这是一幅3人合影照,我们应该如何识别出这张照片中的人脸呢?在下面的实例文件shibie02-1.py中,演示了提取出照片888.jpg中所有人脸的过程。  

实例5-4识别出多人张照片中的人脸

源码路径:daima\5\5-3\shibie02-1.py

import face_recognition
import cv2

# 读取图片并识别人脸
img = face_recognition.load_image_file("888.jpg")
face_locations = face_recognition.face_locations(img)
print(face_locations)

# 调用opencv函数显示图片
img = cv2.imread("888.jpg")
cv2.namedWindow("原图")
cv2.imshow("原图", img)

# 遍历每个人脸,并标注
faceNum = len(face_locations)
for i in range(0, faceNum):
    top = face_locations[i][0]
    right = face_locations[i][1]
    bottom = face_locations[i][2]
    left = face_locations[i][3]

    start = (left, top)
    end = (right, bottom)

    color = (55, 255, 155)
    thickness = 3
    cv2.rectangle(img, start, end, color, thickness)

# 显示识别结果
cv2.namedWindow("识别")
cv2.imshow("识别", img)

cv2.waitKey(0)
cv2.destroyAllWindows()

执行后会输出显示照片888.jpg中的所有的人脸信息,如图5-5所示

图5-5  识别出的3个人脸

5.2.4  判断在照片中是否包含某个人脸

假设我们有一张照片201.jpg,如图5-6所示

图5-6  照片201.jpg

这是一幅单人合影照,假设这个人的名字叫小毛毛。请问我们应该如何识别出在照片888.jpg中有小毛毛呢?在下面的实例文件shibie03.py中,演示了识别判断在照片888.jpg中是否包含小毛毛人脸的过程。  

实例5-5:识别判断在照片888.jpg中是否包含小毛毛人脸

源码路径:daima\5\5-4\shibie03.py

# 识别人脸鉴定是哪个人
import face_recognition
#将jpg文件加载到numpy数组中
chen_image = face_recognition.load_image_file("201.jpg")
#要识别的图片
unknown_image = face_recognition.load_image_file("888.jpg")
#获取每个图像文件中每个面部的面部编码
#由于每个图像中可能有多个面,所以返回一个编码列表。
#但是由于我知道每个图像只有一个脸,我只关心每个图像中的第一个编码,所以我取索引0。
chen_face_encoding = face_recognition.face_encodings(chen_image)[0]
print("chen_face_encoding:{}".format(chen_face_encoding))
unknown_face_encoding = face_recognition.face_encodings(unknown_image)[0]
print("unknown_face_encoding :{}".format(unknown_face_encoding))

known_faces = [
    chen_face_encoding
]
#结果是True/false的数组,未知面孔known_faces阵列中的任何人相匹配的结果
results = face_recognition.compare_faces(known_faces, unknown_face_encoding)

print("result :{}".format(results))
print("这个未知面孔是 小毛毛 吗? {}".format(results[0]))
print("这个未知面孔是 我们从未见过的新面孔吗? {}".format(not True in results))

执行后会输出如下识别结果,这说明在照片888.jpg中存在照片201.jpg的这个人。

result :[True]

这个未知面孔是 小毛毛 吗? True

这个未知面孔是 我们从未见过的新面孔吗? False

假设分别存在3张图片laoguan.jpg(老管的单人照)、maomao.jpg(毛毛的单人照)和unknown.jpg(未知某人的单人照,肯定是老管或毛毛这两人之一),如图5-7所示

图5-7  三张素材图片

5.2.5  识别出在照片中的人到底是谁

我们应该如何识别出照片unknown.jpg中的人是谁呢?在下面的实例文件shibie04.py中,演示了识别判断在照片unknown.jpg中的人到底是谁的过程。  

实例5-6:识别判断在照片unknown.jpg中的人到底是谁

源码路径:daima\5\5-5\shibie04.py

import face_recognition
jobs_image = face_recognition.load_image_file("laoguan.jpg");
obama_image = face_recognition.load_image_file("maomao.jpg");
unknown_image = face_recognition.load_image_file("unknown.jpg");

laoguan_encoding = face_recognition.face_encodings(jobs_image)[0]
maomao_encoding = face_recognition.face_encodings(obama_image)[0]
unknown_encoding = face_recognition.face_encodings(unknown_image)[0]

results = face_recognition.compare_faces([laoguan_encoding, maomao_encoding], unknown_encoding )
labels = ['老管', '毛毛']

print('结果:'+str(results))

for i in range(0, len(results)):
    if results[i] == True:
        print('这个人是:'+labels[i])

执行后会成功输出识别别结果:

结果:[False, True]

这个人是:毛毛

5.2.6  摄像头实时识别

假设我们保存一张“小毛毛”的照片xiaomaomao.jpg,然后用摄像头识别不同的照片,如果是小毛毛本人的照片,则摄像区域自动识别并显示“小毛毛”。如果摄像头不是小毛毛的照片,则在摄像区域显示“unknown”。通过下面的实例文件shibie05.py可以实现上述识别功能。  

实例5-7用摄像头识别不同的照片

源码路径:daima\5\5-6\shibie05.py

import face_recognition
import cv2

video_capture = cv2.VideoCapture(0)#笔记本摄像头是0,外接摄像头设备是1

obama_img = face_recognition.load_image_file("xiaomaomao.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_img)[0]

face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

while True:
    ret, frame = video_capture.read()

    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
    if process_this_frame:
        face_locations = face_recognition.face_locations(small_frame)
        face_encodings = face_recognition.face_encodings(small_frame, face_locations)

        face_names = []
        for face_encoding in face_encodings:
            match = face_recognition.compare_faces([obama_face_encoding], face_encoding)

            if match[0]:
                name = "小毛毛"
            else:
                name = "unknown"

            face_names.append(name)

    process_this_frame = not process_this_frame

    for (top, right, bottom, left), name in zip(face_locations, face_names):
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255),  2)

        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), 2)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left+6, bottom-6), font, 1.0, (255, 255, 255), 1)

    cv2.imshow('Video', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video_capture.release()
cv2.destroyAllWindows()

再看下面的实例文件facerec_from_webcam.py,功能是实时识别摄像头中的人脸。本实例使用库OpenCV从摄像头读取视频。首先准备两幅素材图片obama.jpg和biden.jpg然后识别摄像头中人脸。如果摄像头中的人脸是两幅素材图片obama.jpg和biden.jpg的人脸则在摄像头视频中用矩形标签注明识别结果。如果如果摄像头中的人脸不是两幅素材图片obama.jpg和biden.jpg的人脸则在摄像头视频中用矩形标签注明Unknown”。

实例5-8:实时识别摄像头中的人脸

源码路径:daima\5\5-6\facerec_from_webcam.py

import face_recognition
import cv2
import numpy as np

video_capture = cv2.VideoCapture(0)

#加载实例图片并学习如何识别它
obama_image = face_recognition.load_image_file("obama.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]

#加载第二个实例图片并学习如何识别它。
biden_image = face_recognition.load_image_file("biden.jpg")
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]

#创建已知面编码及其名称的数组
known_face_encodings = [
    obama_face_encoding,
    biden_face_encoding
]
known_face_names = [
    "Barack Obama",
    "Joe Biden"
]

while True:
    #抓取一帧视频
    ret, frame = video_capture.read()

    #将图像从BGR颜色(OpenCV使用)转换为RGB颜色(人脸识别可以使用的颜色)
    rgb_frame = frame[:, :, ::-1]

    #找到视频帧中的所有人脸和人脸编码
    face_locations = face_recognition.face_locations(rgb_frame)
    face_encodings = face_recognition.face_encodings(rgb_frame, face_locations)

    #在这一帧视频中遍历每个人脸
    for (top, right, bottom, left), face_encoding in zip(face_locations, face_encodings):
        #查看该脸是否与已知人脸匹配
        matches = face_recognition.compare_faces(known_face_encodings, face_encoding)

        name = "Unknown"

      
        #或者使用与新人脸距离最小的已知人脸
        face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
        best_match_index = np.argmin(face_distances)
        if matches[best_match_index]:
            name = known_face_names[best_match_index]

        # 在人脸上画一个方框
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        # 在人脸下方绘制一个带有名称的标签
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

    #显示结果图像
    cv2.imshow('Video', frame)

    #按下键盘中的q键将退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

#释放资源
video_capture.release()
cv2.destroyAllWindows()

执行后的效果如图5-8所示

5-8  执行效果

上述实例文件facerec_from_webcam_faster.py的效率一般比较消耗计算机内存资源。在下面的实例文件中,我们对基本的识别功能进行了如下调整,使得识别速度更加快速。

实例5-9:实时识别摄像头中的人脸高效版

(1)以1/4分辨率处理每个视频帧,仍以全分辨率显示。

(2)每隔一帧视频检测人脸。

源码路径:daima\5\5-6\facerec_from_webcam_faster.py

import face_recognition
import cv2
import numpy as np

video_capture = cv2.VideoCapture(0)
#加载实例图片并学习如何识别它
obama_image = face_recognition.load_image_file("obama.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_image)[0]

#加载第二个实例图片并学习如何识别它。
biden_image = face_recognition.load_image_file("biden.jpg")
biden_face_encoding = face_recognition.face_encodings(biden_image)[0]

#创建已知面编码及其名称的数组
known_face_encodings = [
    obama_face_encoding,
    biden_face_encoding
]
known_face_names = [
    "Barack Obama",
    "Joe Biden"
]

#初始化一些变量
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True

while True:
    #抓取一帧视频
    ret, frame = video_capture.read()
    #将视频帧调整为1/4大小以快速实现人脸识别
    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
    #将图像从BGR颜色(OpenCV使用)转换为RGB颜色(人脸识别使用)
    rgb_small_frame = small_frame[:, :, ::-1]
    #每隔一帧的处理视频以节省时间
    if process_this_frame:
        #查找当前视频帧中的所有面和面编码
        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
        face_names = []
        for face_encoding in face_encodings:
            # 查看该脸是否与已知人脸匹配
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
            name = "Unknown"
            face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
            best_match_index = np.argmin(face_distances)
            if matches[best_match_index]:
                name = known_face_names[best_match_index]
            face_names.append(name)

    process_this_frame = not process_this_frame

    #显示结果
    for (top, right, bottom, left), name in zip(face_locations, face_names):
        #缩放脸部位置,因为我们在中检测到的帧已缩放为1/4大小
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        # 在脸上画一个方框
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        #在脸部下方绘制一个带有名称的标签
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

    #显示结果图像
    cv2.imshow('Video', frame)

    #按下键盘中的q键将退出
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

video_capture.release()
cv2.destroyAllWindows()

未完待续

  • 23
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农三叔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值