1. 程式人生 > >tensorflow74 使用tensorflow dlib opencv做特定人臉識別

tensorflow74 使用tensorflow dlib opencv做特定人臉識別

01 基本環境

# 該blog完整參考 http://tumumu.cn/2017/05/02/deep-learning-face/
# 原始碼地址:https://github.com/5455945/tensorflow_demo.git
# https://github.com/5455945/tensorflow_demo/tree/master/SpecificFaceRecognition
# win10 Tensorflow_gpu1.2.1 python3.5.3 dlib opencv
# CUDA v8.0 cudnn-8.0-windows10-x64-v5.1
# 本實驗需要有一個攝像頭,筆記本自帶的即可
# tensorflow_demo\SpecificFaceRecognition\get_my_faces.py 用dlib生成自己臉的jpg影象
# tensorflow_demo\SpecificFaceRecognition\get_my_faces_opencv.py 用opencv生成自己臉的jpg影象(效果沒有dlib好) # tensorflow_demo\SpecificFaceRecognition\set_other_faces.py 預處理lfw的人臉資料 # tensorflow_demo\SpecificFaceRecognition\train_faces.py 人臉識別訓練 # tensorflow_demo\SpecificFaceRecognition\is_my_face.py 人臉識別測試
pip3 install
tensorflow==1.2.1 pip3 install tensorflow_gpu==1.2.1 pip3 install numpy==1.13.1+mkl pip3 install opencv-python==3.2.0 pip3 install dlib==19.4.0 # 一定要注意scikit-learn和scipy的版本 pip3 install scikit-learn==0.18.2 pip3 install scipy==0.19.1

02 獲取本人圖片集

使用get_my_faces.py獲取本人的10000張頭像照片,儲存到./my_faces目錄。只需啟動get_my_faces.py

,坐在電腦前,擺出不同臉部表情和姿勢即可。大約1小時左右可採集10000張。
get_my_faces_opencv.py是採用opencv庫採集的,速度比dlib的get_my_faces.py快些。dlib效果會好些。

get_my_faces.py

# -*- codeing: utf-8 -*-
import cv2
import dlib
import os
import sys
import random

# 使用攝像頭採集某人的人臉資料,儲存到./my_faces目錄

output_dir = './my_faces'
size = 64

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# 改變圖片的亮度與對比度
def relight(img, light=1, bias=0):
    w = img.shape[1]
    h = img.shape[0]
    #image = []
    for i in range(0,w):
        for j in range(0,h):
            for c in range(3):
                tmp = int(img[j,i,c]*light + bias)
                if tmp > 255:
                    tmp = 255
                elif tmp < 0:
                    tmp = 0
                img[j, i, c] = tmp
    return img

# 使用dlib自帶的frontal_face_detector作為我們的特徵提取器
detector = dlib.get_frontal_face_detector()
# 開啟攝像頭 引數為輸入流,可以為攝像頭或視訊檔案
camera = cv2.VideoCapture(0)

index = 1
while True:
    if (index <= 10000):
        print('Being processed picture %s' % index)
        # 從攝像頭讀取照片
        success, img = camera.read()
        # 轉為灰度圖片
        gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # 使用detector進行人臉檢測
        dets = detector(gray_img, 1)

        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 = relight(face, random.uniform(0.5, 1.5), random.randint(-50, 50))
            face = cv2.resize(face, (size,size))
            cv2.imshow('image', face)
            cv2.imwrite(output_dir+'/'+str(index)+'.jpg', face)
            index += 1

        key = cv2.waitKey(30) & 0xff
        if key == 27:
            break
    else:
        print('Finished!')
        break

03 獲取其他人臉圖片集

下載http://vis-www.cs.umass.edu/lfw/lfw.tgz人臉資料集。
windows下,可以使用winrar解壓,注意要先選[檢視檔案],然後再解壓,才能解壓出所有子目錄及檔案。
加壓後的檔案放到./input_img目錄下。
然後,使用set_other_people.py處理./input_img目錄下的解壓檔案,把大約13000+張頭像預處理到./other_faces目錄。
set_other_people.py

# -*- codeing: utf-8 -*-
import sys
import os
import cv2
import dlib

# 下載 lfw.tgz 並解壓所有檔案到./input_img
# wget http://vis-www.cs.umass.edu/lfw/lfw.tgz

input_dir = './input_img'
output_dir = './other_faces'
size = 64

if not os.path.exists(output_dir):
    os.makedirs(output_dir)

# 使用dlib自帶的frontal_face_detector作為我們的特徵提取器
detector = dlib.get_frontal_face_detector()

index = 1
for (path, dirnames, filenames) in os.walk(input_dir):
    for filename in filenames:
        if filename.endswith('.jpg'):
            print('Being processed picture %s' % index)
            img_path = path + '/' + filename
            # 從檔案讀取圖片
            img = cv2.imread(img_path)
            # 轉為灰度圖片
            gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            # 使用detector進行人臉檢測 dets為返回的結果
            dets = detector(gray_img, 1)

            # 使用enumerate 函式遍歷序列中的元素以及它們的下標
            # 下標i即為人臉序號
            # left:人臉左邊距離圖片左邊界的距離 ;right:人臉右邊距離圖片左邊界的距離
            # top:人臉上邊距離圖片上邊界的距離 ;bottom:人臉下邊距離圖片上邊界的距離
            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
                # img[y:y+h, x:x+w]
                face = img[x1:y1, x2:y2]
                # 調整圖片的尺寸
                face = cv2.resize(face, (size, size))
                cv2.imshow('image', face)
                # 儲存圖片
                cv2.imwrite(output_dir + '/' + str(index) + '.jpg', face)
                index += 1

            key = cv2.waitKey(30) & 0xff
            if key == 27:
                sys.exit(0)

04 訓練模型

使用train_faces.py來訓練模型,模型保持到./model目錄下
train_faces.py

# -*- codeing: 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和./other_faces中的人臉資料訓練,保持模型到./model中

my_faces_path = './my_faces'
other_faces_path = './other_faces'
model_path = './model'

if not os.path.exists(model_path):
    os.makedirs(model_path)

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 = weightVariable([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(10):
             # 每次取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("loss ", 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(n * num_batch + i, "acc:", acc, "  loss:", loss)
                    # 準確率大於0.98時儲存並退出
                    if acc > 0.98 and n > 2:
                        saver.save(sess, model_path + '/train_faces.model', global_step = n * num_batch + i)
                        sys.exit(0)
        print('accuracy less 0.98, exited!')

cnnTrain()
'''
train size: 22782, test size: 1200
0 acc: 0.560833   loss: 0.760013
100 acc: 0.923333   loss: 0.280099
200 acc: 0.945833   loss: 0.255821
300 acc: 0.953333   loss: 0.246161
400 acc: 0.958333   loss: 0.113214
500 acc: 0.9625   loss: 0.183178
600 acc: 0.964167   loss: 0.119886
700 acc: 0.971667   loss: 0.134483
800 acc: 0.943333   loss: 0.142579
900 acc: 0.953333   loss: 0.143854
1000 acc: 0.958333   loss: 0.167131
1100 acc: 0.965   loss: 0.10453
1200 acc: 0.975833   loss: 0.132573
1300 acc: 0.976667   loss: 0.191987
1400 acc: 0.9825   loss: 0.0590191
'''

05 使用模型進行識別

使用is_my_face.py來驗證模型,檢測到是自己的臉時,返回true。
is_my_face.py

# -*- codeing: utf-8 -*-
import tensorflow as tf
import cv2
import dlib
import numpy as np
import os
import random
import sys
from sklearn.model_selection import train_test_split

# 使用攝像頭採集人臉,使用./model中的模型檢測是否為特定的人臉

my_faces_path = './my_faces'
other_faces_path = './other_faces'
model_path = './model'
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)))
# 圖片塊,每次取128張圖片
batch_size = 128
num_batch = len(train_x) // 128

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*16*32, 512])
    bf = biasVariable([512])
    drop3_flat = tf.reshape(drop3, [-1, 8*16*32])
    dense = tf.nn.relu(tf.matmul(drop3_flat, Wf) + bf)
    dropf = dropout(dense, keep_prob_75)

    # 輸出層
    Wout = weightVariable([512, 2])
    bout = weightVariable([2])
    out = tf.add(tf.matmul(dropf, Wout), bout)
    return out

output = cnnLayer()
predict = tf.argmax(output, 1)
saver = tf.train.Saver()
sess = tf.Session()
saver.restore(sess, tf.train.latest_checkpoint(model_path))

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()
'''
train size:22782, test size:1200
Is this my face? True
Is this my face? True
Is this my face? True
...
'''

06 關於opencv獲取特定人臉資料

這個使用opencv的程式碼還需要完善,需要多個分類器組合使用,這裡僅僅給出了一個分類器haarcascade_frontalface_default.xml,效果不是很好。opencv自帶的分類器在opencv原始碼的data目錄下面。

get_my_faces_opencv.py

import cv2
import os
import sys
import random

# 這個使用opencv的程式碼還需要完善
# 需要更多的分類器,並且判斷準確的人臉後才儲存
# 這裡貼出來僅供參考

out_dir = './my_faces1'
if not os.path.exists(out_dir):
    os.makedirs(out_dir)

# 改變亮度與對比度
def relight(img, alpha=1, bias=0):
    w = img.shape[1]
    h = img.shape[0]
    #image = []
    for i in range(0,w):
        for j in range(0,h):
            for c in range(3):
                tmp = int(img[j,i,c]*alpha + bias)
                if tmp > 255:
                    tmp = 255
                elif tmp < 0:
                    tmp = 0
                img[j,i,c] = tmp
    return img


# 獲取分類器
haar = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# 開啟攝像頭 引數為輸入流,可以為攝像頭或視訊檔案
camera = cv2.VideoCapture(0)

n = 1
while 1:
    if (n <= 10000):
        print('It`s processing %s image.' % n)
        # 讀幀
        success, img = camera.read()

        gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        faces = haar.detectMultiScale(gray_img, 1.3, 5)
        for f_x, f_y, f_w, f_h in faces:
            face = img[f_y:f_y+f_h, f_x:f_x+f_w]
            face = cv2.resize(face, (64,64))
            '''
            if n % 3 == 1:
                face = relight(face, 1, 50)
            elif n % 3 == 2:
                face = relight(face, 0.5, 0)
            '''
            face = relight(face, random.uniform(0.5, 1.5), random.randint(-50, 50))
            cv2.imshow('img', face)
            cv2.imwrite(out_dir+'/'+str(n)+'.jpg', face)
            n+=1
        key = cv2.waitKey(30) & 0xff
        if key == 27:
            break
    else:
        break