face_recognation人脸识别tensorflow版本代码解析

/* 版权声明:可以任意转载,转载时请标明文章原始出处和作者信息 .*/

###人脸识别程序共分为4个部分,大致结构如下:
####1.get_my_faces_dlib.py
使用opencv获取个人的人脸图像,并通过dlib库中的人脸特征提取,截取获取的正样本人脸数据集。
该程序共包括如下2个重要部分:
(1)定义relight函数,对摄像头拍摄的图像进行光线的转换,多样化样本。
(2)dlib函数针对的是灰度图像,对图像进行灰度转换和resize,存储图像均为64*64.

# get_my_faces_dlib.py
import cv2
import dlib
import random
import os
# import sys
out_dir = 'my_faces'
size = 64
if not os.path.exists(out_dir):
    os.makedirs(out_dir)

def relight(img, light=1, beta=0):
    w = img.shape[1]
    h = img.shape[0]
    # h, w, _ = img.shape

    for i in range(h):
        for j in range(w):
            for c in range(3):
                temp = int(img[i,j,c]*light+beta)
                if temp>255:
                    temp=255
                elif temp<0:
                    temp=0
                img[i,j,c] = temp
    return img

detector = dlib.get_frontal_face_detector()
cam = cv2.VideoCapture(0)

index = 1
while True:
    if index<=500:
        print('Being processed picture %s' % index)
        success, img = cam.read()
        gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        dets = detector(gray_image, 1)  # 返回是一个框[(x1,y1),(x2,y2)]
        for i, d in enumerate(dets):
            y1 = d.top() if d.top()>0 else 0
            y2 = d.bottom() if d.bottom()>0 else 0
            x1 = d.left() if d.left()>0 else 0
            x2 = d.right() if d.right()>0 else 0

            face = img[y1:y2, x1:x2]
            face = relight(face, random.uniform(0.5, 1.5), random.randint(-50, 50))

            face = cv2.resize(face, (size, size))
            cv2.imshow('image', face)
            cv2.imwrite(out_dir+'/'+str(index)+'.jpg',face)
            index += 1
        key = cv2.waitKey(30) & 0xff
        if key==27:
            break
    else:
        print('finished')
        break

####2.set_other_faces.py
对已有的数据集,如LFW数据集,通过重新提取图像到指定的输出文件夹中,形成train过程中的负样本集。
该程序共包括如下2个重要部分:
(1)读取已有数据集input_img中的图像。
(2)利用dlib库中的人脸特征函数将(1)中读取的图像进行人脸的截取,并重新写入新的文件夹other_faces中。

# set_other_faces.py
#encoding: utf-8
import cv2
import os
import dlib
import sys

# 定义数据文件夹
out_dir = 'other_faces'
# 定义待提取数据文件夹,在这里用的是LFW的数据集
input_dir = 'input_img'
# 建立输出文件夹out_dir
if not os.path.exists(out_dir):
    os.makedirs(out_dir)
# 提取人脸的特征,使用dlib自带的检测器
size = 64
detector = dlib.get_frontal_face_detector()
# 读入输入文件夹中的图像,并输出到特定的out_dir文件夹中
index = 1
for (path, namedir, filenames) in os.walk(input_dir):
    # 对输入文件夹input_dir中的每一个jpg图像进行提取并输出到out_dir中。
    for filename in filenames:
        if filename.endswith('.jpg'):
            # 提取图像的路径
            img_path = path + '/' + filename
            img = cv2.imread(img_path)
            # 提取人脸的检测框,获得dets,dlib是对灰度图像进行处理的,故转为灰度图像
            gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            dets = detector(gray_image, 1)
            # 使用enumerate 函数遍历序列中的元素以及它们的下标
            # 下标i即为人脸序号
            # left:人脸左边距离图片左边界的距离 ;right:人脸右边距离图片左边界的距离 
            # top:人脸上边距离图片上边界的距离 ;bottom:人脸下边距离图片上边界的距离
            for i, d in enumerate(dets):
                y1 = d.top() if d.top()>0 else 0
                y2 = d.bottom() if d.bottom()>0 else 0
                x1 = d.left() if d.left()>0 else 0
                x2 = d.right() if d.right()>0 else 0
                # 在原彩色图像中截取face区域,注意不能是对灰度图像进行处理
                face = img[y1:y2, x1:x2]
                # img[y:y+h,x:x+w] 截取框内的人脸
                
                # 对截取的人脸图像进行resize,并显示输出
                face = cv2.resize(face, (size, size))
                cv2.imshow('image', face) 

                # 将resize后的人脸写入out_dir文件夹中
                cv2.imwrite(out_dir + '/'+ str(index)+'.jpg',face)
                index += 1
            # 设定终止key,按esc键停止
            key = cv2.waitKey(30) & 0xff
            if key== 27:
                sys.exit(0)
            # 按q键停止
            # if cv2.waitKey(30) & 0xff == ord('q'):
            #     sys.exit(0)

####3.train_faces.py
训练my_faces和other_faces中的图像,获取准确率高于0.99的训练模型并保存。
该程序共包括如下2个重要部分:
(1)读入图像,特加入了填补函数getPaddingSize,防止图像进行resize的时候失真。
(2)图像转化可读入数据集,image转化为矩阵,label转化为one-hot编码,正样本为[0,1],负样本为[1,0].
(3)将整个正样本和负样本进行随机划分为测试集和训练集,test_size=0.05。
(4)利用CNN进行训练,三层卷积层,维度分别为(32,64,64),卷积核大小均为3;每一层均采用maxpool,池化大小均为2;且都采用dropout操作来减小过拟合。全连接层维度为512,并使用dropout,softmax输出为2。
(5)当所有图像被训练两轮后且测试准确率大于0.99时,将训练结果模型保存在项目目录中,以供实时测试使用。

# train_faces.py
#encoding: utf-8
import tensorflow as tf
import cv2
import numpy as np
import os
import random
import sys
from sklearn.model_selection import train_test_split

my_faces_path = 'my_faces'
other_faces_path = 'other_faces'
size = 64

imgs = []
labs = []

def getPaddingSize(img):
    h, w, _ = img.shape
    top, bottom, left, right = (0,0,0,0)
    longest = max(h, w)

    if w < longest:
        tmp = longest - w
        # //表示整除符号
        left = tmp // 2
        right = tmp - left
    elif h < longest:
        tmp = longest - h
        top = tmp // 2
        bottom = tmp - top
    else:
        pass
    return top, bottom, left, right

def readData(path , h=size, w=size):
    for filename in os.listdir(path):
        if filename.endswith('.jpg'):
            filename = path + '/' + filename

            img = cv2.imread(filename)

            top,bottom,left,right = getPaddingSize(img)
            # 将图片放大, 扩充图片边缘部分
            img = cv2.copyMakeBorder(img, top, bottom, left, right, cv2.BORDER_CONSTANT, value=[0,0,0])
            img = cv2.resize(img, (h, w))

            imgs.append(img)
            labs.append(path)

readData(my_faces_path)
readData(other_faces_path)
# 将图片数据与标签转换成数组
imgs = np.array(imgs)
labs = np.array([[0,1] if lab == my_faces_path else [1,0] for lab in labs])
# 随机划分测试集与训练集
train_x,test_x,train_y,test_y = train_test_split(imgs, labs, test_size=0.05, random_state=random.randint(0,100))
# 参数:图片数据的总数,图片的高、宽、通道
train_x = train_x.reshape(train_x.shape[0], size, size, 3)
test_x = test_x.reshape(test_x.shape[0], size, size, 3)
# 将数据转换成小于1的数
train_x = train_x.astype('float32')/255.0
test_x = test_x.astype('float32')/255.0

print('train size:%s, test size:%s' % (len(train_x), len(test_x)))
# 图片块,每次取100张图片
batch_size = 100
num_batch = len(train_x) // batch_size

x = tf.placeholder(tf.float32, [None, size, size, 3])
y_ = tf.placeholder(tf.float32, [None, 2])

keep_prob_5 = tf.placeholder(tf.float32)
keep_prob_75 = tf.placeholder(tf.float32)

def weightVariable(shape):
    init = tf.random_normal(shape, stddev=0.01)
    return tf.Variable(init)

def biasVariable(shape):
    init = tf.random_normal(shape)
    return tf.Variable(init)

def conv2d(x, W):
    return tf.nn.conv2d(x, W, strides=[1,1,1,1], padding='SAME')

def maxPool(x):
    return tf.nn.max_pool(x, ksize=[1,2,2,1], strides=[1,2,2,1], padding='SAME')

def dropout(x, keep):
    return tf.nn.dropout(x, keep)

def cnnLayer():
    # 第一层
    W1 = weightVariable([3,3,3,32]) # 卷积核大小(3,3), 输入通道(3), 输出通道(32)
    b1 = biasVariable([32])
    # 卷积
    conv1 = tf.nn.relu(conv2d(x, W1) + b1)
    # 池化
    pool1 = maxPool(conv1)
    # 减少过拟合,随机让某些权重不更新
    drop1 = dropout(pool1, keep_prob_5)

    # 第二层
    W2 = weightVariable([3,3,32,64])
    b2 = biasVariable([64])
    conv2 = tf.nn.relu(conv2d(drop1, W2) + b2)
    pool2 = maxPool(conv2)
    drop2 = dropout(pool2, keep_prob_5)

    # 第三层
    W3 = weightVariable([3,3,64,64])
    b3 = biasVariable([64])
    conv3 = tf.nn.relu(conv2d(drop2, W3) + b3)
    pool3 = maxPool(conv3)
    drop3 = dropout(pool3, keep_prob_5)

    # 全连接层
    Wf = weightVariable([8*8*64, 512])
    bf = biasVariable([512])
    drop3_flat = tf.reshape(drop3, [-1, 8*8*64])
    dense = tf.nn.relu(tf.matmul(drop3_flat, Wf) + bf)
    dropf = dropout(dense, keep_prob_75)

    # 输出层
    Wout = weightVariable([512,2])
    bout = biasVariable([2])
    #out = tf.matmul(dropf, Wout) + bout
    out = tf.add(tf.matmul(dropf, Wout), bout)
    return out

def cnnTrain():
    out = cnnLayer()

    cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=out, labels=y_))

    train_step = tf.train.AdamOptimizer(0.01).minimize(cross_entropy)
    # 比较标签是否相等,再求的所有数的平均值,tf.cast(强制转换类型)
    accuracy = tf.reduce_mean(tf.cast(tf.equal(tf.argmax(out, 1), tf.argmax(y_, 1)), tf.float32))
    # 将loss与accuracy保存以供tensorboard使用
    tf.summary.scalar('loss', cross_entropy)
    tf.summary.scalar('accuracy', accuracy)
    merged_summary_op = tf.summary.merge_all()
    # 数据保存器的初始化
    saver = tf.train.Saver()

    with tf.Session() as sess:

        sess.run(tf.global_variables_initializer())

        summary_writer = tf.summary.FileWriter('tmp', graph=tf.get_default_graph())

        for n in range(200):
             # 每次取128(batch_size)张图片
            for i in range(num_batch):
                batch_x = train_x[i*batch_size : (i+1)*batch_size]
                batch_y = train_y[i*batch_size : (i+1)*batch_size]
                # 开始训练数据,同时训练三个变量,返回三个数据
                _,loss,summary = sess.run([train_step, cross_entropy, merged_summary_op],
                                           feed_dict={x:batch_x,y_:batch_y, keep_prob_5:0.5,keep_prob_75:0.75})
                summary_writer.add_summary(summary, n*num_batch+i)
                # 打印损失
                print('第%s次训练,loss=%s' % (n*num_batch+i, loss))

                if (n*num_batch+i) % 100 == 0:
                    # 获取测试数据的准确率
                    acc = accuracy.eval({x:test_x, y_:test_y, keep_prob_5:1.0, keep_prob_75:1.0})
                    print('%s,acc=%s'%(n*num_batch+i, acc))
                    # 准确率大于0.99时保存并退出
                    if acc > 0.99 and n > 2:
                        saver.save(sess, './train_faces.model', global_step=n*num_batch+i)
                        sys.exit(0)
        print('accuracy less 0.99, exited!')

cnnTrain()

####4.is_my_face.py
测试过程直接采用保存的训练模型中的参数,使用opencv获取实时图像,检测摄像头获取的人脸是否是本人,输出为True or False。

# is_my_face.py
saver = tf.train.Saver()  
sess = tf.Session()  
saver.restore(sess, tf.train.latest_checkpoint('.'))  
   
def is_my_face(image):  
    res = sess.run(predict, feed_dict={x: [image/255.0], keep_prob_5:1.0, keep_prob_75: 1.0})  
    if res[0] == 1:  
        return True  
    else:  
        return False  

#使用dlib自带的frontal_face_detector作为我们的特征提取器
detector = dlib.get_frontal_face_detector()

cam = cv2.VideoCapture(0)  
   
while True:  
    _, img = cam.read()  
    gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    dets = detector(gray_image, 1)
    if not len(dets):
        #print('Can`t get face.')
        cv2.imshow('img', img)
        key = cv2.waitKey(30) & 0xff  
        if key == 27:
            sys.exit(0)
            
    for i, d in enumerate(dets):
        x1 = d.top() if d.top() > 0 else 0
        y1 = d.bottom() if d.bottom() > 0 else 0
        x2 = d.left() if d.left() > 0 else 0
        y2 = d.right() if d.right() > 0 else 0
        face = img[x1:y1,x2:y2]
        # 调整图片的尺寸
        face = cv2.resize(face, (size,size))
        print('Is this my face? %s' % is_my_face(face))

        cv2.rectangle(img, (x2,x1),(y2,y1), (255,0,0),3)
        cv2.imshow('image',img)
        key = cv2.waitKey(30) & 0xff
        if key == 27:
            sys.exit(0)
  
sess.close() 
如下图所示,当摄像头读入本人时,显示True,是其他人的时候,显示False。

image

NOTE:

  • 正样本和负样本的比例不可过大,在实际操作过程中,录入正样本太少,与LFW庞大的样本量对比,会造成测试的准备率极低。
  • train_face的range,应根据个人的样本量调整,太少,会造成未达到要求的acc就输出accuracy less 0.99, exited!,保存不了训练模型。

   完整代码详见github_face_reg,相互学习。

  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值