keras实现简单性别识别(二分类问题)

第一步:准备好需要的库

第二步:准备数据集:

将性别不同的图片按照不同的分类放到不同的文件夹内。

数据集

https://pan.baidu.com/s/1_f36Gw4PWztUXZWH_jLWcw

  1. import shutil
  2.  
  3. # 读取文件中图片信息根据性别分类图片到对应目录中
  4. dirroot = "D:\\Users\\a\\Pictures\\adience"
  5. f = open(dirroot+"\\fold_frontal_3_data.txt","r")
  6. i = 0
  7.  
  8. for line in f.readlines():
  9. line = line.split()
  10. dir = line[0]
  11.  
  12. imgName = "landmark_aligned_face."+ line[2] +'.'+ line[1]
  13. if i > 0:
  14. if line[5]== "f":
  15. print("female")
  16. shutil.copy(dirroot+'\\faces\\'+dir+'\\'+imgName, "D:\\pycode\\learn\\data\\validation\\"+imgName)
  17. # 移动图片到female目录
  18. elif line[5]=="m":
  19. print("male")
  20. shutil.copy(dirroot+'\\faces\\'+dir+'\\'+imgName, "D:\\pycode\\learn\\data\\validation\\"+imgName)
  21. # 移动图片到male目录
  22. else:
  23. print("N")
  24. # 未识别男女
  25. i += 1
  26. f.close()

使用ImageDataGenerator,来对图片进行归一化和随机旋转。使用flow_from_directory,来自动产生图片标签生成器。

  1. class Dataset(object):
  2.  
  3. def __init__(self):
  4. self.train = None
  5. self.valid = None
  6.  
  7. def read(self, img_rows=IMAGE_SIZE, img_cols=IMAGE_SIZE):
  8. train_datagen = ImageDataGenerator(
  9. rescale=1. / 255,
  10. horizontal_flip=True)
  11.  
  12. test_datagen = ImageDataGenerator(rescale=1. / 255)
  13.  
  14. train_generator = train_datagen.flow_from_directory(
  15. train_data_dir,
  16. target_size=(img_rows, img_cols),
  17. batch_size=batch_size,
  18. class_mode='binary')
  19.  
  20. validation_generator = test_datagen.flow_from_directory(
  21. validation_data_dir,
  22. target_size=(img_rows, img_cols),
  23. batch_size=batch_size,
  24. class_mode='binary')
  25.  
  26. self.train = train_generator
  27. self.valid = validation_generator

第三部:网络

  1. class Model(object):
  2.  
  3. def __init__(self):
  4. self.model = Sequential()
  5. self.model.add(Conv2D(32, (3, 3), input_shape=(IMAGE_SIZE,IMAGE_SIZE,3)))
  6. self.model.add(Activation('relu'))
  7. self.model.add(MaxPooling2D(pool_size=(2, 2)))
  8.  
  9. self.model.add(Conv2D(32, (3, 3)))
  10. self.model.add(Activation('relu'))
  11. self.model.add(MaxPooling2D(pool_size=(2, 2)))
  12.  
  13. self.model.add(Conv2D(64, (3, 3)))
  14. self.model.add(Activation('relu'))
  15. self.model.add(MaxPooling2D(pool_size=(2, 2)))
  16.  
  17. self.model.add(Conv2D(64, (3, 3)))
  18. self.model.add(Activation('relu'))
  19. self.model.add(MaxPooling2D(pool_size=(2, 2)))
  20.  
  21. self.model.add(Flatten())
  22. self.model.add(Dense(64))
  23. self.model.add(Activation('relu'))
  24. self.model.add(Dropout(0.85))
  25. self.model.add(Dense(1))
  26. self.model.add(Activation('sigmoid'))
  27.  
  28. def train(self, dataset, batch_size=batch_size, nb_epoch=epochs):
  29.  
  30. self.model.compile(loss='binary_crossentropy',
  31. optimizer='adam',
  32. metrics=['accuracy'])
  33. self.model.fit_generator(dataset.train,
  34. steps_per_epoch=nb_train_samples // batch_size,
  35. epochs=epochs,
  36. validation_data=dataset.valid,
  37. validation_steps=nb_validation_samples//batch_size)
  38.  
  39. def save(self, file_path=FILE_PATH):
  40. print('Model Saved.')
  41. self.model.save_weights(file_path)
  42.  
  43. def load(self, file_path=FILE_PATH):
  44. print('Model Loaded.')
  45. self.model.load_weights(file_path)
  46.  
  47. def predict(self, image):
  48. # 预测样本分类
  49. img = image.resize((1, IMAGE_SIZE, IMAGE_SIZE, 3))
  50. img = image.astype('float32')
  51. img /= 255
  52.  
  53. #归一化
  54. result = self.model.predict(img)
  55. print(result)
  56. # 概率
  57. result = self.model.predict_classes(img)
  58. print(result)
  59. # 0/1
  60.  
  61. return result[0]
  62.  
  63. def evaluate(self, dataset):
  64. # 测试样本准确率
  65. score = self.model.evaluate_generator(dataset.valid,steps=2)
  66. print("样本准确率%s: %.2f%%" % (self.model.metrics_names[1], score[1] * 100))

第四部:主程序

  1. if __name__ == '__main__':
  2. dataset = Dataset()
  3. dataset.read()
  4.  
  5. model = Model()
  6. model.load()
  7. model.train(dataset)
  8. model.evaluate(dataset)
  9. model.save()

第五步:识别程序

opencv检测模块版

  1. #!/usr/bin/env python
  2. """
  3. 从摄像头中获取图像实时监测
  4. """
  5. import numpy as np
  6. import cv2
  7. from GenderTrain import Model
  8.  
  9. def detect(img, cascade):
  10. """
  11. 检测图像是否含有人脸部分
  12. :param img: 待检测帧图像
  13. :param cascade: 面部对象检测器
  14. :return: 面部图像标记
  15. """
  16. rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30),
  17. flags=cv2.CASCADE_SCALE_IMAGE)
  18. if len(rects) == 0:
  19. return []
  20. rects[:,2:] += rects[:,:2]
  21. return rects
  22.  
  23. def draw_rects(img, rects, color):
  24. """
  25. 根据图像标记人脸区域与性别
  26. :param img:
  27. :param rects:
  28. :param color:
  29. :return:
  30. """
  31. for x, y, w, h in rects:
  32. face = img[x:x+w,y:y+h]
  33. face = cv2.resize(face,(224,224))
  34. if gender.predict(face)==1:
  35. text = "Male"
  36. else:
  37. text = "Female"
  38. cv2.rectangle(img, (x, y), (w, h), color, 2)
  39. cv2.putText(img, text, (x, h), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), lineType=cv2.LINE_AA)
  40.  
  41. if __name__ == '__main__':
  42. haar__cascade_path = "D:\\opencv\\sources\\data\\haarcascades\\haarcascade_frontalface_default.xml"
  43.  
  44. cascade = cv2.CascadeClassifier( haar__cascade_path)
  45. cam = cv2.VideoCapture(0)
  46. # 获取摄像头视频
  47. gender = Model()
  48. gender.load()
  49. # 加载性别模型
  50. while True:
  51. ret, img = cam.read()
  52. # 读取帧图像
  53. rects = detect(img, cascade)
  54. print(rects)
  55. vis = img.copy()
  56. draw_rects(vis, rects, (0, 255, 0))
  57. cv2.imshow('Gender', vis)
  58. if cv2.waitKey(5) == 27:
  59. break
  60. cv2.destroyAllWindows()

MTCNN检测版

  1. """
  2. 从摄像头中获取图像实时监测
  3. """
  4. import PIL
  5. import numpy as np
  6. import detect_face
  7. import tensorflow as tf
  8. import cv2
  9. from GenderTrain import Model
  10.  
  11. with tf.Graph().as_default():
  12. gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.5)
  13. sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
  14. with sess.as_default():
  15. pnet, rnet, onet = detect_face.create_mtcnn(sess,
  16. 'E:\\pycode\\real-time-deep-face-recognition-master\\20170512-110547')
  17. minsize = 20 # minimum size of face
  18. threshold = [0.6, 0.7, 0.7] # three steps's threshold
  19. factor = 0.709 # scale factor
  20. margin = 44
  21. frame_interval = 3
  22. batch_size = 1000
  23. image_size = 182
  24. input_image_size = 160
  25.  
  26. def draw_rects(img, rects, color):
  27. """
  28. 根据图像标记人脸区域与性别
  29. :param img:
  30. :param rects:
  31. :param color:
  32. :return:
  33. """
  34. for x, y, w, h in rects:
  35. face = img[x:x+w,y:y+h]
  36. face = cv2.resize(face,(224,224))
  37. if gender.predict(face)==1:
  38. text = "Male"
  39. else:
  40. text = "Female"
  41. cv2.rectangle(img, (x, y), (w, h), color, 2)
  42. cv2.putText(img, text, (x, h), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), lineType=cv2.LINE_AA)
  43.  
  44. if __name__ == '__main__':
  45. cam = cv2.VideoCapture(0)
  46. # 获取摄像头视频
  47. gender = Model()
  48. gender.load()
  49. # 加载性别模型
  50. while True:
  51. ret, img = cam.read()
  52. # 读取帧图像
  53. bounding_boxes, _ = detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)
  54. # 读取帧图像
  55. for face_position in bounding_boxes:
  56. face_position = face_position.astype(int)
  57. print(face_position[0:4])
  58. rects = [[face_position[0], face_position[1], face_position[2], face_position[3]]]
  59. vis = img.copy()
  60. draw_rects(vis, rects, (255, 255, 255))
  61. cv2.imshow('Gender', vis)
  62. if cv2.waitKey(5) == 27:
  63. break
  64. cv2.destroyAllWindows()

完全版

  1. import os
  2. import random
  3. import cv2
  4. import numpy as np
  5. from tensorflow.contrib.keras.api.keras.preprocessing.image import ImageDataGenerator,img_to_array
  6. from tensorflow.contrib.keras.api.keras.models import Sequential
  7. from tensorflow.contrib.keras.api.keras.layers import Dense, Dropout, Activation, Flatten
  8. from tensorflow.contrib.keras.api.keras.layers import Conv2D, MaxPooling2D
  9. from tensorflow.contrib.keras.api.keras.optimizers import SGD
  10.  
  11. IMAGE_SIZE = 182
  12. # 训练图片大小
  13. epochs = 150#原来是50
  14. # 遍历次数
  15. batch_size = 32
  16. # 批量大小
  17. nb_train_samples = 512*2
  18. # 训练样本总数
  19. nb_validation_samples = 128*2
  20. # 测试样本总数
  21. train_data_dir = 'D:\\code\\learn\\data_sex\\train_data\\'
  22. validation_data_dir = 'D:\\data_sex\\test_data\\'
  23. # 样本图片所在路径
  24. FILE_PATH = 'Gender_new.h5'
  25. # 模型存放路径
  26. class Dataset(object):
  27.  
  28. def __init__(self):
  29. self.train = None
  30. self.valid = None
  31.  
  32. def read(self, img_rows=IMAGE_SIZE, img_cols=IMAGE_SIZE):
  33. train_datagen = ImageDataGenerator(
  34. rescale=1. / 255,
  35. horizontal_flip=True)
  36.  
  37. test_datagen = ImageDataGenerator(rescale=1. / 255)
  38.  
  39. train_generator = train_datagen.flow_from_directory(
  40. train_data_dir,
  41. target_size=(img_rows, img_cols),
  42. batch_size=batch_size,
  43. class_mode='binary')
  44.  
  45. validation_generator = test_datagen.flow_from_directory(
  46. validation_data_dir,
  47. target_size=(img_rows, img_cols),
  48. batch_size=batch_size,
  49. class_mode='binary')
  50.  
  51. self.train = train_generator
  52. self.valid = validation_generator
  53.  
  54. class Model(object):
  55.  
  56. def __init__(self):
  57. self.model = Sequential()
  58. self.model.add(Conv2D(32, (3, 3), input_shape=(IMAGE_SIZE,IMAGE_SIZE,3)))
  59. self.model.add(Activation('relu'))
  60. self.model.add(MaxPooling2D(pool_size=(2, 2)))
  61.  
  62. self.model.add(Conv2D(32, (3, 3)))
  63. self.model.add(Activation('relu'))
  64. self.model.add(MaxPooling2D(pool_size=(2, 2)))
  65.  
  66. self.model.add(Conv2D(64, (3, 3)))
  67. self.model.add(Activation('relu'))
  68. self.model.add(MaxPooling2D(pool_size=(2, 2)))
  69.  
  70. self.model.add(Flatten())
  71. self.model.add(Dense(64))
  72. self.model.add(Activation('relu'))
  73. self.model.add(Dropout(0.5))
  74. self.model.add(Dense(1))
  75. self.model.add(Activation('sigmoid'))
  76.  
  77. def train(self, dataset, batch_size=batch_size, nb_epoch=epochs):
  78.  
  79. self.model.compile(loss='binary_crossentropy',
  80. optimizer='adam',
  81. metrics=['accuracy'])
  82. self.model.fit_generator(dataset.train,
  83. steps_per_epoch=nb_train_samples // batch_size,
  84. epochs=epochs,
  85. validation_data=dataset.valid,
  86. validation_steps=nb_validation_samples//batch_size)
  87.  
  88. def save(self, file_path=FILE_PATH):
  89. print('Model Saved.')
  90. self.model.save_weights(file_path)
  91.  
  92. def load(self, file_path=FILE_PATH):
  93. print('Model Loaded.')
  94. self.model.load_weights(file_path)
  95.  
  96. def predict(self, image):
  97. # 预测样本分类
  98. img = image.resize((1, IMAGE_SIZE, IMAGE_SIZE, 3))
  99. img = image.astype('float32')
  100. img /= 255
  101.  
  102. #归一化
  103. result = self.model.predict(img)
  104. print(result)
  105. # 概率
  106. result = self.model.predict_classes(img)
  107. print(result)
  108. # 0/1
  109.  
  110. return result[0]
  111.  
  112. def evaluate(self, dataset):
  113. # 测试样本准确率
  114. score = self.model.evaluate_generator(dataset.valid,steps=2)
  115. print("样本准确率%s: %.2f%%" % (self.model.metrics_names[1], score[1] * 100))
  116.  
  117. if __name__ == '__main__':
  118. dataset = Dataset()
  119. dataset.read()
  120.  
  121. model = Model()
  122. model.load()
  123. model.train(dataset)
  124. model.evaluate(dataset)
  125. model.save()

keras实现简单性别识别(二分类问题)的更多相关文章

  1. keras框架下的深度学习(二)二分类和多分类问题

    本文第一部分是对数据处理中one-hot编码的讲解,第二部分是对二分类模型的代码讲解,其模型的建立以及训练过程与上篇文章一样:在最后我们将训练好的模型保存下来,再用自己的数据放入保存下来的模型中进行分 ...

  2. 1.keras实现-->自己训练卷积模型实现猫狗二分类(CNN)

    原数据集:包含 25000张猫狗图像,两个类别各有12500 新数据集:猫.狗 (照片大小不一样) 训练集:各1000个样本 验证集:各500个样本 测试集:各500个样本 1= 狗,0= 猫 # 将 ...

  3. 基于Keras的imdb数据集电影评论情感二分类

    IMDB数据集下载速度慢,可以在我的repo库中找到下载,下载后放到~/.keras/datasets/目录下,即可正常运行.)中找到下载,下载后放到~/.keras/datasets/目录下,即可正 ...

  4. [DeeplearningAI笔记]卷积神经网络4.1-4.5 人脸识别/one-shot learning/Siamase网络/Triplet损失/将面部识别转化为二分类问题

    4.4特殊应用:人脸识别和神经网络风格转换 觉得有用的话,欢迎一起讨论相互学习~Follow Me 4.1什么是人脸识别 Face verification人脸验证 VS face recogniti ...

  5. xgb, lgb, Keras, LR(二分类、多分类代码)

    preprocess # 通用的预处理框架 import pandas as pd import numpy as np import scipy as sp # 文件读取 def read_csv_ ...

  6. C++开发人脸性别识别教程(16)——视频人脸性别识别

    在之前的博文中我们已经可以顺利驱动摄像头来採集源图像.在这篇博文中将正式为其加入性别识别的代码,实现摄像头视频的人脸性别识别. 一.人脸检測 在得到摄像头採集的源图像之后,首先要做的就是对其进行人脸检 ...

  7. C++开发人脸性别识别教程(5)——通过FaceRecognizer类实现性别识别

    在之前的博客中已经攻克了人脸检測的问题,我们计划在这篇博客中介绍人脸识别.性别识别方面的相关实现方法. 事实上性别识别和人脸识别本质上是相似的,由于这里仅仅是一个简单的MFC开发,主要工作并不在算法研 ...

  8. 基于深度学习的人脸性别识别系统(含UI界面,Python代码)

    摘要:人脸性别识别是人脸识别领域的一个热门方向,本文详细介绍基于深度学习的人脸性别识别系统,在介绍算法原理的同时,给出Python的实现代码以及PyQt的UI界面.在界面中可以选择人脸图片.视频进行检 ...

  9. 基于OpenCV性别识别

    叙述性说明 所谓的性别识别推断检测到的面部是男性还是女性.它是一个二值分类问题. 识别算法可以用于SVM,BP神经网络.LDA,PCA,PCA+LDA等等.OpenCV官网给出的文档是基于Fisher ...

随机推荐

  1. JS基础:闭包和作用域链

    简介 一个定义在函数内部的函数与包含它的外部函数构成了闭包,内部函数可以访问外部函数的变量,这些变量将一直保存在内存中,直到无法再引用这个内部函数. 例如: var a = 0; function o ...

  2. Jenkins实现Android自动化打包

    转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/77102359 本文出自[赵彦军的博客] 1.Tomcat 进入 https://t ...

  3. erlang的脚本执行---escript

    1.概述: 作为程序员对于脚本语言应该很熟悉了,脚本语言的优点很多,如快速开发.容易编写.实时开发和执行, 我们常用的脚本有Javascript.shell.python等,我们的erlang语言也有 ...

  4. 建站记录:设置apache .htaccess文件给网站添加404错误处理页面

    有些空间服务商会在后台设置中,提供这个选项,可以直观地设置404错误指向的页面,这一点很方便,比如我之前用的阿里云虚拟主机就可以在控制台直接设置. 新租用的香港主机后台没有找到选取文件的地方,只是可以 ...

  5. Ubuntu下vim中文乱码

    在linux中,用vim打开包含中文的文件时,有可能出现乱码 下面的vim配置方法亲测有效 1. 找到你的vimrc文件,也有可能是.vimrc,我的服务器是vimrc,我改的是 有的说建议不要改全局 ...

  6. 嵌入Python系列 | 调用Python模块中无参数函数

    开发环境 Python版本:3.6.4 (32-bit) 编辑器:Visual Studio Code C++环境:Visual Studio 2013 需求说明 在用VS2013编写的Win32程序 ...

  7. TensorFlow源码安装

    前言 TensorFlow如果能二进制包安装,我真的不想选择自己编译,但是情况不由人,好不容易找到一台服务器,CPU不支持AVX指令集,安装的release版本运行到import tensorflow ...

  8. Visual Studio 201~ Code 格式检查

    前言 好的代码格式,有利于阅读和查错,慢慢的有利于养成良好的编码习惯,也可以帮我们找出一些低级错误. StyleCop 在Nuget上搜索stylecop,选择MSBuild的那个版本,安装. 手动编 ...

  9. Http Header信息

    REMOTE_ADDR – 访问客户端的 IP 地址 HTTP_VIA – 如果有该条信息, 就证明您使用了代理服务器,代理服务器的地址就是后面的数值. HTTP_X_FORWARDED_FOR – ...

  10. strace详解及实战

    详细参数: -c 统计每一系统调用的所执行的时间,次数和出错的次数等. -d 输出strace关于标准错误的调试信息. -f 跟踪由fork调用所产生的子进程. -ff 如果提供-o filename ...