opencv动态识别人脸

复制代码
import cv2
import os
import numpy as np



def take_faces():
    while True:
        key = input('请输入文件夹的名字,姓名拼音的缩写,如果输入Q,程序退出!')
        if key == 'Q':
            break
        # 在faces_dynamic下面创建子文件夹
        os.makedirs('./faces_dymamic/%s' % (key), exist_ok=True)
        take_photo(key)

def load_data():
    listdir = os.listdir('./faces_dymamic')
    #列表生成式
    names = [d for d in listdir if not d.startswith('.')]
    faces  = []
    target = [i for i in range(len(names))]*10
    for dir in names:
        for i in range(1,11):
            gray = cv2.imread('./faces_dymamic/%s/%d.jpg'% (dir,i)) #三维图片
            gray_ = gray[:, :, 0] #二维数组
            faces.append(gray_)
    faces = np.asarray(faces)
    target = np.asarray(target)
    target.sort()  # 排序
    return faces,target,names


def dynamic_recognizer_face(face_recognizer,names):
    cap = cv2.VideoCapture(0)
    #人脸检测
    face_detector = cv2.CascadeClassifier('./haarcascade_frontalface_default.xml')
    while True:
        flag,frame = cap.read()
        if not flag:
            break
        gray = cv2.cvtColor(frame, code=cv2.COLOR_BGR2GRAY)
        faces = face_detector.detectMultiScale(gray,minNeighbors=5)
        for x,y,w,h in faces:
            face = gray[y:y + h, x:x + w]
            face = cv2.resize(face, dsize=(64, 64))
            y_,confidence = face_recognizer.predict(face)
            label = names[y_]
            print('这个人是:%s.置信度:%0.1f'%(label,confidence))

            cv2.rectangle(frame,pt1=(x,y),pt2=(x+w,y+h),color=[0,0,255],thickness=2)
            cv2.putText(frame,text=label,
                        org=(x,y-10),
                        fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                        fontScale=1.5,
                        color=[0,0,255],thickness=2)
        cv2.imshow('face',frame)
        key = cv2.waitKey(1000//24)
        if key == ord('q'):
            break
    cv2.destroyAllWindows()
    cap.release()

if __name__ == '__main__':
   
    #2、加载数据,返回目标值
    faces,target,names  = load_data()
    #print(faces.shape,target.shape)
    #3、加载人脸识别算法
    #face_recognizer = cv2.face.EigenFaceRecognizer_create()
    #face_recognizer = cv2.face.FisherFaceRecognizer_create()
    face_recognizer = cv2.face.LBPHFaceRecognizer_create()
    #4、算法训练,找到目标值之间的规律
    face_recognizer.train(faces,target)
    #5、动态加载数据
    dynamic_recognizer_face(face_recognizer,names )
相关推荐
笨笨聊运维2 小时前
CentOS官方不维护版本,配置python升级方法,无损版
linux·python·centos
Gerardisite2 小时前
如何在微信个人号开发中有效管理API接口?
java·开发语言·python·微信·php
小毛驴8502 小时前
软件设计模式-装饰器模式
python·设计模式·装饰器模式
serve the people2 小时前
机器学习(ML)和人工智能(AI)技术在WAF安防中的应用
人工智能·机器学习
闲人编程3 小时前
Python的导入系统:模块查找、加载和缓存机制
java·python·缓存·加载器·codecapsule·查找器
weixin_457760003 小时前
Python 数据结构
数据结构·windows·python
0***K8923 小时前
前端机器学习
人工智能·机器学习
陈天伟教授3 小时前
基于学习的人工智能(5)机器学习基本框架
人工智能·学习·机器学习
m0_650108243 小时前
PaLM-E:具身智能的多模态语言模型新范式
论文阅读·人工智能·机器人·具身智能·多模态大语言模型·palm-e·大模型驱动