人脸实时入库,实时创建分类器,实时识别人脸信息

1.实时入库

import cv2
import os
def main():
    cam = cv2.VideoCapture("1.mp4")
    cam.set(3, 640)
    cam.set(4, 480)
    face_detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
    face_id = input('输入人脸名字:')
    print("\n [INFO] Initializing face capture. Look the camera and wait ...")
    count = 0
    while(cam.isOpened()):
        print("保存成功!")
        ret, img = cam.read()
        if ret==True:
            img = cv2.flip(img, 1)
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            faces = face_detector.detectMultiScale(gray, 1.3, 5)
            cv2.imshow('image', img)

            for (x,y,w,h) in faces:
                cv2.rectangle(img, (x,y), (x+w,y+h), (255,0,0), 2)
                count += 1
                if not os.path.isdir("dataset"):
                    os.mkdir("dataset")
                cv2.imwrite("dataset/User." + str(face_id) + '.' + str(count) + ".jpg", gray[y:y+h,x:x+w])
            k = cv2.waitKey(100) & 0xff # Press 'ESC' for exiting video
            if k == 27:
                break
            elif count >= 30: # Take 30 face sample and stop video
                 break
        else:
            break
    print("\n [INFO] Exiting Program and cleanup stuff")
    cam.release()
    cv2.destroyAllWindows()
if __name__ == '__main__':
    main()

2.实时创建分类器

import cv2
import numpy as np
from PIL import Image
import os
def getImagesAndLabels(path):
    detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
    imagePaths = [os.path.join(path,f) for f in os.listdir(path)]
    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 main():
    path = 'dataset'
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    print ("\n [INFO] Training faces. It will take a few seconds. Wait ...")
    faces,ids = getImagesAndLabels(path)
    recognizer.train(faces, np.array(ids))
    if not os.path.isdir("trainer"):
        os.mkdir("trainer")
    recognizer.write('trainer/trainer.yml')
    print("\n [INFO] {0} faces trained. Exiting Program".format(len(np.unique(ids))))
if __name__ == '__main__':
    main()

3.实时识别人脸信息

import cv2
import numpy as np
import os
from PIL import Image,ImageDraw,ImageFont
def cv2AddChineseText(img, text, position, textColor=(0, 255, 0), textSize=30):
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(img)
    fontStyle = ImageFont.truetype(
        "simsun.ttc", textSize, encoding="utf-8")
    draw.text(position, text, textColor, font=fontStyle)
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)
def main():
    recognizer = cv2.face.LBPHFaceRecognizer_create()
    recognizer.read('trainer/trainer.yml')
    cascadePath = "haarcascade_frontalface_default.xml"
    faceCascade = cv2.CascadeClassifier(cascadePath)
    font = cv2.FONT_HERSHEY_SIMPLEX
    id = 0
    names = ['jack', '廖庆健', 'Paula', 'Ilza', 'Zile', 'Wafe']
    cam = cv2.VideoCapture("1.mp4")
    cam.set(3, 640)
    cam.set(4, 480)
    minW = 0.1 * cam.get(3)
    minH = 0.1 * cam.get(4)
    while (cam.isOpened()):
        ret, img = cam.read()
        if ret==True:
            img = cv2.flip(img, 1)  # Flip vertically
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            faces = faceCascade.detectMultiScale(
                gray,
                scaleFactor=1.2,
                minNeighbors=5,
                minSize=(int(minW), int(minH)),
            )
            for (x, y, w, h) in faces:
                cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)
                id, confidence = recognizer.predict(gray[y:y + h, x:x + w])
                if (confidence <=100 and confidence>=30):
                    id = names[id]
                    confidence = "{0}%".format(round(100 - confidence))
                else:
                    id = "unknown"
                    confidence = "{0}%".format(round(100 - confidence))
                print(id,type(id),confidence)

                img=cv2AddChineseText(img, id, (x , y ), (255, 0, 0), 30)
                cv2.putText(img, confidence, (x+5, y-5), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
            cv2.imshow('camera', img)
            k = cv2.waitKey(10) & 0xff
            if k == 27:
                break
        else:
            break
    print("\n [INFO] Exiting Program and cleanup stuff")
    cam.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    main()

在这里插入图片描述
在这里插入图片描述
4.缺点
识别度较低

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页