引入
深度神经网络已经应用在很多方面,同时图像识别是神经网络最具潜力的应用领域。本文将以人脸识别的demo为例,介绍神经网络在图像识别中的应用。
1.程序用到的库
(1)tensorflow:它是一个极其强大的神经网络库,对python有较好的支持。
(2)dlib:它是一款C++的开源工具包,可以进行人脸检测。
(3)open-cv:机器视觉领域极其强大的库,可以进行图像的处理。
(4)numpy:python的科学计算库。
2.必要的程序及库安装
(1)python3.x:建议通过anaconda进行安装。
(2)tensorflow:pip install tensorflow
(3)numpy:pip install numpy
(4)dlib:下载dlib的whl文件之后进行安装 pip install dlib-*****.whl
3.程序的具体实现
本程序的部分图像处理内容参考了http://tumumu.cn/的博客内容。
程序的数据集采用马萨诸塞大学阿默斯特分校发起的lfw(点这里下载数据集)项目收集的数据集。
1.录入自己的脸,准备数据集
collect_my_face.py
#导入库
import cv2
import dlib
import os
import sys
import random
#output_dir用来存放录入的脸部图片
output_dir="./my_faces"
#size最后的图片尺寸为size*size
size=64
if not os.path.exists(output_dir):
os.makedirs(output_dir)
def relight(img,light=1,bias=0):
#随机改变图片亮度,增加图片的多样性
w=img.shape[0]
h=img.shape[1]
for i in range(0,h):
for j in range(w):
for c in range(3):
tmp=int(img[j,i,c]*light+bias)
if tmp>255:
tmp=255
elif tmp<0:
tmp=0
img[j,i,c]=tmp
return img
detector=dlib.get_frontal_face_detector()
camera=cv2.VideoCapture(0)
index=int(input("输入录入断点:"))
while True:
if (index<=10000):
#录入10000张照片
print("Being processed picture %s"%index)
success,img=camera.read()
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
dets=detector(gray_img,1)
for i,d in enumerate(dets):
#针对识别出来的面部进行剪裁,并把尺寸调整成size*size
x1=d.top() if d.top() >0 else 0
y1=d.bottom() if d.bottom()>0 else 0
x2=d.left() if d.left()>0 else 0
y2=d.right() if d.right()>0 else 0
face=img[x1:y1,x2:y2]
face=relight(face,random.uniform(0.5,1.5),random.randint(-50,50))
face=cv2.resize(face,(size,size))
cv2.imshow("image",face)
cv2.imwrite(output_dir+"/"+str(index)+".jpg",face)
index+=1
key=cv2.waitKey(30)& 0xff
if key==27:
break
2.数据集转化为batch
input_images_prepare.py
import os
import numpy as np
import cv2
class Read_Batch():
#定义Read_Batch类用以读取batch
def __init__(self,path,myface_dir_list=[],other_dir_list=[],batch_list=[],label_list=[]):
#类内参数初始化,myface_dir_list存放my_faces文件夹下的文件名
self.myface_dir_list=os.listdir(path+"my_faces")
self.other_dir_list=os.listdir(path+"other_faces")
#batch_list存放读取的batch
self.batch_list=batch_list
#myface_readed_location指向已经读取到的文件位置,防止下次读取batch的时候重复读取之前读过的图片
self.myface_readed_location=0
self.other_face_readed_location=0
self.path=path
#label_list存放图片的label
self.label_list=label_list
self.myface_len=len(self.myface_dir_list)
self.other_face_len&