手把手教你用1行代码实现人脸识别

正文
 
环境要求:
 

  • Ubuntu17.10
  • Python 2.7.14
 
环境搭建:
1. 安装 Ubuntu17.10 > 安装步骤在这里
2. 安装 Python2.7.14 (Ubuntu17.10 默认Python版本为2.7.14)
3. 安装 git 、cmake 、 python-pip
# 安装 git
$ sudo apt-get install -y git
# 安装 cmake
$ sudo apt-get install -y cmake
# 安装 python-pip
$ sudo apt-get install -y python-pip
4. 安装编译dlib
安装face_recognition这个之前需要先安装编译dlib
# 编译dlib前先安装 boost
$ sudo apt-get install libboost-all-dev
# 开始编译dlib
# 克隆dlib源代码
$ git clone https://github.com/davisking/dlib.git
$ cd dlib
$ mkdir build
$ cd build
$ cmake .. -DDLIB_USE_CUDA=0 -DUSE_AVX_INSTRUCTIONS=1
$ cmake --build .(注意中间有个空格)
$ cd ..
$ python setup.py install --yes USE_AVX_INSTRUCTIONS --no DLIB_USE_CUDA
5. 安装 face_recognition
# 安装 face_recognition
$ pip install face_recognition
# 安装face_recognition过程中会自动安装 numpy、scipy 等
环境搭建完成后 , 在终端输入 face_recognition 命令查看是否成功
 
手把手教你用1行代码实现人脸识别

文章插图
 
实现人脸识别:
示例一(1行代码实现人脸识别):
1. 首先你需要提供一个文件夹 , 里面是所有你希望系统认识的人的图片 。其中每个人一张图片 , 图片以人的名字命名:
known_people文件夹下有babe、成龙、容祖儿的照片
 
手把手教你用1行代码实现人脸识别

文章插图
 
2. 接下来 , 你需要准备另一个文件夹 , 里面是你要识别的图片:
unknown_pic文件夹下是要识别的图片 , 其中韩红是机器不认识的
 
手把手教你用1行代码实现人脸识别

文章插图
 
3. 然后你就可以运行face_recognition命令了 , 把刚刚准备的两个文件夹作为参数传入 , 命令就会返回需要识别的图片中都出现了谁:
识别成功!!!
 
手把手教你用1行代码实现人脸识别

文章插图
 
示例二(识别图片中的所有人脸并显示出来):
# filename : find_faces_in_picture.py
# -*- coding: utf-8 -*-
# 导入pil模块  , 可用命令安装 apt-get install python-Imaging
from PIL import Image
# 导入face_recogntion模块 , 可用命令安装 pip install face_recognition
import face_recognition
# 将jpg文件加载到numpy 数组中
image = face_recognition.load_image_file("/opt/face/unknown_pic/all_star.jpg")
# 使用默认的给予HOG模型查找图像中所有人脸
# 这个方法已经相当准确了 , 但还是不如CNN模型那么准确 , 因为没有使用GPU加速
# 另请参见: find_faces_in_picture_cnn.py
face_locations = face_recognition.face_locations(image)
# 使用CNN模型
# face_locations = face_recognition.face_locations(image, number_of_times_to_upsample=0, model="cnn")
# 打印:我从图片中找到了 多少 张人脸
print("I found {} face(s) in this photograph.".format(len(face_locations)))
# 循环找到的所有人脸
for face_location in face_locations:
# 打印每张脸的位置信息
top, right, bottom, left = face_location
print("A face is located at pixel location Top: {}, Left: {}, Bottom: {}, Right: {}".format(top, left, bottom, right))
# 指定人脸的位置信息 , 然后显示人脸图片
face_image = image[top:bottom, left:right]
pil_image = Image.fromarray(face_image)
pil_image.show()
如下图为用于识别的图片
 
手把手教你用1行代码实现人脸识别

文章插图
 
# 执行python文件
$ python find_faces_in_picture.py
从图片中识别出7张人脸 , 并显示出来 , 如下图
 
手把手教你用1行代码实现人脸识别

文章插图
 
示例三(自动识别人脸特征):
# filename : find_facial_features_in_picture.py
# -*- coding: utf-8 -*-
# 导入pil模块  , 可用命令安装 apt-get install python-Imaging
from PIL import Image, ImageDraw
# 导入face_recogntion模块 , 可用命令安装 pip install face_recognition
import face_recognition


推荐阅读