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

最近在发现一个很好的人脸识别的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()

这里要说明一下这里是在一开始就定义了奥巴马的图片在程序中的。然后再调用摄像头进行检测和识别的。整体看效果还不错。
这里写图片描述
当然你也可以预先把自己的照片放上去,然后就可以实时把自己识别出来了。

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值