用CNN卷积神经网络进行人脸识别

该博客介绍了如何利用CNN卷积神经网络实现人脸识别。首先,详细讲述了数据处理的步骤,接着说明了模型训练和保存的过程,模型保存为model_weight.h5。外部接口通过调用Model类的face_predict函数进行人脸检测和识别。最后,展示了从视频中实时采集图像并进行预测的运行效果,识别结果以绿框显示人脸类别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1:对数据的处理class类

# -*- coding: utf-8 -*-
import os
import sys
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
    #RGB颜色
    BLACK = [0, 0, 0]
    #给图像增加边界,是图片长、宽等长,cv2.BORDER_CONSTANT指定边界颜色由value指定
    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)
                #cv2.imwrite('1.jpg', image)
                images.append(image)
                #print(full_path.split("\\")[3])
                labels.append(full_path.split("\\")[3])
    return images,labels
#从指定路径读取训练数据
def load_dataset(path_name):
    images,labels = read_path(path_name)
    #将输入的所有图片转成四维数组,尺寸为(图片数量*IMAGE_SIZE*IMAGE_SIZE*3)
    #两个人共1200张图片,IMAGE_SIZE为64,故对我来说尺寸为1200 * 64 * 64 * 3
    #图片为64 * 64像素,一个像素3个颜色值(RGB)
    images = np.array(images)
    #标注数据,'me'文件夹下都是我的脸部图像,全部指定为0,另外一个文件夹下是闺女的,全部指定为1
    labels = np.array([0 if label.startswith('meng') else 1 for label in labels])
    return images, labels



2:对model的训练,将训练好的model进行保存

#CNN网络模型类
import  random
from  keras.preprocessing.image import  ImageDataGenerator

from keras.layers import  Conv2D,MaxPooling2D,Activation,Dropout,Flatten,Dense,Convolution2D
from sklearn.model_selection  import  train_test_split

from  keras.models import  Sequential

from keras.optimizers import SGD

from  keras.utils import   np_utils

from  keras.models import  load_model

from load_face_dataset import load_dataset, resize_image, IMAGE_SIZE

from  keras import backend as k



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

     #建立模型
     def build_model(self, dataset, nb_classes = 2):
         #构建一个空的网络模型,它是一个线性堆叠模型,各神经网络层会被顺序添加,专业名称为序贯模型或线性堆叠模型
         self.model = Sequential()

         self.modelmodel.add(Conv2D(
             filters=32,
             activation='relu',
             padding='sa
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值