如何保存人脸识别器模型?

时间:2020-05-01 05:47:04

标签: python opencv

我正在使用开放式cv进行人脸识别项目,现在我担心的是,一旦训练了我如何保存Lbph识别模型,我已经尝试过identr.write()函数,但是当我采用这种方式时我得到了一个公认的部分,那就是未定义名称,我该如何解决它,任何帮助将不胜感激。

培训部分: '''

import cv2
import os
import numPy

# preparing data
dataset_path="C:/Users/acer/PycharmProjects/Final_Project/Database"
if len(os.listdir(dataset_path))!=0:
    (images, lables, names, id) = ([], [], {}, 0)
    for (_, dirs, _) in os.walk(dataset_path):
        for subdir in dirs:
            names[id] = subdir
            subjectpath = os.path.join(dataset_path, subdir)
            for filename in os.listdir(subjectpath):
                path = subjectpath + '/' + filename
                lable = id
                images.append(cv2.imread(path, 0))
                lables.append(int(lable))
            id += 1

    # Create a Numpy array from the two lists above
    (images, lables) = [numpy.array(li) for li in [images, lables]]

    # initializing and training Local Binary Patterns Histogram model
    Face_Recognizer = cv2.face.LBPHFaceRecognizer_create()
    print("Training started....")
    Face_Recognizer.train(images, lables)
    Face_Recognizer.write("C:/Users/acer/PycharmProjects/Final_Project/Face_Recognizer.yml")
    print("Training completed")
else:
    print("oops, Dataset is not present! First create the dataset")

'''

识别部分:

'''

Face_Recognizer = cv2.face.LBPHFaceRecognizer_create()
Face_Recognizer.read("C:/Users/acer/PycharmProjects/Final_Project/Face_Recognizer.yml")
(width, height) = (300, 300)
webcam = cv2.VideoCapture(0)
fourcc=cv2.VideoWriter_fourcc(*'XVID') # this function is used to store the fourcc code
video_writer_obj=cv2.VideoWriter("E:/Pycharm/data/saved_video.avi",fourcc,20,(640,480))
while True:
    (_, im) = webcam.read()
    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x, y, w, h) in faces:
        cv2.rectangle(im, (x, y), (x + w, y + h), (255, 0, 0), 2)
        face = gray[y:y + h, x:x + w]
        face_resize = cv2.resize(face, (width, height))
        # Try to recognize the face
        prediction = Face_Recognizer.predict(face_resize)
        cv2.rectangle(im, (x, y), (x + w, y + h), (0, 255, 0), 3)

        if prediction[1] < 500:

            cv2.putText(im, '% s - %.0f' %
                        (names[prediction[0]], prediction[1]), (x - 10, y - 10),
                        cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0))
        else:
            cv2.putText(im, 'not recognized',
                        (x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN, 1, (0, 255, 0))
    video_writer_obj.write(im)
    cv2.imshow('OpenCV', im)

    key = cv2.waitKey(10)
    if key == 32:
        break
'''

请在我的代码中进行所需的更改。谢谢

0 个答案:

没有答案