利用opencv 做一个简单的人脸识别

文章目录

  • 安装
  • 实现
  • 人脸识别
  • 进行人脸模型训练
  • 识别人脸测试
  • 效果展示
  • 完整代码

  • 想开发一个属于自己的人脸识别系统, 动手开始吧
    利用opencv 做一个简单的人脸识别_第1张图片

安装

  • opencv 和 包模块opencv-contrib-python
  • 安装失败的解决方案
pip uninstall opencv-python
pip uninstall opencv-contrib-python

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

  • 完成后重启就可以了

实现

  • 先对人脸进行识别
  • 获取人脸特征图片并截取 灰度图保存
  • 进行人脸模型训练
  • 测试运行

人脸识别

  • 运用了opencv 的人脸识别框架
face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
  • 截取800 帧的人脸图片 并保存数据图片
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()

利用opencv 做一个简单的人脸识别_第2张图片
利用opencv 做一个简单的人脸识别_第3张图片
测试用一个宝藏up主的人脸测试,打扰了,你要火

进行人脸模型训练

  • 运用opencv 的face mok
  • recog = cv.face.LBPHFaceRecognizer_create()
# 人脸识别器
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')

  • 训练完保存了一个模型文件
  • 利用opencv 做一个简单的人脸识别_第4张图片

识别人脸测试

  • 先用人脸识别出人脸区域,截取出人脸区域,进行灰度化
  • 输入到模型中预测
  • 图片展示
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()
        

效果展示

利用opencv 做一个简单的人脸识别_第5张图片
利用opencv 做一个简单的人脸识别_第6张图片

  • 下面这个是训练的视频,上面是测试的视频

完整代码

# %%
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()
        
            
        
        
        

# %%





你可能感兴趣的:(opencv,深度学习,opencv,计算机视觉,python)