Python --- 笑脸检测+口罩人脸识别
笑脸检测-口罩人脸识别
- 一、笑脸数据集(genki4k)正负样本的划分、模型训练和测试的过程(至少包括SVM、CNN),输出模型训练精度和测试精度(F1-score和ROC)
- 1.数据集下载
- 2.训练数据集
- 1) 导入Keras
- 2) 读取数据集,训练
- 3) 将笑脸图片和非笑脸图片放入对应文件夹
- 4) 打印数据集中笑脸和非笑脸图片数
- 5) 构建小型卷积神经网络
- 6) 数据预处理
- 7) 训练模型
- 8) 数据增强
- 3.摄像头实时笑脸识别
- 二、将数据集换为口罩数据集,并进行训练,实现佩戴口罩的人脸识别
- 1.口罩数据集下载
- 2.口罩佩戴的人脸识别
- 参考文献
一、笑脸数据集(genki4k)正负样本的划分、模型训练和测试的过程(至少包括SVM、CNN),输出模型训练精度和测试精度(F1-score和ROC)
1.数据集下载
笑脸数据集下载链接:https://pan.baidu.com/s/1ldA8CF6pH4q0Bheik_Tttg
提取码:fui1
2.训练数据集
1) 导入Keras
import keras
keras.__version__
2) 读取数据集,训练
import os, shutil
# The path to the directory where the original
# dataset was uncompressed
original_dataset_dir = 'smileface/genki4k'# The directory where we will
# store our smaller dataset
base_dir = 'smileface/smile_and_nosmile'
os.mkdir(base_dir)# Directories for our training,
# validation and test splits
train_dir = os.path.join(base_dir, 'train')
os.mkdir(train_dir)
validation_dir = os.path.join(base_dir, 'validation')
os.mkdir(validation_dir)
test_dir = os.path.join(base_dir, 'test')
os.mkdir(test_dir)# Directory with our training smile pictures
train_smile_dir = os.path.join(train_dir, 'smiles')
os.mkdir(train_smile_dir)# Directory with our training nosmile pictures
train_nosmile_dir = os.path.join(train_dir, 'no_smiles')
os.mkdir(train_nosmile_dir)# Directory with our validation smile pictures
validation_smile_dir = os.path.join(validation_dir, 'smiles')
os.mkdir(validation_smile_dir)# Directory with our validation nosmile pictures
validation_nosmile_dir = os.path.join(validation_dir, 'no_smiles')
os.mkdir(validation_nosmile_dir)# Directory with our validation smile pictures
test_smile_dir = os.path.join(test_dir, 'smiles')
os.mkdir(test_smile_dir)# Directory with our validation nosmile pictures
test_nosmile_dir = os.path.join(test_dir, 'no_smiles')
os.mkdir(test_nosmile_dir)
3) 将笑脸图片和非笑脸图片放入对应文件夹
将笑脸数据集中的两个数据放到生成的文件夹中相应的位置
4) 打印数据集中笑脸和非笑脸图片数
print('total training smile images:', len(os.listdir(train_smile_dir)))
print('total training nosmile images:', len(os.listdir(train_nosmile_dir)))
print('total validation smile images:', len(os.listdir(validation_smile_dir)))
print('total validation nosmile images:', len(os.listdir(validation_nosmile_dir)))
print('total test smile images:', len(os.listdir(test_smile_dir)))
print('total test nosmile images:', len(os.listdir(test_nosmile_dir)))
这里只选用了几十张图像进行模型的构建,自然其最终精度也会下降许多。当然,更多的图像自然建立的模型精度也会更高,这取决于你电脑的配置了。
5) 构建小型卷积神经网络
from keras import layers
from keras import modelsmodel = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu',input_shape=(150, 150, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))
了解征图的尺寸是如何随着每一层变化的
model.summary()
from keras import optimizers
model.compile(loss='binary_crossentropy',optimizer=optimizers.RMSprop(lr=1e-4),metrics=['acc'])
6) 数据预处理
from keras.preprocessing.image import ImageDataGenerator
# All images will be rescaled by 1./255
train_datagen = ImageDataGenerator(rescale=1./255)
test_datagen = ImageDataGenerator(rescale=1./255)train_generator = train_datagen.flow_from_directory(# This is the target directorytrain_dir,# All images will be resized to 150x150target_size=(150, 150),batch_size=20,# Since we use binary_crossentropy loss, we need binary labelsclass_mode='binary')validation_generator = test_datagen.flow_from_directory(validation_dir,target_size=(150, 150),batch_size=20,class_mode='binary')
生成器的输出
for data_batch, labels_batch in train_generator:print('data batch shape:', data_batch.shape)print('labels batch shape:', labels_batch.shape)break
7) 训练模型
history = model.fit_generator(train_generator,steps_per_epoch=100,epochs=30,validation_data=validation_generator,validation_steps=50)
这里使用fit_generator方法来完成此操作,对于我们这样的数据生成器,它相当于fit方法。
保存模型
model.save('smile_and_nosmile.h5')
保存好模型之后便可以进行此模型的人脸识别了,不过精度不会太高,毕竟只使用了这么少量的图片
绘制模型的损失和准确性
import matplotlib.pyplot as pltacc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']epochs = range(len(acc))plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()plt.figure()plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
8) 数据增强
数据增强采用的方法是从现有的训练样本中生成更多的训练数据,方法是通过一系列随机变换来“增强”样本,从而产生看上去可信的图像。我们的目标是在训练时,我们的模型不会两次看到完全相同的图像。这有助于将模型暴露于数据的更多方面,并更好地泛化。
datagen = ImageDataGenerator(rotation_range=40,width_shift_range=0.2,height_shift_range=0.2,shear_range=0.2,zoom_range=0.2,horizontal_flip=True,fill_mode='nearest')
查看数据增强后的图像
# This is module with image preprocessing utilities
from keras.preprocessing import imagefnames = [os.path.join(train_smile_dir, fname) for fname in os.listdir(train_smile_dir)]# We pick one image to "augment"
img_path = fnames[3]# Read the image and resize it
img = image.load_img(img_path, target_size=(150, 150))# Convert it to a Numpy array with shape (150, 150, 3)
x = image.img_to_array(img)# Reshape it to (1, 150, 150, 3)
x = x.reshape((1,) + x.shape)# The .flow() command below generates batches of randomly transformed images.
# It will loop indefinitely, so we need to `break` the loop at some point!
i = 0
for batch in datagen.flow(x, batch_size=1):plt.figure(i)imgplot = plt.imshow(image.array_to_img(batch[0]))i += 1if i % 4 == 0:breakplt.show()
如果我们使用这种数据增加配置训练一个新的网络,我们的网络将永远不会看到两次相同的输入。然而,它看到的输入仍然是高度相关的,因为它们来自少量的原始图像——我们不能产生新的信息,我们只能混合现有的信息。因此,这可能还不足以完全消除过度拟合。
为了进一步对抗过拟合,我们还将在我们的模型中增加一个Dropout层,就在密集连接分类器之前:
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu',input_shape=(150, 150, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(128, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Flatten())
model.add(layers.Dropout(0.5))
model.add(layers.Dense(512, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))model.compile(loss='binary_crossentropy',optimizer=optimizers.RMSprop(lr=1e-4),metrics=['acc'])
用数据增强和退出训练网络
train_datagen = ImageDataGenerator(rescale=1./255,rotation_range=40,width_shift_range=0.2,height_shift_range=0.2,shear_range=0.2,zoom_range=0.2,horizontal_flip=True,)# Note that the validation data should not be augmented!
test_datagen = ImageDataGenerator(rescale=1./255)train_generator = train_datagen.flow_from_directory(# This is the target directorytrain_dir,# All images will be resized to 150x150target_size=(150, 150),batch_size=32,# Since we use binary_crossentropy loss, we need binary labelsclass_mode='binary')validation_generator = test_datagen.flow_from_directory(validation_dir,target_size=(150, 150),batch_size=32,class_mode='binary')history = model.fit_generator(train_generator,steps_per_epoch=100,epochs=100,validation_data=validation_generator,validation_steps=50)
保存模型
model.save('smile_and_nosmile_1.h5')
再查看模型的损失和准确性
acc = history.history['acc']
val_acc = history.history['val_acc']
loss = history.history['loss']
val_loss = history.history['val_loss']epochs = range(len(acc))plt.plot(epochs, acc, 'bo', label='Training acc')
plt.plot(epochs, val_acc, 'b', label='Validation acc')
plt.title('Training and validation accuracy')
plt.legend()plt.figure()plt.plot(epochs, loss, 'bo', label='Training loss')
plt.plot(epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.show()
3.摄像头实时笑脸识别
import cv2
from keras.preprocessing import image
from keras.models import load_model
import numpy as np
import dlib
from PIL import Image
model = load_model('smile_and_nosmile_1.h5')
detector = dlib.get_frontal_face_detector()
video=cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_SIMPLEX
def rec(img):gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)dets=detector(gray,1)if dets is not None:for face in dets:left=face.left()top=face.top()right=face.right()bottom=face.bottom()cv2.rectangle(img,(left,top),(right,bottom),(0,255,0),2)img1=cv2.resize(img[top:bottom,left:right],dsize=(150,150))img1=cv2.cvtColor(img1,cv2.COLOR_BGR2RGB)img1 = np.array(img1)/255.img_tensor = img1.reshape(-1,150,150,3)prediction =model.predict(img_tensor) print(prediction)if prediction[0][0]<0.5:result='no_smiles'else:result='smiles'cv2.putText(img, result, (left,top), font, 2, (0, 255, 0), 2, cv2.LINE_AA)cv2.imshow('smile detector', img)
while video.isOpened():res, img_rd = video.read()if not res:breakrec(img_rd)if cv2.waitKey(1) & 0xFF == ord('q'):break
video.release()
cv2.destroyAllWindows()
二、将数据集换为口罩数据集,并进行训练,实现佩戴口罩的人脸识别
1.口罩数据集下载
人脸口罩数据集下载链接:https://pan.baidu.com/s/11PBCmDDx7Dtx_ckjwZR2uw
提取码:n2um
训练人脸口罩数据集和训练笑脸数据集一样,只需改一下和相应的变量名和数据集。
2.口罩佩戴的人脸识别
import cv2
from keras.preprocessing import image
from keras.models import load_model
import numpy as np
import dlib
from PIL import Image
model = load_model('mask_and_nomask.h5')
detector = dlib.get_frontal_face_detector()
video=cv2.VideoCapture(0)
font = cv2.FONT_HERSHEY_SIMPLEX
def rec(img):gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)dets=detector(gray,1)if dets is not None:for face in dets:left=face.left()top=face.top()right=face.right()bottom=face.bottom()cv2.rectangle(img,(left,top),(right,bottom),(0,255,0),2)img1=cv2.resize(img[top:bottom,left:right],dsize=(150,150))img1=cv2.cvtColor(img1,cv2.COLOR_BGR2RGB)img1 = np.array(img1)/255.img_tensor = img1.reshape(-1,150,150,3)prediction =model.predict(img_tensor) print(prediction)if prediction[0][0]>0.5:result='nomask'else:result='mask'cv2.putText(img, result, (left,top), font, 2, (0, 255, 0), 2, cv2.LINE_AA)cv2.imshow('mask detector', img)
while video.isOpened():res, img_rd = video.read()if not res:breakrec(img_rd)if cv2.waitKey(1) & 0xFF == ord('q'):break
video.release()
cv2.destroyAllWindows()
参考文献
https://blog.csdn.net/dQCFKyQDXYm3F8rB0/article/details/104743982
https://blog.csdn.net/cj151525/article/details/104984897
https://blog.csdn.net/weixin_45137708/article/details/107142706
Python --- 笑脸检测+口罩人脸识别相关推荐
- 京东AI:戴口罩人脸识别pytorch开源库
项目介绍 该项目是JDAI开源的基于PyTorch的人脸识别工具箱,提供了一个包括目前主流backbone和head的的training module,一个标准化的人脸识别evaluation mod ...
- 利用MTCNN和FaceNet实现人脸检测和人脸识别 | CSDN博文精选
作者 | pan_jinquan 来源 | CSDN博文精选 (*点击阅读原文,查看作者更多文章) 人脸检测和人脸识别技术算是目前人工智能方面应用最成熟的技术了.本博客将利用MTCNN和FaceNet ...
- 用Python实现简单的人脸识别,10分钟(附源码)
前言 今天,我们用Python实现简单的人脸识别技术! Python里,简单的人脸识别有很多种方法可以实现,依赖于python胶水语言的特性,我们通过调用包可以快速准确的达成这一目的.这里介绍的是准确 ...
- 中国队拿下口罩人脸识别世界第一!还将推出全球最大公开人脸数据集
允中 发自 凹非寺 量子位 编辑 | 公众号 QbitAI 在新冠疫情全球大流行的背景下,佩戴口罩几乎是所有国家和地区居民出行的必备选项.但严重的面部遮挡会对人脸识别技术构成严重挑战,受此影响,类似手 ...
- 10分钟手把手教你运用Python实现简单的人脸识别
欲直接下载代码文件,关注我们的公众号哦!查看历史消息即可! 前言:让我的电脑认识我 我的电脑只有认识我,才配称之为我的电脑! 今天,我们用Python实现高大上的人脸识别技术! Python里,简单的 ...
- python人脸识别毕业设计-Python基于Dlib的人脸识别系统的实现
之前已经介绍过人脸识别的基础概念,以及基于opencv的实现方式,今天,我们使用dlib来提取128维的人脸嵌入,并使用k临近值方法来实现人脸识别. 人脸识别系统的实现流程与之前是一样的,只是这里我们 ...
- pytorch实现人脸识别_一步一步带你完成深度学习与对象检测之人脸识别
前期文章我们分享了opencv的人脸检测 人工智能-OpenCV+Python实现人脸识别 以及dlib的人脸检测与人脸识别 人工智能-Dlib+Python实现人脸识别 通过往期的分享,我们了解到人 ...
- 统一操作系统 UOS 官网正式上线;旷视回应“戴口罩人脸识别”;IntelliJ IDEA 2019.3.3 发布 | 极客头条...
整理 | 屠敏 快来收听极客头条音频版吧,智能播报由标贝科技提供技术支持. 「极客头条」-- 技术人员的新闻圈! CSDN 的读者朋友们早上好哇,「极客头条」来啦,快来看今天都有哪些值得我们技术人关注 ...
- 基于Python的百度AI人脸识别API接口(可用于OpenCV-Python人脸识别)
基于Python的百度AI人脸识别API接口(可用于OpenCV-Python人脸识别) 资源: download.csdn.net/download/weixin_53403301/43644312 ...
最新文章
- wxpython安装失败_在Windows XP上安装wxPython后,“导入wx”失败
- linux 磁盘扩容_当LINUX服务器磁盘空间不够时如何进行磁盘扩容?
- Proguard returned with error code 1. See console
- mysql构建镜像时写入密码_用Dockerfile手动创建mysql5.7主从镜像
- 在Archlinuxarm上搭建Minecraft基岩服务器
- 学习编程的25个“坑”,你踩到了吗?
- php sort_flags
- 一道网易游戏笔试题的不同解法
- linux下使用lftp的小结
- 2021牛客多校3 - 24dian(dfs)
- win10卸载电脑管家就蓝屏_win10 动不动就蓝屏,都不敢用啦。该怎么解决呢?
- python list遍历定位元素_python for循环,第二遍定位不到元素?
- teststand调用python模块_TestStand 基本知识[10]--在序列中调用代码模块之--LabVIEW
- python程序运行原理_谈谈 Python 程序的运行原理
- vs2010中使用Nunit测试c#代码结果的正确性
- ESP8266多功能点阵时钟 - PCB制作分享
- Win10 UWP 开发教程
- 六、Python函数
- 交易总额高达600亿美元?亚马逊、微软和谷歌完成100多笔并购
- 【设计权限系统】ACL, DAC, MAC, RBAC, ABAC模型的不同应用场景
热门文章
- 《自己动手写Docker》学习笔记2
- iOS coding多人协作开发工具
- 读完本篇文章就会掌握hive over窗口函数的使用附带习题
- sunny-ngrok linux命令,ngrok使用
- linux怎么用命令期启动ngrok,ngrok 开机启动设置
- Cadence 如何通过.dra(封装)查看使用哪个.pad(焊盘)文件
- 写代码这条路,能走多远?阿里算法专家告诉你
- 人脸识别界面设计Android,人脸识别系统的设计及Android平台实现
- 北邮计算机学院9月推免,夏令营、预推免总结--计算机方向 (南科大、自动化所、上科大、北邮)...
- 《雷神之锤 Ⅲ》平方根倒数速算法魔术数字的另一种求法(2)