python 实现人脸采集 训练 与人脸识别

前提:

1、安装三个需要用到的包

numpy减少运算量

 

2、有人脸识别.xml 文件,也可以网上,也可以点击下面连接下

链接:https://pan.baidu.com/s/1RpVouQUPXNK9uvodB6ELrg 
提取码:htdm 

使用:

faces = cv2.CascadeClassifier("haarcascade_frontalface_default.xml") 

直接运行可能报错显示:

cv2.error: OpenCV(4.1.0) C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect.cpp:1658: error: (-215:Assertion failed) !empty() in function 'cv::CascadeClassifier::detectMultiScale'

解决办法:在本地建 C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect这个路径放入haarcascade_frontalface_default.xml文件

以及脸保存的路径选择:cv2.imwrite("ALLFace/User."+str(face_id)+"."+str(count)+".jpg",new_img)
此处的ALLFace是文件夹在项目路径下。

 

关于路径的问题都可以用绝对路径替代(而不是在当前路径下只写ALLFace\)

 

 

 

实现

1、解析

# 人脸识别分类器      使用opencv自带的人脸分类器
faceCascade=cv2.CascadeClassifier(r'C:\python3.7\Lib\site-packages\cv2\data\haarcascade_frontalface_default.xml')
# 开启摄像头   默认笔记本的摄像头是第0号摄像头,如果有外置摄像头,并向启动就是1
cap = cv2.VideoCapture(0)
# 读取摄像头中的图像,ok为是否读取成功的判断参数
ok, img = cap.read()
# 人脸检测
    faces = faceCascade.detectMultiScale(
        gray,     
        scaleFactor=1.05,
        minNeighbors=5,     
        minSize=(32, 32)
    )
# 画矩形  
cv2.rectangle(img, (ex, ey), (ex+ew, ey+eh), (0, 255, 0), 2)
#显示视频窗口  
cv2.imshow('video', img)
#获取按键指令
k = cv2.waitKey(1)
#关闭摄像头
cap.release()
#销毁全部窗体
cv2.destroyAllWindows()
# 转为灰度图片 
 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 保存图像    
cv2.imwrite(path, src)
#打开图片,并转化为灰度
PIL_img = Image.open(imagePath).convert('L')

2、代码:

 

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

def red(date):
    faces = cv2.CascadeClassifier(r"C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect\haarcascades\haarcascade_frontalface_default.xml")
    cap=cv2.VideoCapture(0)
    face_id=input("\n enter user id: ")
    count=0
    while True:
        ret, img = cap.read()
        if ret:
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            face = faces.detectMultiScale(gray,1.05, 10,minSize=(32,32))
            for (x,y,w,h) in face:
                cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
                if h+w>=300:
                    new_img = cv2.resize(img[y:y + h, x:x + w], (92, 112))  # 调整图像大小
                    count+=1
                    cv2.imwrite("ALLFace/User."+str(face_id)+"."+str(count)+".jpg",new_img)
                    cv2.imshow('image',img)
            k=cv2.waitKey(1)
            if k==27:
                break
            if count==500:
                break
    cap.release()
    cv2.destroyAllWindows()

def getImageAndLabels(path):
    detector = cv2.CascadeClassifier(
        r"C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect\haarcascades\haarcascade_frontalface_default.xml")
    imagePaths = [os.path.join(path, f) for f in os.listdir(path)]  # join函数的作用
    faceSamples = []
    ids = []
    for imagePath in imagePaths:
        PIL_img = Image.open(imagePath).convert('L')  # convert it to grayscale
        img_numpy = np.array(PIL_img, 'uint8')
        id = int(os.path.split(imagePath)[-1].split(".")[1])
        faces = detector.detectMultiScale(img_numpy)
        for (x, y, w, h) in faces:
            faceSamples.append(img_numpy[y:y + h, x: x + w])
            ids.append(id)
    return faceSamples, ids


def train(path):
    recohnizer=cv2.face.LBPHFaceRecognizer_create()
    faces,ids=getImageAndLabels(path)
    recohnizer.train(faces,np.array(ids))
    recohnizer.write(r'E:\01STUDY\20190701\work\deathopencv\train\trainer.yml')
    print("{0} faces trained.exiting program".format(len(np.unique(ids))))

def realize():
    recohnizer = cv2.face.LBPHFaceRecognizer_create()
    recohnizer.read(r'E:\01STUDY\20190701\work\deathopencv\train\trainer.yml')
    cascadePath=(r"C:\projects\opencv-python\opencv\modules\objdetect\src\cascadedetect\haarcascades\haarcascade_frontalface_default.xml")
    facaeCascade=cv2.CascadeClassifier(cascadePath)
    font=cv2.FONT_HERSHEY_SIMPLEX
    idnum=0
    name={1:"ymz"}
    cap=cv2.VideoCapture(0)
    minW=0.1*cap.get(3)
    minH=0.1*cap.get(4)
    while True:
        ret, img = cap.read()
        if ret:
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            face = facaeCascade.detectMultiScale(gray,1.05, 10,minSize=(32,32))
            for (x,y,w,h) in face:
                cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
                idnum,confidence=recohnizer.predict(gray[y:y+h,x:x+w])
                print(idnum)
                if confidence<100 :#置信度大于50%
                    idnum=name[idnum]
                    confidence="{0}%".format(round(100-confidence))
                else:
                    idnum="unknown"
                    confidence="{0}%".format(round(100-confidence))
                cv2.putText(img,idnum,(x+5,y-5),font,1,(255,0,0),1)
                cv2.putText(img,str(confidence),(x+5,y+h-5),font,1,(0,0,0),1)
            cv2.imshow('camera',img)
            k=cv2.waitKey(10)
            if k==27:
                break
    cap.release()
    cv2.destroyAllWindows()


if __name__=='__main__':
    date2=r'E:\01STUDY\20190701\work\deathopencv\ALLface'
    #red(date2)
    #train(date2)
    realize()

python 实现人脸采集 训练 与人脸识别_第1张图片

3、有什么问题欢迎提问交流,以上代码只是进行简单的采集训练和识别

你可能感兴趣的:(Python)