环境介绍:
任何东西的起步都是把它的环境给搭建好,关于tensorflow的环境搭建网上一众博客这里就不多说了,自己使用的是Anaconda那套安装流程。这次代码还需要的一些其他python库,大家可以在跑的时候发现哪个no moudle了在install即可。
总的来说代码的大致情况如下:
1.搭建工具:windows +tensorflow 1.4.0 + python 3.5 + opencv3
2.训练代码:test3.py
训练的代码cmd运行就好了,你要做的就是双手离开键盘睡一觉第二天就能跑完。训练后的模型保存为ckpt1 文件夹,里面有四种文件
上面两幅图截取自test3.py运行以后的cmd截图,经过很久的运行时间就会在ckpt1文件夹得到需要的文件了。
识别的代码运行就不放上来啦(就不爆照了hhhh)
That's all
附上两个python源码:
test3.py
- # -*- coding: utf-8 -*-
- from skimage import io,transform
- import glob
- import os
- import tensorflow as tf
- import numpy as np
- import time
- path='D:/code/python/Anaconda3/envs/faces'
- #将所有的图片resize成100*100
- w=128
- h=128
- c=3
- #读取图片
- def read_img(path):
- cate=[path+'/'+x for x in os.listdir(path) if os.path.isdir(path+'/'+x)]
- imgs=[]
- labels=[]
- for idx,folder in enumerate(cate):
- for im in glob.glob(folder+'/*.png'):
- print('reading the images:%s'%(im))
- img=io.imread(im)
- img=transform.resize(img,(w,h,c))
- imgs.append(img)
- labels.append(idx)
- return np.asarray(imgs,np.float32),np.asarray(labels,np.int32)
- data,label=read_img(path)
- #打乱顺序
- num_example=data.shape[0]
- arr=np.arange(num_example)
- np.random.shuffle(arr)
- data=data[arr]
- label=label[arr]
- #将所有数据分为训练集和验证集
- ratio=0.8
- s=np.int(num_example*ratio)
- x_train=data[:s]
- y_train=label[:s]
- x_val=data[s:]
- y_val=label[s:]
- #-----------------构建网络----------------------
- #占位符
- x=tf.placeholder(tf.float32,shape=[None,w,h,c],name='x')
- y_=tf.placeholder(tf.int32,shape=[None,],name='y_')
- def CNNlayer():
- #第一个卷积层(128——>64)
- conv1=tf.layers.conv2d(
- inputs=x,
- filters=32,
- kernel_size=[5, 5],
- padding="same",
- activation=tf.nn.relu,
- kernel_initializer=tf.truncated_normal_initializer(stddev=0.01))
- pool1=tf.layers.max_pooling2d(inputs=conv1, pool_size=[2, 2], strides=2)
- #第二个卷积层(64->32)
- conv2=tf.layers.conv2d(
- inputs=pool1,
- filters=64,
- kernel_size=[5, 5],
- padding="same",
- activation=tf.nn.relu,
- kernel_initializer=tf.truncated_normal_initializer(stddev=0.01))
- pool2=tf.layers.max_pooling2d(inputs=conv2, pool_size=[2, 2], strides=2)
- #第三个卷积层(32->16)
- conv3=tf.layers.conv2d(
- inputs=pool2,
- filters=128,
- kernel_size=[3, 3],
- padding="same",
- activation=tf.nn.relu,
- kernel_initializer=tf.truncated_normal_initializer(stddev=0.01))
- pool3=tf.layers.max_pooling2d(inputs=conv3, pool_size=[2, 2], strides=2)
- #第四个卷积层(16->8)
- conv4=tf.layers.conv2d(
- inputs=pool3,
- filters=128,
- kernel_size=[3, 3],
- padding="same",
- activation=tf.nn.relu,
- kernel_initializer=tf.truncated_normal_initializer(stddev=0.01))
- pool4=tf.layers.max_pooling2d(inputs=conv4, pool_size=[2, 2], strides=2)
- re1 = tf.reshape(pool4, [-1, 8 * 8 * 128])
- #全连接层
- dense1 = tf.layers.dense(inputs=re1,
- units=1024,
- activation=tf.nn.relu,
- kernel_initializer=tf.truncated_normal_initializer(stddev=0.01),