Use opencv to do a simple face recognition

172 Views
No Comments

共计 5424 个字符,预计需要花费 14 分钟才能阅读完成。

Use opencv to do a simple face recognition

summary

  • how to develop face recognition by opencv ,let's go
    origin code github click it
    voideo Bilibili click to video

Use opencv to do a simple face recognition

  • add_panel
    Use opencv to do a simple face recognition

install

  • opencv and opencv-contrib-python
    • Solution for installation failure
pip uninstall opencv-python
pip uninstall opencv-contrib-python

pip install opencv-python
pip install opencv-contrib-python

tips: you should restart after installed

realize

  • Face recognition first
  • Obtain the face feature picture and save the grayscale image
  • Conduct face model training
  • Test run

Face recognition

  • opencv's face recognition framework is used
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
  • Capture 800 frames of face pictures and save data pictures
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
VIDEO_PATH = 'video/hero2.mp4'
face_id = 2
#sampleNum用来计数样本数目
count = 0
SAVE_PATH = 'data/'

cap = cv.VideoCapture(VIDEO_PATH)
count = 0
while cap.isOpened():
    ret, img = cap.read()
    if ret is not None:
        if img is None:
            continue
        img = imutils.resize(img, width=600)
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        face = face_cascade.detectMultiScale(gray, 1.3, 5)
        for (x, y, w, h) in face:
            cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0))
            count += 1
            if not os.path.exists(SAVE_PATH + 'user.' + str(face_id)):
                os.mkdir(SAVE_PATH + 'user.' + str(face_id))
            cv.imwrite(SAVE_PATH + 'user.' + str(face_id) + "/count_" + str(count) + ".jpg", gray[y: y + h, x: x + w])
        if count >= 800:
            break   
        cv.imshow('h', img)
        key = cv.waitKey(1)
        if key == 27:
            break
    else:
        break
cap.release()
cv.destroyAllWindows()

Use opencv to do a simple face recognition
Use opencv to do a simple face recognition

Test with a treasure up the Lord's face test. Excuse me, you want fire

Conduct face model training

  • run the opencv of face mok
  • recog = cv.face.LBPHFaceRecognizer_create()

import time

recog = cv.face.LBPHFaceRecognizer_create()
recog.read('trainner/face.yaml')

time_start = time.process_time()
def get_imgs_labels():
    face_id = 0
    face_arr = []
    face_ids = []
    for user_id in os.listdir(SAVE_PATH):
        face_id = user_id.split('.')[1]
        user_path = SAVE_PATH + user_id
        image_paths = [os.path.join(user_path, key) for key in os.listdir(user_path)]
        for path in image_paths:
            face_ids.append(int(face_id))
            img = cv.imread(path, 0)
            # img_arr = np.array(img, dtype="uint8")
            face_arr.append(img)
    return face_arr, face_ids

face_arr, face_ids = get_imgs_labels()
time_end = time.process_time ()
print('runTime' + str((time_end - time_start)))
recog.train(train_img_gen)
print('train' + str((time.process_time () - time_end)))
recog.save('trainner/face.yaml')
  • Saved a model file after training

test of face recognition

VIDEO_PATH = 'video/hero3.mp4'
font = cv.FONT_HERSHEY_SIMPLEX
idNum = 0
names = ['unknow', 'cc', 'dm']
cap = cv.VideoCapture(VIDEO_PATH)
while cap.isOpened():
    ret, img = cap.read()
    img = imutils.resize(img, width=600)
    if ret is not None:
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        face = face_cascade.detectMultiScale(gray, 1.3, 5)
        for (x, y, w, h) in face:
            cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0))
            id, conf = recog.predict(gray[y: y+h, x: x+w])
            user = ''
            if conf < 100:
                user = names[id]
                conf = "{0}%".format(round(100-conf))
            else:
                user = "unknown"
                conf = "{0}%".format(round(100-conf))
            cv.putText(img, user, (x + 5, y - 5), font, 1, (0,255, 0), 1)
            cv.putText(img, str(conf), (x + 50, y - 5), font, 1, (0,255, 0), 1)
        cv.imshow('face', img)
        key = cv.waitKey(1)
        if key == 27:
            break
cap.release()
cv.destroyAllWindows()

results

Use opencv to do a simple face recognition
Use opencv to do a simple face recognition

full code

# %%
import cv2 as cv 
import numpy as np
import imutils
import os
from PIL import Image

# %%
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
VIDEO_PATH = 'video/hero2.mp4'
face_id = 2
#sampleNum用来计数样本数目
count = 0
SAVE_PATH = 'data/'

cap = cv.VideoCapture(VIDEO_PATH)
count = 0
while cap.isOpened():
    ret, img = cap.read()
    if ret is not None:
        if img is None:
            continue
        img = imutils.resize(img, width=600)
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        face = face_cascade.detectMultiScale(gray, 1.3, 5)
        for (x, y, w, h) in face:
            cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0))
            count += 1
            if not os.path.exists(SAVE_PATH + 'user.' + str(face_id)):
                os.mkdir(SAVE_PATH + 'user.' + str(face_id))
            cv.imwrite(SAVE_PATH + 'user.' + str(face_id) + "/count_" + str(count) + ".jpg", gray[y: y + h, x: x + w])
        if count >= 800:
            break   
        cv.imshow('h', img)
        key = cv.waitKey(1)
        if key == 27:
            break
    else:
        break
cap.release()
cv.destroyAllWindows()

# %%
import tensorflow.keras as keras
from keras.preprocessing.image import ImageDataGenerator

train_gen = ImageDataGenerator(rescale= 1./255)
train_img_gen = train_gen.flow_from_directory('./data/')

# %%
# 人脸识别器
import time

recog = cv.face.LBPHFaceRecognizer_create()
recog.read('trainner/face.yaml')
#创建一个函数,用于从数据集文件夹中获取训练图片,并获取id
time_start = time.process_time()
def get_imgs_labels():
    face_id = 0
    face_arr = []
    face_ids = []
    for user_id in os.listdir(SAVE_PATH):
        face_id = user_id.split('.')[1]
        user_path = SAVE_PATH + user_id
        image_paths = [os.path.join(user_path, key) for key in os.listdir(user_path)]
        for path in image_paths:
            face_ids.append(int(face_id))
            img = cv.imread(path, 0)
            # img_arr = np.array(img, dtype="uint8")
            face_arr.append(img)
    return face_arr, face_ids

face_arr, face_ids = get_imgs_labels()
time_end = time.process_time ()
print('runTime' + str((time_end - time_start)))
recog.train(train_img_gen)
print('train' + str((time.process_time () - time_end)))
recog.save('trainner/face.yaml')

# %%
VIDEO_PATH = 'video/hero2.mp4'
font = cv.FONT_HERSHEY_SIMPLEX
idNum = 0
names = ['unknow', 'cc', 'dm']
cap = cv.VideoCapture(VIDEO_PATH)
while cap.isOpened():
    ret, img = cap.read()
    img = imutils.resize(img, width=600)
    if ret is not None:
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        face = face_cascade.detectMultiScale(gray, 1.3, 5)
        for (x, y, w, h) in face:
            cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0))
            id, conf = recog.predict(gray[y: y+h, x: x+w])
            user = ''
            if conf < 100:
                user = names[id]
                conf = "{0}%".format(round(100-conf))
            else:
                user = "unknown"
                conf = "{0}%".format(round(100-conf))
            cv.putText(img, user, (x + 5, y - 5), font, 1, (0,255, 0), 1)
            cv.putText(img, str(conf), (x + 50, y - 5), font, 1, (0,255, 0), 1)
        cv.imshow('face', img)
        key = cv.waitKey(1)
        if key == 27:
            break
cap.release()
cv.destroyAllWindows()

# %%
END
 0
Comment(No Comments)