创新实训项目:目的是在手机端实现用户手势的检测并且识别用户所做的手势
遇到的问题:
首先在手部检测的解决办法中,我尝试过用opencv进行手部识别,但存在的问题是背景对手的识别的影响太大,如果采用颜色进行手和背景的区分的话,又会受到光照等影响,总体而言效果不好。
之后转向使用机器学习方法进行识别。
在寻找可用的手部检测的代码中花了很长时间,试了几个github上的项目因为种种问题不能运行。
考虑过使用openpose框架进行手部的识别,虽然准确度高但是很吃GPU,所以希望寻找对性能要求低的模型进行改进。
最终在 这里 找到了通过卷积神经网络训练后的可用的手识别的项目。
下面是改编和使用该项目,并且在其基础上进行手势分类的过程:
一.对 这里 项目进行的改进
1.首先由于要取识别出来的手部图片进行图片分类操作,先将 config.py 文件中的 DEMO_TYPE 设置为DEMO_TYPE = 'MULTI'
就可以显示出如图图片
2.接着将上图的左右两个图片的输出改为单一图片输出
在 run_demo_hand_with_tracker.py 中 将main方法中 if ('multi')分支中的imshow语句更改为cv2.imshow('local_img', local_img.astype(np.uint8))
即取消了list的合并
3.运行run_demo_hand_with_tracker.py,保存当前手势图片
在上述imshow方法下面加上保存图片的语句cv2.imwrite('你的路径'+'.jpg', local_img.astype(np.uint8), [int(cv2.IMWRITE_JPEG_QUALITY), 90])
即可在输出文件夹中得到类似下面的图片集
4.自行录入多种手势进行训练
在这里我录入了6种手势
每种手势600多张,一共4038张的图片作为数据集进行手势分类的训练
数据集被我保存在项目目录下的 classify -- handGesturePic目录下,共6个子目录
二.对上述数据集进行分类操作
1.搭建cnn网络
学习参考 点击打开链接 这篇博客的花图片的分类
具体实现代码 classmain.py :# -*- coding: utf-8 -*-
from skimage import io, transform
import glob
import os
import tensorflow as tf
import numpy as np
import time
path = './handGesturePic/'
# 模型保存地址
model_path='./modelSave/model.ckpt'
# 将所有的图片resize成100*100
w = 100
h = 100
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):
print('reading the images:%s' % (folder))
for im in glob.glob(folder + '/*.jpg'):
img = io.imread(im)
img = transform.resize(img, (w, h))
imgs.append(img)
labels.append(idx)
return np.asarray(imgs, np.float32), np.asarray(labels, np.int32)
data, label = read_img(path) # data 4038*(100,100,3) label 4038个0~5
# 打乱顺序
num_example = data.shape[0] # 4038
arr = np.arange(num_example) # [ 0 1 2 ... 4037]
np.random.shuffle(arr) # 将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_')
# 100×100×3->100×100×32->50×50×32->50×50×64->25×25×64->25×25×128->12×12×128->12×12×128->6×6×128
def inference(input_tensor, train, regularizer): # regularizer = tf.contrib.layers.l2_regularizer(0.0001)
'''
tf.nn.conv2d(input, filter, strides(步长,一般为1 :[1, 1, 1, 1]), padding, use_cudnn_on_gpu=None, data_format=None, name=None)
input的张量[batch, in_height, in_width, in_channels]
过滤器 / 内核张量 [filter_height, filter_width(filter大小), in_channels(输入通道), out_channels(输出通道)]
执行以下操作:
展平filter为一个形状为[filter_height * filter_width * in_channels, output_channels]的二维矩阵。
从input中按照filter大小提取图片子集形成一个大小为[batch, out_height, out_width, filter_height * filter_width * in_channels]的虚拟张量。
循环每个图片子集,右乘filter矩阵。
'''
with tf.variable_scope('layer1-conv1'):
conv1_weights = tf.get_variable("weight", [5, 5, 3, 32], initializer=tf.truncated_normal_initializer(stddev=0.1))
conv1_biases = tf.get_variable("bias", [32], initializer=tf.constant_initializer(0.0))
conv1 = tf.nn.conv2d(input_tensor, conv1_weights, strides=[1, 1, 1, 1], padding='SAME')
# 当padding=SAME时,输入与输出形状相同
relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_biases))
with tf.name_scope("layer2-pool1"):
pool1 = tf.nn.max_pool(relu1, ksize=[1,2,2,1],strides=[1,2,2,1],padding="VALID")
with tf.variable_scope("layer3-conv2"):
conv2_weights = tf.get_variable("weight", [5, 5, 32, 64], initializer=tf.truncated_normal_initializer(stddev=0.1))
conv2_biases = tf.get_variable("bias", [64], initializer=tf.constant_initializer(0.0))
conv2 = tf.nn.conv2d(pool1, conv2_weights, strides=[1, 1, 1, 1], padding='SAME')
relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_biases))
with tf.name_scope("layer4-pool2"):
pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
with tf.variable_scope("layer5-conv3"):
conv3_weights = tf.get_variable("weight", [3, 3, 64, 128], initializer=tf.truncated_normal_initializer(stddev=0.1))
conv3_biases = tf.get_variable("bias", [128], initializer=tf.constant_initializer(0.0))
conv3 = tf.nn.conv2d(pool2, conv3_weights, strides=[1, 1, 1, 1], padding='SAME')
relu3 = tf.nn.relu(tf.nn.bias_add(conv3, conv3_biases))
with tf.name_scope("layer6-pool3"):
pool3 = tf.nn.max_pool(relu3, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
with tf.variable_scope("layer7-conv4"):
conv4_weights = tf.get_variable("weight",[3,3,128,128],initializer=tf.truncated_normal_initializer(stddev=0.1))
conv4_biases = tf.get_variable("bias", [128], initializer=tf.constant_initializer(0.0))
conv4 = tf.nn.conv2d(pool3, conv4_weights, strides=[1, 1, 1, 1], padding='SAME')
relu4 = tf.nn.relu(tf.nn.bias_add(conv4, conv4_biases))
with tf.name_scope("layer8-pool4"):
pool4 = tf.nn.max_pool(relu4, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='VALID')
nodes = 6*6*128
reshaped = tf.reshape(pool4,[-1,nodes])
with tf.variable_scope('layer9-fc1'):
fc1_weights = tf.get_variable("weight", [nodes, 1024],
initializer=tf.truncated_normal_initializer(stddev=0.1))
if regularizer != None: tf.add_to_collection('losses', regularizer(fc1_weights))
# tf.add_to_collection向当前计算图中添加张量集合
fc1_biases = tf.get_variable("bias", [1024], initializer=tf.constant_initializer(0.1))
fc1 = tf.nn.relu(tf.matmul(reshaped, fc1_weights) + fc1_biases)
if train: fc1 = tf.nn.dropout(fc1, 0.5)
with tf.variable_scope('layer10-fc2'):
fc2_weights = tf.get_variable("weight", [1024, 512],
initializer=tf.truncated_normal_initializer(stddev=0.1))
if regularizer != None: tf.add_to_collection('losses', regularizer(fc2_weights))
fc2_biases = tf.get_variable("bias", [512], initializer=tf.constant_initializer(0.1))
fc2 = tf.nn.relu(tf.matmul(fc1, fc2_weights) + fc2_biases)
if train: fc2 = tf.nn.dropout(fc2, 0.5)
with tf.variable_scope('layer11-fc3'):
fc3_weights = tf.get_variable("weight", [512, 6],
initializer=tf.truncated_normal_initializer(stddev=0.1))
if regularizer != None: tf.add_to_collection('losses', regularizer(fc3_weights))
fc3_biases = tf.get_variable("bias", [6], initializer=tf.constant_initializer(0.1))
logit = tf.matmul(fc2, fc3_weights) + fc3_biases
return logit
# ---------------------------网络结束---------------------------
regularizer = tf.contrib.layers.l2_regularizer(0.0001) # 返回一个执行L2正则化的函数.在损失函数上加上正则项是防止过拟合的一个重要方法
logits = inference(x, False, regularizer)
# (小处理)将logits乘以1赋值给logits_eval,定义name,方便在后续调用模型时通过tensor名字调用输出tensor
b = tf.constant(value=1, dtype=tf.float32)
logits_eval = tf.multiply(logits, b, name='logits_eval')
loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=y_)
train_op = tf.train.AdamOptimizer(learning_rate=0.001).minimize(loss)
correct_prediction = tf.equal(tf.cast(tf.argmax(logits, 1), tf.int32), y_)
# tf.equal Returns:A `Tensor` of type `bool`.
# tf.cast :Casts a tensor to a new type. Returns:A `Tensor` or `SparseTensor` with same shape as `x`.(shape相同只改变type)
acc = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
# 定义一个函数,按批次取数据
def minibatches(inputs=None, targets=None, batch_size=None, shuffle=False):
assert len(inputs) == len(targets)
if shuffle:
indices = np.arange(len(inputs))
np.random.shuffle(indices)
for start_idx in range(0, len(inputs) - batch_size + 1, batch_size):
if shuffle:
excerpt = indices[start_idx:start_idx + batch_size]
else:
excerpt = slice(start_idx, start_idx + batch_size)
yield inputs[excerpt], targets[excerpt]
# 训练和测试数据,可将n_epoch设置更大一些
n_epoch=10
batch_size=64
saver=tf.train.Saver()
sess=tf.Session()
sess.run(tf.global_variables_initializer())
for epoch in range(n_epoch):
start_time = time.time()
# training
train_loss, train_acc, n_batch = 0, 0, 0
for x_train_a, y_train_a in minibatches(x_train, y_train, batch_size, shuffle=True):
_, err, ac = sess.run([train_op,loss,acc], feed_dict={x: x_train_a, y_: y_train_a})
train_loss += err
train_acc += ac
n_batch += 1
print("----------------epoch: %f-------------------" % epoch)
print(" train loss: %f" % (np.sum(train_loss) / n_batch))
print(" train acc: %f" % (np.sum(train_acc) / n_batch))
# validation
val_loss, val_acc, n_batch = 0, 0, 0
for x_val_a, y_val_a in minibatches(x_val, y_val, batch_size, shuffle=False):
err, ac = sess.run([loss,acc], feed_dict={x: x_val_a, y_: y_val_a})
val_loss += err
val_acc += ac
n_batch += 1
print(" validation loss: %f" % (np.sum(val_loss) / n_batch))
print(" validation acc: %f" % (np.sum(val_acc) / n_batch))
print('\n')
saver.save(sess, model_path)
sess.close()
注意在最后一层全连接输出中(layer11-fc3),要根据你所要分类的类别数目更改输出的维度,在这里我设置成了6
代码中的n_epoch变量控制整个训练集训练的轮数,我设置成了10(训练的硬件环境为1080ti,因为数据量小,用时大约5分钟)
十轮训练之后,准确率如下
在训练集中准确率为100%,在测试集中为98.3%
分类的模型参数保存在项目目录下的 classify -- modelSave 中
2.使用上述训练后的模型进行手势识别分类
useClassifyModel.pyfrom skimage import io,transform
import tensorflow as tf
import numpy as np
path1 = "./storePic/5.jpg"
path2 = "./storePic/7.jpg"
path3 = "./storePic/102304.jpg"
path4 = "./storePic/12034.jpg"
path5 = "./storePic/ok.jpg"
path6 = "./storePic/2.jpg"
dict = {0:'5',1:'7',2:'12034',3:'ok',4:'102304',5:'2'}
w=100
h=100
c=3
def read_one_image(path):
img = io.imread(path)
img = transform.resize(img,(w,h))
return np.asarray(img)
with tf.Session() as sess:
data = []
data1 = read_one_image(path1)
data2 = read_one_image(path2)
data3 = read_one_image(path3)
data4 = read_one_image(path4)
data5 = read_one_image(path5)
data6 = read_one_image(path6)
data.append(data1)
data.append(data2)
data.append(data3)
data.append(data4)
data.append(data5)
data.append(data6)
saver = tf.train.import_meta_graph('./classify/modelSave/model.ckpt.meta')
saver.restore(sess,tf.train.latest_checkpoint('./classify/modelSave/'))
graph = tf.get_default_graph()
x = graph.get_tensor_by_name("x:0")
feed_dict = {x:data}
logits = graph.get_tensor_by_name("logits_eval:0")
classification_result = sess.run(logits,feed_dict)
# 打印出预测矩阵
print(classification_result)
# 打印出预测矩阵每一行最大值的索引
print(tf.argmax(classification_result, 1).eval())
# 根据索引通过字典对应花的分类
output = []
output = tf.argmax(classification_result, 1).eval()
for i in range(len(output)):
print("第",i+1,"个手势预测:"+dict[output[i]])
输出结果
可以看到预测跟输入的图片对应是十分准确的
完整的项目代码在 我的github 中