face_recognition+python-opencv实现摄像头实时人脸识别

参考:

https://www.jianshu.com/p/9d5f0020acd5

完整代码

csharp 复制代码
# -*- coding: utf-8 -*-

import face_recognition

import cv2

import os

camera = cv2.VideoCapture(0)

font = cv2.FONT_HERSHEY_DUPLEX

face_names = []

face_codings = []

person_list = os.listdir("faces/")

for i in range(len(person_list)):

    person_name = os.listdir("faces/" + "person_" + str(i + 1))

    # print(person_name[0])

    face_img = face_recognition.load_image_file("faces/" + "person_" + str(i + 1) + "/" + person_name[0])

    face_codings.append(face_recognition.face_encodings(face_img)[0])

    face_names.append(person_name[0][:person_name[0].index(".")])

while True:

    success,img=camera.read()

    img_new = cv2.resize(img, (0, 0), fx=0.25, fy=0.25)

    process_this_frame = True

    if process_this_frame:

        marks = face_recognition.face_locations(img_new)

        codings = face_recognition.face_encodings(img_new, marks)

        for coding in codings:

            result = face_recognition.compare_faces(face_codings, coding,0.4)

            print(result)

            for i in range(len(result)):

                if result[i]:

                    name = face_names[i]

                    break

                if i == len(result)-1:

                    name = "unknown"

                #break

        process_this_frame = not process_this_frame

        for (top, right, bottom, left)in (marks):

            top *= 4

            right *= 4

            bottom *= 4

            left *= 4

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

            cv2.putText(img, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

        cv2.imshow('face', img)

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

            break

camera.release()

cv2.destroyAllWindows()
相关推荐
喵手11 分钟前
Python爬虫实战:构建各地统计局数据发布板块的自动化索引爬虫(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集数据csv导出·采集各地统计局数据发布数据·统计局数据采集
天天爱吃肉82181 小时前
跟着创意天才周杰伦学新能源汽车研发测试!3年从工程师到领域专家的成长秘籍!
数据库·python·算法·分类·汽车
m0_715575341 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
甄心爱学习1 小时前
【leetcode】判断平衡二叉树
python·算法·leetcode
深蓝电商API1 小时前
滑块验证码破解思路与常见绕过方法
爬虫·python
Ulyanov1 小时前
Pymunk物理引擎深度解析:从入门到实战的2D物理模拟全攻略
python·游戏开发·pygame·物理引擎·pymunk
sensen_kiss1 小时前
INT303 Coursework1 爬取影视网站数据(如何爬虫网站数据)
爬虫·python·学习
玄同7652 小时前
我的 Trae Skill 实践|使用 UV 工具一键搭建 Python 项目开发环境
开发语言·人工智能·python·langchain·uv·trae·vibe coding
Yorlen_Zhang2 小时前
Python Tkinter Text 控件完全指南:从基础编辑器到富文本应用
开发语言·python·c#
HAPPY酷2 小时前
C++ 和 Python 的“容器”对决:从万金油到核武器
开发语言·c++·python