您的位置:首页 > 编程语言 > Python开发

python实现人脸实时监控识别程序 face_recognition

2017-12-08 21:32 1021 查看
最近在发现一个很好的人脸识别的API 接口 face_recognition可以很方便的用python实现一个实时监控人脸的程序。

先介绍一下这个API接口。这是一个可以通过python或者命令行即可实现人脸识别的功能的人脸识别的库。



安装配置,在我电脑上面安装比较容易,我直接使用了代码

pip install face_recognition


我python版本是3.6,在win10 64 位系统下使用了anaconda 安装的。

安装好了以后显示如下



这样表明你已经安装好了。

下面我们开始写相关程序

import face_recognition
import cv2
image = face_recognition.load_image_file("face2.jpg")
face_locations = face_recognition.face_locations(image)
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 = (0, 0, 255)
thickness = 2
cv2.rectangle(img, start, end, color, thickness)

cv2.namedWindow(u"识别")
cv2.imshow(u"识别", img)

cv2.waitKey(0)
cv2.destroyAllWindows()




这里就在网上随便找了一副图片,大家将就的看一下。当然这里显示我使用了opencv.大家还需要安装一下opencv.也很简单就一句代码的事。

大家也许发现了上面的中文显示出现了乱码。这里我也暂时没解决。如果有解决的大家跟我说一下。

下面就调用摄像头实时识别人脸了。

import face_recognition
import cv2

video_capture = cv2.VideoCapture(0)

obama_img = face_recognition.load_image_file("obama.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 = "Barack"
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()


这里要说明一下这里是在一开始就定义了奥巴马的图片在程序中的。然后再调用摄像头进行检测和识别的。整体看效果还不错。



当然你也可以预先把自己的照片放上去,然后就可以实时把自己识别出来了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: