基于TensorFlow深度学习⼈脸识别源码级项⽬实战
⽂章⽬录
前⾔
⼈脸年龄识别属于⼈脸属性识别的范畴,⼈脸属性识别可对图⽚中的⼈脸进⾏检测定位,并识别出⼈脸的相关属性(如年龄、性别、表情、种族、颜值等)内容。不同属性识别的算法可以相同,也可以不同。rude-carnie是做年龄识别和性别识别的⼀个开源项⽬,基于TensorFlow,源代码⽹址:www.github/dpressel/rude-carnie。下⾯我们基于这个项⽬源码来讲年龄识别。
⼀、年龄识别核⼼代码guess.py
我们可以把年龄划分为⼏个段[’(0, 2)’,’(4, 6)’,’(8, 12)’,’(15, 20)’,’(25, 32)’,’(38, 43)’,’(48, 53)’,’(60, 100)’],然后基于分类的思想来做年龄预测问题。⽤下⾯的脚本命令:
python3 guess.py --model_type inception --model_dir /home/hadoop/chongdianleme/ nianling/22801/inception/22801 --filename /home/hadoop/chongdianleme/data/myimages/baidu1.jpg
另外⼀个问题是,因为训练的模型⽤的是开源项⽬训练好的,是拿外国⼈的⼈脸数据训练,这样⽤来
预测我们中国⼈的年龄会有⼀些差异,最好的⽅式是拿我们中国⼈⾃⼰的⼈脸年龄数据做训练,这样预测才会更好。
针对年龄识别和性别识别都是⽤guess.py这个⽂件,年龄识别是多分类,性别是⼆分类。我们看下guess.py的源码,如代码8.5所⽰:
零基础学java编程【代码8.5】 guess.py
代码如下(⽰例):
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import math
import time
from data import inputs
import numpy as np
import tensorflow as tf
from model import select_model, get_checkpoint
from utils import *
import os
import json
import csv
RESIZE_FINAL =227
#性别有两个
GENDER_LIST =['M','F']
#年龄是分段的,可以看成多分类任务
AGE_LIST =['(0, 2)','(4, 6)','(8, 12)','(15, 20)','(25, 32)','(38, 43)','(48, 53)','(60, 100)']
MAX_BATCH_SZ =128
#模型⽂件⽬录
tf.app.flags.DEFINE_string('model_dir','',
'Model directory (where training data lives)')
#性别和年龄都是⽤的这个,通过参数age|gender来区分
tf.app.flags.DEFINE_string('class_type','age',
'Classification type (age|gender)')
#⽤cpu还是⽤GPU来训练
tf.app.flags.DEFINE_string('device_id','/cpu:0',
'What processing unit to execute inference on')
tf.app.flags.DEFINE_string('filename','',
'File (Image) or File list (Text/No header TSV) to process')
tf.app.flags.DEFINE_string('target','',
'CSV file containing the filename processed along with best guess and score')
#检查点
#检查点
tf.app.flags.DEFINE_string('checkpoint','checkpoint',
'Checkpoint basename')
tf.app.flags.DEFINE_string('model_type','default',
'Type of convnet')
tf.app.flags.DEFINE_string('requested_step','','Within the model directory, a requested step to , 9000') tf.app.flags.DEFINE_boolean('single_look', False,'single look at the image or multiple crops')
tf.app.flags.DEFINE_string('face_detection_model','','Do frontal face detection with model specified')
tf.app.flags.DEFINE_string('face_detection_type','cascade','Face detection model type (yolo_tiny|cascade)') FLAGS = tf.app.flags.FLAGS
def one_of(fname, types):
return any([dswith('.'+ ty)for ty in types])
def resolve_file(fname):
if ists(fname):return fname
for suffix in ('.jpg','.png','.JPG','.PNG','.jpeg'):
cand = fname + suffix
if ists(cand):
return cand
return None
def classify_many_single_crop(sess, label_list, softmax_output, coder, images, image_files, writer):
try:
num_batches = il(len(image_files)/ MAX_BATCH_SZ)
pg =ProgressBar(num_batches)
for j in range(num_batches):
start_offset = j * MAX_BATCH_SZ
end_offset =min((j +1)* MAX_BATCH_SZ,len(image_files))
batch_image_files = image_files[start_offset:end_offset]
print(start_offset, end_offset,len(batch_image_files))
image_batch =make_multi_image_batch(batch_image_files, coder)
batch_results = sess.run(softmax_output, feed_dict={images:image_batch.eval()})
batch_sz = batch_results.shape[0]
for i in range(batch_sz):
output_i = batch_results[i]
best_i = np.argmax(output_i)
best_choice =(label_list[best_i], output_i[best_i])
print('Guess @ 1 %s, prob = %.2f'% best_choice)
if writer is not None:
f = batch_image_files[i]
writer.writerow((f, best_choice[0],'%.2f'% best_choice[1]))
pg.update()
pg.done()
except Exception as e:
print(e)
print('Failed to run all images')
def classify_one_multi_crop(sess, label_list, softmax_output, coder, images, image_file, writer):
try:
print('Running file %s'% image_file)
image_batch =make_multi_crop_batch(image_file, coder)
batch_results = sess.run(softmax_output, feed_dict={images:image_batch.eval()})
output = batch_results[0]
batch_sz = batch_results.shape[0]
for i in range(1, batch_sz):
output = output + batch_results[i]
output /= batch_sz
best = np.argmax(output)
best_choice =(label_list[best], output[best])
print('Guess @ 1 %s, prob = %.2f'% best_choice)
print('Guess @ 1 %s, prob = %.2f'% best_choice)
nlabels =len(label_list)
if nlabels >2:
output[best]=0
second_best = np.argmax(output)
print('Guess @ 2 %s, prob = %.2f'%(label_list[second_best], output[second_best]))
if writer is not None:
writer.writerow((image_file, best_choice[0],'%.2f'% best_choice[1]))
except Exception as e:
print(e)
print('Failed to run image %s '% image_file)
def list_images(srcfile):
with open(srcfile,'r') as csvfile:
delim =','dswith('.csv')else'\t'
reader = ader(csvfile, delimiter=delim)
dswith('.csv') dswith('.tsv'):
print('skipping header')
_ =next(reader)
return[row[0]for row in reader]
def main(argv=None): # pylint: disable=unused-argument
files =[]
print("target %s"% FLAGS.target)
if FLAGS.face_detection_model:
print('Using face detector (%s) %s'%(FLAGS.face_detection_type, FLAGS.face_detection_model))
face_detect =face_detection_model(FLAGS.face_detection_type, FLAGS.face_detection_model)
face_files, rectangles = face_detect.run(FLAGS.filename)
print(face_files)
files += face_files
config = tf.ConfigProto(allow_soft_placement=True)
with tf.Session(config=config) as sess:
label_list = AGE_LIST if FLAGS.class_type =='age'else GENDER_LIST
nlabels =len(label_list)
print('Executing on %s'% FLAGS.device_id)
model_fn =select_del_type)
with tf.device(FLAGS.device_id):
images = tf.placeholder(tf.float32,[None, RESIZE_FINAL, RESIZE_FINAL,3])
logits =model_fn(nlabels, images,1, False)
init = tf.global_variables_initializer()
requested_step = quested_step quested_step else None
checkpoint_path ='%s'%(del_dir)
model_checkpoint_path, global_step =get_checkpoint(checkpoint_path, requested_step, FLAGS.checkpoint)
saver = tf.train.Saver()
softmax_output = tf.nn.softmax(logits)
coder =ImageCoder()
# Support a batch mode if no face detection model
if len(files)==0:
if(os.path.isdir(FLAGS.filename)):
for relpath in os.listdir(FLAGS.filename):
abspath = os.path.join(FLAGS.filename, relpath)
if os.path.isfile(abspath) and any([dswith('.'+ ty)for ty in ('jpg','png','JPG','PNG','jpeg')]):
print(abspath)
print(abspath)
files.append(abspath)
else:
files.append(FLAGS.filename)
# If it happens to be a list file, read the list and clobber the files
if any([dswith('.'+ ty)for ty in ('csv','tsv','txt')]):
files =list_images(FLAGS.filename)
writer = None
output = None
if FLAGS.target:
print('Creating output file %s'% FLAGS.target)
output =open(FLAGS.target,'w')
writer = csv.writer(output)
writer.writerow(('file','label','score'))
image_files =list(filter(lambda x: x is not None,[resolve_file(f)for f in files]))
print(image_files)
if FLAGS.single_look:
classify_many_single_crop(sess, label_list, softmax_output, coder, images, image_files, writer)
else:
for image_file in image_files:
classify_one_multi_crop(sess, label_list, softmax_output, coder, images, image_file, writer)
if output is not None:
output.close()
if __name__ =='__main__':
tf.app.run()
⼆、年龄识别Web⼯程化代码
年龄识别我们对外提供⼀个Web接⼝,guessAgeWeb_chongdianleme.py如代码8.6所⽰:【代码8.6】 guessAgeWeb_chongdianleme.py
代码如下(⽰例):
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from datetime import datetime
import math
import time
from data import inputs
import numpy as np
import tensorflow as tf
from model import select_model, get_checkpoint
from utils import *
import os
import csv
#pip3 install flask
from flask import Flask
from flask import request
import urllib
# pip3 install requests
import requests, quest
from scipy import misc
import argparse
import facenet
import align.detect_face
import json
RESIZE_FINAL =227
#性别有两个
GENDER_LIST =['M','F']
GENDER_LIST =['M','F']
#年龄是分段的,可以看成多分类任务
AGE_LIST =['(0, 2)','(4, 6)','(8, 12)','(15, 20)','(25, 32)','(38, 43)','(48, 53)','(60, 100)']
MAX_BATCH_SZ =128
def one_of(fname, types):
return any([dswith('.'+ ty)for ty in types])
def resolve_file(fname):
if ists(fname):return fname
for suffix in ('.jpg','.png','.JPG','.PNG','.jpeg'):
cand = fname + suffix
if ists(cand):
return cand
return None
def list_images(srcfile):
with open(srcfile,'r') as csvfile:
delim =','dswith('.csv')else'\t'
reader = ader(csvfile, delimiter=delim)
dswith('.csv') dswith('.tsv'):
print('skipping header')
_ =next(reader)
return[row[0]for row in reader]
# 初始化
class_type ='age'
device_id ="/cpu:0"
model_type ="inception"
requested_step =""
#模型⽂件⽬录
model_dir ="/home/hadoop/chongdianleme/nianling/22801/inception/22801"
checkpoint ="checkpoint"
config = tf.ConfigProto(allow_soft_placement=True)
sess = tf.Session(config=config)
with sess.as_default():
label_list = AGE_LIST if class_type =='age'else GENDER_LIST
nlabels =len(label_list)
model_fn =select_model(model_type)
images = tf.placeholder(tf.float32,[None, RESIZE_FINAL, RESIZE_FINAL,3])
logits =model_fn(nlabels, images,1, False)
init = tf.global_variables_initializer()
requested_step = requested_step if requested_step else None
checkpoint_path ='%s'%(model_dir)
model_checkpoint_path, global_step =get_checkpoint(checkpoint_path, requested_step, checkpoint) saver = tf.train.Saver()
softmax_output = tf.nn.softmax(logits)
coder =ImageCoder()
def _is_png(filename):
return'.png' in filename
app =Flask(__name__)
@ute('/predictAge', methods=['GET','POST'])
def prediction():
start = time.time()
imageUrl = ("imageUrl")
#⽤户信息
device = ("device")
userid = ("userid")
urlType = ("urlType")
imageType = ("imageType")
files =[]
#⽀持本地图⽚和⽹络图⽚
if urlType=="local":
filename = imageUrl
else:
baseImageName = os.path.basename(imageUrl)
filename ="/home/hadoop/chongdianleme/ageimage/%s"% baseImageName
filename = filename+imageType

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。