2、机器学习笔记之摄像头人脸采集与识别

 1、采集人脸数据,用于机器学习

import cv2
import os

v = cv2.VideoCapture(0)
face_detector = cv2.CascadeClassifier('./xml/haarcascade_frontalface_alt.xml')
filename = 1
dirname = './images/hlw'
writeflag = False

if not os.path.exists(dirname):
    os.mkdir(dirname)
while True:
    flag,frame = v.read()
    #摄像头出问题
    if flag == False:
        break
    gray = cv2.cvtColor(frame,code=cv2.COLOR_BGR2GRAY)
    faces = face_detector.detectMultiScale(gray)
    for x,y,w,h in faces:
        face = gray[y:y+h,x:x+w] #获取人脸
        cv2.resize(face,dsize=(64,64))
        if writeflag:
            path = os.path.join(dirname, str(filename)+'.jpg')
            cv2.imwrite(path,face)
            filename += 1
        cv2.rectangle(frame,pt1=(x,y),pt2=(x+w,y+h),color=[0,0,255],thickness=2)

    if filename > 100:
        break
    cv2.imshow("face",frame)
    key = cv2.waitKey(1000//24)
    if key == ord('q'):
        break
    if key == ord('w'):
        writeflag = True

cv2.destroyAllWindows();
v.release()

采集完的数据如下

2、机器学习笔记之摄像头人脸采集与识别_第1张图片

2、学习并保存模型

import cv2
import os
import numpy as np

def load_data():
    listdir = os.listdir('./images_dynamic')
    dirs = [d for d in listdir if not d.startswith('.')]
    faces = []
    target = []
    names = []
    for index,dir in enumerate(dirs):
        names.append(dir)
        for i in range(1,101):
            gray = cv2.imread('./images_dynamic/%s/%d.jpg'%(dir,i))
            gray_ = gray[:,:,0]
            gray_ = cv2.resize(gray_,dsize=(64,64))
            faces.append(gray_)
            target.append(index)
    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('./xml/haarcascade_frontalface_alt.xml')
    while True:
        flag, frame = cap.read()
        # 摄像头出问题
        if flag == False:
            break
        gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
        faces = face_detector.detectMultiScale(gray,minNeighbors=10)
        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,label,org=(x,y-10),fontFace=cv2.FONT_HERSHEY_SIMPLEX,color=[0,0,255],thickness=2,fontScale=1.5)
        cv2.imshow("face", frame)
        key = cv2.waitKey(1000//24)
        if key == ord('q'):
            break
    cap.release();
def dynamic_recognizer_face2(face_recognizer,names):
    gray = cv2.imread('./images_dynamic/%s/%d.jpg' % ('hlw', 2))
    gray_ = gray[:, :, 0]
    gray_ = cv2.resize(gray_, dsize=(64, 64))
    y_, confidence = face_recognizer.predict(gray_)
    print(names[y_])

if __name__ == '__main__':
    #1、加载数据
    faces,target,names = load_data()
    # print(faces.shape,len(target))
    print(faces,target)
    #2、加载算法
    face_recognizer = cv2.face.EigenFaceRecognizer_create()
    #face_recognizer = cv2.face.FisherFaceRecognizer_create()
    #face_recognizer = cv2.face.LBPHFaceRecognizer_create()
    # print(face_recognizer)
    # 3 训练
    face_recognizer.train(faces, target)
    # 保存训练数据
    face_recognizer.write('./model/demo.pt')
    # 预测
    dynamic_recognizer_face(face_recognizer,names)

3、使用模型

将main方法改成如下代码:

if __name__ == '__main__':
    names = ['hanlw','tly']
    #2、加载算法
    # face_recognizer = cv2.face.EigenFaceRecognizer_create()
    # face_recognizer = cv2.face.FisherFaceRecognizer_create()
    face_recognizer = cv2.face.LBPHFaceRecognizer_create()
    # 3 加载训练模型
    face_recognizer.read('./model/demo.pt')
    # 预测
    dynamic_recognizer_face(face_recognizer,names)

效果如下:

2、机器学习笔记之摄像头人脸采集与识别_第2张图片

你可能感兴趣的:(python_pytorch,python,opencv)