栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

基于OpenCV的人脸检测、训练、识别

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于OpenCV的人脸检测、训练、识别

基于OpenCV的人脸检测、训练、识别

该系统利用Harr级联检测和LPBH进行人脸检测和训练、识别

import cv2
#import time

cam = cv2.VideoCapture(0)


classifier = cv2.CascadeClassifier('./cascade/haarcascade_frontalface_alt2.xml')

# For each person, enter one numeric face id
face_input_id = input('n enter user id end press  ==>  ')

while(True):

    img = cv2.flip(cam.read()[1],1)
#     img = cv2.flip(img, -1) # flip video image vertically
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = classifier.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(32, 32))
    if len(faces):
        x,y,w,h = faces[0]
        cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)  
#        if time.time()-save_time > 0.2:
#            cv2.imwrite("dataset/" + str(face_input_id) +"."+str(count)+ ".jpg", gray[y:y+h,x:x+w])
#            count += 1
#            save_time = time.time()
    
    cv2.imshow('image', img)

    if cv2.waitKey(10) == 27:   # 通过esc键退出摄像
        if len(faces):
            cv2.imwrite("dataset/" + str(face_input_id) + ".jpg", gray[y:y+h,x:x+w])
        else:
            print("截取人脸失败")
        break
#    elif count >= 50: # Take 30 face sample and stop video
#         break


cam.release()
cv2.destroyAllWindows()



import cv2
import numpy as np
from PIL import Image
import os

# Path for face image database
path = 'dataset'

recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("./cascade/haarcascade_frontalface_alt2.xml")

# function to get the images and label data
def getImagesAndLabels(path):

    imagePaths = [os.path.join(path,f) for f in os.listdir(path)]     
    faceSamples=[]
    ids = []
    if len(imagePaths):
        for imagePath in imagePaths:
            PIL_img = Image.open(imagePath).convert('L') # convert it to grayscale
            img_numpy = np.array(PIL_img,'uint8')
            face_training_id = int(os.path.split(imagePath)[-1].split(".")[0])   
            faceSamples.append(img_numpy)
            ids.append(face_training_id)

    return faceSamples,ids

print ("正在训练")
faces,ids = getImagesAndLabels(path)
if faces == [] or ids == []:
    print("None")
else:
    recognizer.train(faces, np.array(ids))
    
    # Save the model into trainer/trainer.yml
    recognizer.write('trainer/trainer.yml') # recognizer.save() worked on Mac, but not on Pi
    
    # Print the numer of faces trained and end program
    print("共"+str(len(np.unique(ids)))+"个数据")

import cv2
import time


recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "./cascade/haarcascade_frontalface_alt2.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);

font = cv2.FONT_HERSHEY_SIMPLEX

face_output_id = 0
face_1st_flag=0

# names related to ids: example ==> Marcelo: id=1,  etc
names = ['None', 'yangxu', 'zhoulaoshi', 'liuqian', 'hekun', ] 

# Initialize and start realtime video capture
cam = cv2.VideoCapture(0)

while True:

    img = cv2.flip(cam.read()[1],1)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(gray,scaleFactor=1.2,minNeighbors=5,minSize=(32, 32))
    if len(faces):
        for(x,y,w,h) in faces:
            cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
            face_output_id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
            real_confidence = int(100-confidence)
            if (real_confidence > 50):
                face_name = str(names[face_output_id])
                face_confidence = str(real_confidence)+"%"
                if face_1st_flag == 0:
                    face_1st_flag = 1
                    face_1st_id = face_output_id
                    face_1st_time = time.time()
                else:
                    if 2.1 > time.time() - face_1st_time > 2.0 :
                        if face_output_id == face_1st_id:
                            print("识别成功: "+str(face_output_id)+" "+face_name)
                        face_1st_flag = 0
                    if time.time() - face_1st_time > 2.1:
                        print("请保持稳定")
                        face_1st_flag = 0

            else:
                face_name = "Unknown"
                face_confidence = str(real_confidence)+"%"

            cv2.putText(img, str(face_name), (x+5,y-5), font, 1, (255,255,255), 2)
            cv2.putText(img, str(face_confidence), (x+5,y+h-5), font, 1, (255,255,0), 1)  

    cv2.imshow('camera',img) 

    if cv2.waitKey(10) == 27:
        break


cam.release()
cv2.destroyAllWindows()

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/949830.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号