【深度学习】基于卷积神经网络(tensorflow)的人脸识别项目(四)

目录

前言

经过前段时间研究,从LeNet-5手写数字入门到最近研究的一篇天气识别。我想干一票大的,因为我本身从事的就是C++/Qt开发,对Qt还是比较熟悉,所以我想实现一个界面化的一个人脸识别。

对卷积神经网络的概念比较陌生的可以看一看这篇文章:卷积实际上是干了什么
想了解神经网络的训练流程、或者环境搭建的可以看这篇文章:环境搭建与训练流程

如果想学习本项目请先去看
第一篇
基于卷积神经网络(tensorflow)的人脸识别项目(一)
第二篇基于卷积神经网络(tensorflow)的人脸识别项目(二)
第三篇基于卷积神经网络(tensorflow)的人脸识别项目(三)

基本思路

具体步骤如下:

  1. 首先需要收集数据,我的想法是通过OpenCV调用摄像头进行收集人脸照片。
  2. 然后进行预处理,主要是对数据集分类,训练集、验证集、测试集。
  3. 开始训练模型,提前创建好标签键值对。
  4. 测试人脸识别效果,通过OpenCV捕获人脸照片然后对图片进行预处理最后传入模型中,然后将识别的结果通过文字的形式打印在屏幕上,以此循环,直到输入q退出。

本篇主要是对上述步骤中的第四步进行实现。最后分享整个全流程的完整项目代码。

测试人脸识别效果

设计思路

通过OpenCV打开摄像头捕捉人脸区域,然后对图片进行预处理(如灰度化、归一化等等),然后加载模型,把处理后的图片放入模型中进行预测,然后对预测的结果进行一个精度过滤就是对识别率低于90%的结果认为识别不准确,就会输出other表示不能高度识别。正常情况下输出每个文件所对应的label。

详细代码

加载模型

将我们之前训练好的模型通过load_model方法进行加载。

    MODEL_PATH = './me.face.model.h5'
    def load_model(self, file_path=MODEL_PATH):
        self.model = load_model(file_path)

人脸预测

这里对图片进行了归一化处理,并对预测结果进行了精度过滤。
注意: K.image_dim_ordering() =\= 'th': 如果报错的话请替换为 K.image_data_format() == 'channels_first'channels_last“对应原本的” tf“,” channels_first“对应原本的” th“。

    def face_predict(self, image):
        if K.image_data_format() == 'channels_first' and image.shape != (1, 3, IMAGE_SIZE, IMAGE_SIZE):
            image = resize_image(image)
            image = image.reshape((1, 3, IMAGE_SIZE, IMAGE_SIZE))
        elif K.image_data_format() == 'channels_last' and image.shape != (1, IMAGE_SIZE, IMAGE_SIZE, 3):
            image = resize_image(image)
            image = image.reshape((1, IMAGE_SIZE, IMAGE_SIZE, 3))

        image = image.astype('float32')
        image /= 255

        result = self.model.predict_proba(image)
        print('result:', result)
        my_result = list(result[0]).index(max(result[0]))
        max_result = max(result[0])
        print("result最大值下标:", my_result)
        if max_result > 0.90:
            return my_result
        else:
            return -1

主要逻辑

主要分为以下几步骤:

  1. 加载模型
  2. 预处理(设置摄像头、人脸区域的边框颜色、haar分类器的路径、label数组等)
  3. 捕获一帧图片
  4. 对图片灰度化
  5. 计算出人脸区域并框出
  6. 将人脸区域交给识别模型进行识别
  7. 将识别结果进行屏幕打印
  8. 然后3-7步骤循环。
  9. 输入q退出识别,然后释放所占用的资源

这个逻辑不是很复杂,下面直接进行代码展示,在代码中也有详细的注释说明:

import cv2
from keras_train import Model

if __name__ == '__main__':
    model = Model()
    model.load_model(file_path='./model/me.face.model.h5')

    color = (0, 255, 0)

    cap = cv2.VideoCapture(0)

    cascade_path = "./model/haarcascade_frontalface_alt2.xml"

    while True:
        _, frame = cap.read()

        frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        cascade = cv2.CascadeClassifier(cascade_path)

        faceRects = cascade.detectMultiScale(frame_gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
        if len(faceRects) > 0:
            for faceRect in faceRects:
                x, y, w, h = faceRect

                image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
                faceID = model.face_predict(image)

                human = {0: 'use2', 1: 'use3', 2: 'use4', -1: 'others', 3: 'use5', 4: 'LinXi07',
                         5: 'use7', 6: 'use8', 7: 'use1', 8: 'use9'}

                cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, thickness=2)

                cv2.putText(frame, human[faceID],
                            (x + 30, y + 30),
                            cv2.FONT_HERSHEY_SIMPLEX,
                            1,
                            (255, 0, 255),
                            2)

        cv2.imshow("Face Identification System", frame)

        k = cv2.waitKey(10)

        if k & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

测试效果

这里对模型进行测试,并支持多个人脸同时识别,且识别率较高。( 忽略掉人脸

【深度学习】基于卷积神经网络(tensorflow)的人脸识别项目(四)

; 总结

从最开始的收集数据到中间的预处理再到后来的模型建立到最后的测试效果,这一路非常坎坷,不是数据格式不匹配导致报错,就是版本不匹配来回重装环境再就是模型识别率上不去。总算把这个完整的做出来了,路途坎坷但收获不菲。让我们一起加油吧!!!!

所有代码

这里我以文件进行分类,总共四个文件。

文件名说明frame_capture.py制作数据集keras_train.py训练模型 评估模型load_data.py加载数据,预处理face_predict_use_keras.py预测模型

然后deep_learning用来存放每个人的照片。model用来存放模型好的模型以及harr分类器。

【深度学习】基于卷积神经网络(tensorflow)的人脸识别项目(四)

; face_predict_use_keras.py

import cv2
import sys

def catch_usb_video(window_name, camera_idx):
    '''使用cv2.imshow()的时候,如果图片太大,会显示不全并且无法调整。
    因此在cv2.imshow()的前面加上这样的一个语句:cv2.namedWindow('image', 0),
    得到的图像框就可以自行调整大小,可以拉伸进行自由调整。'''
    cv2.namedWindow(window_name, 0)

    cap = cv2.VideoCapture(camera_idx)

    '''
    Haar特征是一种反映图像的灰度变化的,像素分模块求差值的一种特征。它分为三类:边缘特征、线性特征、中心特征和对角线特征。
    '''
    classfier = cv2.CascadeClassifier("./model/haarcascade_frontalface_alt2.xml")

    color = (0, 0, 255)
    num = 0
    while cap.isOpened():
        ok, frame = cap.read()
        if not ok:
            break

        grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        faceRects = classfier.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))

        if len(faceRects) > 0:
            for faceRect in faceRects:

                x, y, w, h = faceRect
                cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)

                img_name = '%s/%d.jpg' % ('./deep_learning/zm', num)
                image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
                cv2.imwrite(img_name, image)
                num += 1
                if num > (500):
                    break

            cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, 2)

            font = cv2.FONT_HERSHEY_SIMPLEX
            cv2.putText(frame, 'num:%d' % (num), (x + 30, y + 30), font, 1, (255, 0, 255), 4)

        if num > (500):
            break

        cv2.imshow(window_name, frame)
        c = cv2.waitKey(1)
        if c & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

if __name__ == '__main__':
    catch_usb_video("face", 0)

keras_train.py

import random
from sklearn.model_selection import train_test_split
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Convolution2D, MaxPooling2D
from keras.optimizers import SGD
from keras.utils import np_utils
from keras.models import load_model
from keras import backend as K
from load_data import load_dataset, resize_image, IMAGE_SIZE

class Dataset:
    def __init__(self, path_name):

        self.train_images = None
        self.train_labels = None

        self.valid_images = None
        self.valid_labels = None

        self.test_images = None
        self.test_labels = None

        self.path_name = path_name

        self.input_shape = None

    def load(self, img_rows=IMAGE_SIZE, img_cols=IMAGE_SIZE,
             img_channels=3, nb_classes=3):

        images, labels = load_dataset(self.path_name)

        train_images, valid_images, train_labels, valid_labels = train_test_split(images, labels, test_size=0.2,
                                                                                  random_state=random.randint(0, 100))
        _, test_images, _, test_labels = train_test_split(images, labels, test_size=0.5,
                                                          random_state=random.randint(0, 100))

        if K.image_data_format() == 'channels_first':
            train_images = train_images.reshape(train_images.shape[0], img_channels, img_rows, img_cols)
            valid_images = valid_images.reshape(valid_images.shape[0], img_channels, img_rows, img_cols)
            test_images = test_images.reshape(test_images.shape[0], img_channels, img_rows, img_cols)
            self.input_shape = (img_channels, img_rows, img_cols)
        else:
            train_images = train_images.reshape(train_images.shape[0], img_rows, img_cols, img_channels)
            valid_images = valid_images.reshape(valid_images.shape[0], img_rows, img_cols, img_channels)
            test_images = test_images.reshape(test_images.shape[0], img_rows, img_cols, img_channels)
            self.input_shape = (img_rows, img_cols, img_channels)

            print(train_images.shape[0], 'train samples')
            print(valid_images.shape[0], 'valid samples')
            print(test_images.shape[0], 'test samples')

            train_labels = np_utils.to_categorical(train_labels, nb_classes)
            valid_labels = np_utils.to_categorical(valid_labels, nb_classes)
            test_labels = np_utils.to_categorical(test_labels, nb_classes)

            train_images = train_images.astype('float32')
            valid_images = valid_images.astype('float32')
            test_images = test_images.astype('float32')

            train_images /= 255
            valid_images /= 255
            test_images /= 255

            self.train_images = train_images
            self.valid_images = valid_images
            self.test_images = test_images
            self.train_labels = train_labels
            self.valid_labels = valid_labels
            self.test_labels = test_labels

class Model:
    def __init__(self):
        self.model = None

    def build_model(self, dataset, nb_classes=3):

        self.model = Sequential()

        self.model.add(Convolution2D(32, 3, 3, border_mode='same',
                                     input_shape=dataset.input_shape))
        self.model.add(Activation('relu'))

        self.model.add(Convolution2D(32, 3, 3))
        self.model.add(Activation('relu'))

        self.model.add(MaxPooling2D(pool_size=(2, 2)))
        self.model.add(Dropout(0.25))

        self.model.add(Convolution2D(64, 3, 3, border_mode='same'))
        self.model.add(Activation('relu'))

        self.model.add(Convolution2D(64, 3, 3))
        self.model.add(Activation('relu'))

        self.model.add(MaxPooling2D(pool_size=(2, 2)))
        self.model.add(Dropout(0.25))

        self.model.add(Flatten())
        self.model.add(Dense(512))
        self.model.add(Activation('relu'))
        self.model.add(Dropout(0.5))
        self.model.add(Dense(nb_classes))
        self.model.add(Activation('softmax'))

        self.model.summary()

    def train(self, dataset, batch_size=20, nb_epoch=10, data_augmentation=True):

        sgd = SGD(lr=0.01, decay=1e-6,
                  momentum=0.9, nesterov=True)
        self.model.compile(loss='categorical_crossentropy',
                           optimizer=sgd,
                           metrics=['accuracy'])

        if not data_augmentation:
            self.model.fit(dataset.train_images,
                           dataset.train_labels,
                           batch_size=batch_size,
                           nb_epoch=nb_epoch,
                           validation_data=(dataset.valid_images, dataset.valid_labels),
                           shuffle=True)

        else:

            datagen = ImageDataGenerator(
                featurewise_center=False,
                samplewise_center=False,
                featurewise_std_normalization=False,
                samplewise_std_normalization=False,
                zca_whitening=False,
                rotation_range=20,
                width_shift_range=0.2,
                height_shift_range=0.2,
                horizontal_flip=True,
                vertical_flip=False)

            datagen.fit(dataset.train_images)

            self.model.fit_generator(datagen.flow(dataset.train_images, dataset.train_labels,
                                                  batch_size=batch_size),
                                     samples_per_epoch=dataset.train_images.shape[0],
                                     nb_epoch=nb_epoch,
                                     validation_data=(dataset.valid_images, dataset.valid_labels))

    MODEL_PATH = './me.face.model.h5'

    def save_model(self, file_path=MODEL_PATH):
        self.model.save(file_path)

    def load_model(self, file_path=MODEL_PATH):
        self.model = load_model(file_path)

    def evaluate(self, dataset):
        score = self.model.evaluate(dataset.test_images, dataset.test_labels, verbose=1)
        print("%s: %.2f%%" % (self.model.metrics_names[1], score[1] * 100))

    def face_predict(self, image):

        if K.image_data_format() == 'channels_first' and image.shape != (1, 3, IMAGE_SIZE, IMAGE_SIZE):
            image = resize_image(image)
            image = image.reshape((1, 3, IMAGE_SIZE, IMAGE_SIZE))
        elif K.image_data_format() == 'channels_last' and image.shape != (1, IMAGE_SIZE, IMAGE_SIZE, 3):
            image = resize_image(image)
            image = image.reshape((1, IMAGE_SIZE, IMAGE_SIZE, 3))

        image = image.astype('float32')
        image /= 255

        result = self.model.predict_proba(image)
        print('result:', result)
        my_result = list(result[0]).index(max(result[0]))
        max_result = max(result[0])
        print("result最大值下标:", my_result)
        if max_result > 0.90:
            return my_result
        else:
            return -1

if __name__ == '__main__':
    dataset = Dataset('.\\deep_learning')
    dataset.load(nb_classes=9)

    model = Model()
    model.build_model(dataset, nb_classes=9)
    model.train(dataset)
    model.save_model(file_path='./model/me.face.model.h5')

    model = Model()
    model.load_model(file_path='./model/me.face.model.h5')
    model.evaluate(dataset)

load_data.py

import os
import numpy as np
import cv2

IMAGE_SIZE = 64

def resize_image(image, height=IMAGE_SIZE, width=IMAGE_SIZE):
    top, bottom, left, right = (0, 0, 0, 0)

    h, w, _ = image.shape

    longest_edge = max(h, w)

    if h < longest_edge:
        dh = longest_edge - h
        top = dh // 2
        bottom = dh - top
    elif w < longest_edge:
        dw = longest_edge - w
        left = dw // 2
        right = dw - left
    else:
        pass

    BLACK = [0, 0, 0]

    constant = cv2.copyMakeBorder(image, top, bottom, left, right, cv2.BORDER_CONSTANT, value=BLACK)

    return cv2.resize(constant, (height, width))

images = []
labels = []

def read_path(path_name):
    for dir_item in os.listdir(path_name):

        full_path = os.path.abspath(os.path.join(path_name, dir_item))

        if os.path.isdir(full_path):
            read_path(full_path)
        else:
            if dir_item.endswith('.jpg'):
                image = cv2.imread(full_path)

                image = resize_image(image, IMAGE_SIZE, IMAGE_SIZE)

                images.append(image)
                labels.append(path_name)

    return images, labels

def indentify(label):
    if label.endswith('use'):
        return 0
    elif label.endswith('use'):
        return 1
    elif label.endswith('use'):
        return 2
    elif label.endswith('use'):
        return 3
    elif label.endswith('use'):
        return 4
    elif label.endswith('use'):
        return 5
    elif label.endswith('use'):
        return 6
    elif label.endswith('use'):
        return 7
    elif label.endswith('use'):
        return 8

def load_dataset(path_name):
    images, labels = read_path(path_name)

    images = np.array(images)
    print(images.shape)

    labels = np.array([indentify(label) for label in labels])

    print(images,labels)
    return images, labels

if __name__ == '__main__':
    images, labels = load_dataset('./deep_learning')

face_predict_use_keras.py

import cv2
from keras_train import Model

if __name__ == '__main__':

    model = Model()
    model.load_model(file_path='./model/me.face.model.h5')

    color = (0, 255, 0)

    cap = cv2.VideoCapture(0)

    cascade_path = "./model/haarcascade_frontalface_alt2.xml"

    while True:
        _, frame = cap.read()

        frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        cascade = cv2.CascadeClassifier(cascade_path)

        faceRects = cascade.detectMultiScale(frame_gray, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))
        if len(faceRects) > 0:
            for faceRect in faceRects:
                x, y, w, h = faceRect

                image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
                faceID = model.face_predict(image)

                human = {0: 'use3', 1: 'use4', 2: 'use8', -1: 'others', 3: 'use88', 4: 'LinXi07',
                         5: 'use2', 6: 'use', 7: 'use1', 8: 'use7'}

                cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), color, thickness=2)

                cv2.putText(frame, human[faceID],
                            (x + 30, y + 30),
                            cv2.FONT_HERSHEY_SIMPLEX,
                            1,
                            (255, 0, 255),
                            2)

        cv2.imshow("Face Identification System", frame)

        k = cv2.waitKey(10)

        if k & 0xFF == ord('q'):
            break

    cap.release()
    cv2.destroyAllWindows()

以上就是全部代码啦。有啥疑问就评论区讨论奥。

Original: https://blog.csdn.net/qq_45254369/article/details/126492132
Author: 林夕07
Title: 【深度学习】基于卷积神经网络(tensorflow)的人脸识别项目(四)

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/721523/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球