python+opencv实现人脸识别笔记三(训练模型+保存模型)
2019-05-07 20:26
751 查看
一
在进行训练之前,我们首先需要对图片进行修改,使其长宽相等。
新建 训练模型.py
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 = '/home/dong/PycharmProjects/untitled/人脸识别/data/me' other_faces_path = '/home/dong/PycharmProjects/untitled/人脸识别/data/zhang' 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 # 相当于 h-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.3, 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() ''' out = tf.nn.softmax(out) #归一化 c1 = -tf.reduce.sum(y_*tf.log(out1)) cross_entropy = tf.reduce_mean(c1) ''' cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=out, labels=y_)) # 梯度下降函数,优化器就会按照循环的次数一次次沿着loss最小值的方向优化参数了。 # train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss) 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()) for n in range(10): # 每次取12(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}) # 打印损失 acc = accuracy.eval({x: test_x, y_: test_y, keep_prob_5: 1.0, keep_prob_75: 1.0}) print(n * num_batch + i, loss, acc) 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) # 准确率大于0.98时保存并退出 if acc > 0.98 and n > 2: saver.save(sess, '/home/dong/PycharmProjects/untitled/FaceRecognition-tensorflow/模型/train_faces.model', global_step=n * num_batch + i) sys.exit(0) print('accuracy less 0.98, exited!') cnnTrain()
这是我的训练结果
准确率相当高
相关文章推荐
- 人脸检测及识别python实现系列(3)——为模型训练准备人脸数据
- python+opencv实现人脸识别笔记四(识别出人脸)
- TensorFlow实现人脸识别(4)--------对人脸样本进行训练,保存人脸识别模型
- Python+opencv实现调取摄像头识别人脸,并将人脸转化为灰度图并保存到本地
- 人脸检测及识别python实现系列(5)——利用keras库训练人脸识别模型
- 人脸检测及识别python实现系列(3)——为模型训练准备人脸数据
- TensorFlow实现人脸识别(5)-------利用训练好的模型实时进行人脸检测
- 深度学习(一)——deepNN模型实现摄像头实时识别人脸表情(C++和python3.6混合编程)
- 【图像识别】 Python+Opencv调用摄像头实现人脸识别并保存视频
- OpenCV3计算机视觉Python语言实现人脸识别笔记
- python下实现人脸识别(opencv2)
- 深度人脸识别的 Caffe 实现(附模型开源地址及论文下载)
- OpenCV + Python 实现人脸识别
- OpenCV实践之路——人脸识别之二模型训练
- 百度DMLC分布式深度机器学习开源项目(简称“深盟”)上线了如xgboost(速度快效果好的Boosting模型)、CXXNET(极致的C++深度学习库)、Minerva(高效灵活的并行深度学习引擎)以及Parameter Server(一小时训练600T数据)等产品,在语音识别、OCR识别、人脸识别以及计算效率提升上发布了多个成熟产品。
- 静态图片人脸识别 OpenCV3,Python3实现
- Python3结合Dlib实现人脸识别和剪切
- 主成分分析 (PCA) 与其高维度下python实现(简单人脸识别)
- 人脸检测及识别python实现系列(4)——卷积神经网络(CNN)入门