欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

利用face_recognition,dlib与OpenCV调用摄像头进行人脸识别

程序员文章站 2023-03-26 15:30:27
用已经搭建好 face_recognition,dlib 环境来进行人脸识别 未搭建好环境请参考:https://www.cnblogs.com/guihua-pingting/p/12201077.html 使用OpenCV 调用摄像头 import face_recognition import ......

用已经搭建好 face_recognition,dlib 环境来进行人脸识别

未搭建好环境请参考:

使用opencv 调用摄像头

import face_recognition
import cv2

video_capture = cv2.videocapture(0)
# videocapture打开摄像头,0为笔记本内置摄像头,1为外usb摄像头,或写入视频路径
mayun_img = face_recognition.load_image_file("mayun.jpg")
jobs_img = face_recognition.load_image_file("jobs.jpg")

mayun_face_encoding = face_recognition.face_encodings(mayun_img)[0]
jobs_face_encoding = face_recognition.face_encodings(jobs_img)[0]


face_locations = []
face_encodings = []
face_names = []
process_this_frame = true

while true:
    ret, frame = video_capture.read()
    #  video_capture.read()按帧读取视频,ret,frame是获video_capture.read()方法的两个返回值。
    #  其中ret是布尔值,如果读取帧是正确的则返回true,
    #  如果文件读取到结尾,它的返回值就为false。frame就是每一帧的图像,是个三维矩阵。

    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([mayun_face_encoding, jobs_face_encoding], face_encoding)

            if match[0]:
                name = "mayun"
            elif match[1]:
                name = "jobs"
            else:
                name = "unknown"
            print(name)

            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()

我使用手机中的照片来进行验证

利用face_recognition,dlib与OpenCV调用摄像头进行人脸识别

 

因为是按每一帧进行读取:

 利用face_recognition,dlib与OpenCV调用摄像头进行人脸识别

 

 有些人在使用时会出现摄像头打不开的情况

我使用的是win10系统给出一个建议:

在设置中找到隐私设置,在找到相机选项,把权限打开即可

利用face_recognition,dlib与OpenCV调用摄像头进行人脸识别