其他分享
首页 > 其他分享> > [人脸识别]10-通过摄像头进行人脸识别

[人脸识别]10-通过摄像头进行人脸识别

作者:互联网

1程序代码

import cv2 as cv
import numpy as np
import os
# coding=utf-8


#加载训练数据集文件
recogizer=cv.face.LBPHFaceRecognizer_create()
recogizer.read('trainer/trainer.yml')
names=[]
warningtime = 0


def warning():
    print("非法人员靠近摄像头")

#准备识别的图片
def face_detect_fun(img):
    gray=cv.cvtColor(img,cv.COLOR_BGR2GRAY)#转换为灰度
    face_detector=cv.CascadeClassifier(cv.data.haarcascades+"haarcascade_frontalface_alt2.xml")
    face=face_detector.detectMultiScale(gray)
    for x,y,w,h in face:
        cv.rectangle(img,(x,y),(x+w,y+h),color=(0,0,255),thickness=2)
        cv.circle(img,center=(x+w//2,y+h//2),radius=w//2,color=(0,255,0),thickness=1)
        # 人脸识别
        ids, confidence = recogizer.predict(gray[y:y + h, x:x + w])
        print('标签id:',ids,'置信评分:', confidence)
        if confidence > 80:
            global warningtime
            warningtime += 1
            if warningtime > 100:
               warning()
               warningtime = 0
            cv.putText(img, 'unkonw', (x + 10, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
        else:
            cv.putText(img,str(names[ids-1]), (x + 10, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.75, (0, 255, 0), 1)
    cv.imshow('result',img)
    #print('bug:',ids)

def get_name():
    path = './jm/'
    imagePaths=[os.path.join(path,f) for f in os.listdir(path)]
    for imagePath in imagePaths:
       name = str(os.path.split(imagePath)[1].split('.',2)[1])
       names.append(name)


cap=cv.VideoCapture(0)
get_name()
while True:
    flag,frame=cap.read()
    if not flag:
        break
    face_detect_fun(frame)
    if ord('q') == cv.waitKey(10):
        break
cv.destroyAllWindows()
cap.release()

2.识别效果

 

 

 

标签:10,人脸识别,img,face,warningtime,path,cv,摄像头
来源: https://www.cnblogs.com/cqmcu/p/16122440.html