您的位置:首页 > 其它

使用face_recognition(二)目标人脸“实时”检测

2018-01-03 16:48 232 查看
使用的就是给的样例,例程的网址在这边:链接

改了里面的图片。程序比较好理解,主要有下面几个小点要注意:

OpenCV读取的图片和摄像头都是BGR格式的,因此我们在使用前需要先进行格式转换。可以使用OpenCV自带的函数,也可以使用
rgb_small_frame = small_frame[:, :, ::-1]


处理的图像大小会影响检测速度,因此官方给的例程中加速版其实就是把视频图像缩小了,我一开始还以为是什么骚操作。而且我觉得速度加快有限

下面是的我代码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time
4000
: 2018/1/3 15:52
# @Author  : He Hangjiang
# @Site    :
# @File    : 摄像头实时识别.py
# @Software: PyCharm

import face_recognition
import cv2

video_capture = cv2.VideoCapture(0)

# 本地图像
hhj_image = face_recognition.load_image_file("hhj.jpg")
hhj_face_encoding = face_recognition.face_encodings(hhj_image)[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)

# opencv的图像是BGR格式的,而我们需要是的RGB格式的,因此需要进行一个转换。
rgb_small_frame = small_frame[:, :, ::-1]

# Only process every other frame of video to save time
if process_this_frame:
# 根据encoding来判断是不是同一个人,是就输出true,不是为flase
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:
# 默认为unknown
match = face_recognition.compare_faces([hhj_face_encoding], face_encoding)
name = "Unknown"

if match[0]:
name = "hhj"

face_names.append(name)

process_this_frame = not process_this_frame

# 将捕捉到的人脸显示出来
for (top, right, bottom, left), name in zip(face_locations, face_names):
# Scale back up face locations since the frame we detected in was scaled to 1/4 size
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)

# Display
cv2.imshow('Video', frame)

# 按Q退出
if cv2.waitKey(1) & 0xFF == ord('q'):
break

video_capture.release()
cv2.destroyAllWindows()


经过自己测试,感觉速度其实并不能达到实时,大概就一秒一帧的样子(自己估计),因此显示会卡卡的,感觉效果不算特别理想。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: