可以使用OpenCV,OpenCV的人脸检测功能在一般场合还是不错的。而ubuntu正好提供了python-opencv这个包,用它可以方便地实现人脸检测的代码。
写代码之前应该先安装python-opencv:
#!/usr/bin/python# -*- coding: UTF-8 -*-
# face_detect.py
# Face Detection using OpenCV. Based on sample code from:
# http://python.pastebin.com/m76db1d6b
# Usage: python face_detect.py <image_file>
import sys, os
from opencv.cv import *
from opencv.highgui import *
from PIL import Image, ImageDraw
from math import sqrt
def detectObjects(image):
"""Converts an image to grayscale and prints the locations of any faces found"""
grayscale = cvCreateImage(cvSize(image.width, image.height), 8, 1)
cvCvtColor(image, grayscale, CV_BGR2GRAY)
storage = cvCreateMemStorage(0)
cvClearMemStorage(storage)
cvEqualizeHist(grayscale, grayscale)
cascade = cvLoadHaarClassifierCascade(
'/usr/share/opencv/haarcascades/haarcascade_frontalface_default.xml',
cvSize(1,1))
faces = cvHaarDetectObjects(grayscale, cascade, storage, 1.1, 2,
CV_HAAR_DO_CANNY_PRUNING, cvSize(20,20))
result = []
for f in faces:
result.append((f.x, f.y, f.x+f.width, f.y+f.height))
return result
def grayscale(r, g, b):
return int(r * .3 + g * .59 + b * .11)
def process(infile, outfile):
image = cvLoadImage(infile)
if image:
faces = detectObjects(image)
im = Image.open(infile)
if faces:
draw = ImageDraw.Draw(im)
for f in faces:
draw.rectangle(f, outline=(255, 0, 255))
im.save(outfile, "JPEG", quality=100)
else:
print "Error: cannot detect faces on %s" % infile
if __name__ == "__main__":
process('input.jpg', 'output.jpg')
简介该库可以通过python或者命令行即可实现人脸识别的功能。使用dlib深度学习人脸识别技术构建,在户外脸部检测数据库基准(Labeled Faces in the Wild)上的准确率为99.38%。
在github上有相关的链接和API文档。
在下方为提供的一些相关源码或是文档。当前库的版本是v0.2.0,点击docs可以查看API文档,我们可以查看一些函数相关的说明等。
安装配置
安装配置很简单,按照github上的说明一步一步来就可以了。
根据你的python版本输入指令:
pip install face_recognition11
或者
pip3 install face_recognition11
正常来说,安装过程中会出错,会在安装dlib时出错,可能报错也可能会卡在那不动。因为pip在编译dlib时会出错,所以我们需要手动编译dlib再进行安装。
按照它给出的解决办法:
1、先下载下来dlib的源码。
git clone
2、编译dlib。
cd dlib
mkdir build
cd build
cmake .. -DDLIB_USE_CUDA=0 -DUSE_AVX_INSTRUCTIONS=1
cmake --build1234512345
3、编译并安装python的拓展包。
cd ..
python3 setup.py install --yes USE_AVX_INSTRUCTIONS --no DLIB_USE_CUDA1212
注意:这个安装步骤是默认认为没有GPU的,所以不支持cuda。
在自己手动编译了dlib后,我们可以在python中import dlib了。
之后再重新安装,就可以配置成功了。
根据你的python版本输入指令:
pip install face_recognition11
或者
pip3 install face_recognition11
安装成功之后,我们可以在python中正常import face_recognition了。
编写人脸识别程序
编写py文件:
# -*- coding: utf-8 -*-
#
# 检测人脸
import face_recognition
import cv2
# 读取图片并识别人脸
img = face_recognition.load_image_file("silicon_valley.jpg")
face_locations = face_recognition.face_locations(img)
print face_locations
# 调用opencv函数显示图片
img = cv2.imread("silicon_valley.jpg")
cv2.namedWindow("原图")
cv2.imshow("原图", img)
# 遍历每个人脸,并标注
faceNum = len(face_locations)
for i in range(0, faceNum):
top = face_locations[i][0]
right = face_locations[i][1]
bottom = face_locations[i][2]
left = face_locations[i][3]
start = (left, top)
end = (right, bottom)
color = (55,255,155)
thickness = 3
cv2.rectangle(img, start, end, color, thickness)
# 显示识别结果
cv2.namedWindow("识别")
cv2.imshow("识别", img)
cv2.waitKey(0)
cv2.destroyAllWindows()12345678910111213141516171819202122232425262728293031323334353637381234567891011121314151617181920212223242526272829303132333435363738
注意:这里使用了python-OpenCV,一定要配置好了opencv才能运行成功。
运行结果:
程序会读取当前目录下指定的图片,然后识别其中的人脸,并标注每个人脸。
(使用图片来自美剧硅谷)
编写人脸比对程序
首先,我在目录下放了几张图片:
这里用到的是一张乔布斯的照片和一张奥巴马的照片,和一张未知的照片。
编写程序:
# 识别图片中的人脸
import face_recognition
jobs_image = face_recognition.load_image_file("jobs.jpg")
obama_image = face_recognition.load_image_file("obama.jpg")
unknown_image = face_recognition.load_image_file("unknown.jpg")
jobs_encoding = face_recognition.face_encodings(jobs_image)[0]
obama_encoding = face_recognition.face_encodings(obama_image)[0]
unknown_encoding = face_recognition.face_encodings(unknown_image)[0]
results = face_recognition.compare_faces([jobs_encoding, obama_encoding], unknown_encoding )
labels = ['jobs', 'obama']
print('results:'+str(results))
for i in range(0, len(results)):
if results[i] == True:
print('The person is:'+labels[i])123456789101112131415161718123456789101112131415161718
运行结果:
识别出未知的那张照片是乔布斯的。
摄像头实时识别
代码:
# -*- coding: utf-8 -*-
import face_recognition
import cv2
video_capture = cv2.VideoCapture(1)
obama_img = face_recognition.load_image_file("obama.jpg")
obama_face_encoding = face_recognition.face_encodings(obama_img)[0]
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
while True:
ret, frame = video_capture.read()
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
if process_this_frame:
face_locations = face_recognition.face_locations(small_frame)
face_encodings = face_recognition.face_encodings(small_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
match = face_recognition.compare_faces([obama_face_encoding], face_encoding)
if match[0]:
name = "Barack"
else:
name = "unknown"
face_names.append(name)
process_this_frame = not process_this_frame
for (top, right, bottom, left), name in zip(face_locations, face_names):
top *= 4
right *= 4
bottom *= 4
left *= 4
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), 2)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, name, (left+6, bottom-6), font, 1.0, (255, 255, 255), 1)
cv2.imshow('Video', frame)
if cv2.waitKey(1) &0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545512345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
识别结果:
我直接在手机上百度了几张图试试,程序识别出了奥巴马。
这个库很cool啊!
很多人都认为人脸识别是一项非常难以实现的工作,看到名字就害怕,然后心怀忐忑到网上一搜,看到网上N页的教程立马就放弃了。这些人里包括曾经的我自己。其实如果如果你不是非要深究其中的原理,只是要实现这一工作的话,人脸识别也没那么难。今天我们就来看看如何在40行代码以内简单地实现人脸识别。一点区分
对于大部分人来说,区分人脸检测和人脸识别完全不是问题。但是网上有很多教程有无无意地把人脸检测说成是人脸识别,误导群众,造成一些人认为二者是相同的。其实,人脸检测解决的问题是确定一张图上有木有人脸,而人脸识别解决的问题是这个脸是谁的。可以说人脸检测是是人识别的前期工作。今天我们要做的是人脸识别。
所用工具
Anaconda 2——Python 2
Dlib
scikit-image
Dlib
对于今天要用到的主要工具,还是有必要多说几句的。Dlib是基于现代C++的一个跨平台通用的框架,作者非常勤奋,一直在保持更新。Dlib内容涵盖机器学习、图像处理、数值算法、数据压缩等等,涉猎甚广。更重要的是,Dlib的文档非常完善,例子非常丰富。就像很多库一样,Dlib也提供了Python的接口,安装非常简单,用pip只需要一句即可:
pip install dlib
上面需要用到的scikit-image同样只是需要这么一句:
pip install scikit-image
注:如果用pip install dlib安装失败的话,那安装起来就比较麻烦了。错误提示很详细,按照错误提示一步步走就行了。
人脸识别
之所以用Dlib来实现人脸识别,是因为它已经替我们做好了绝大部分的工作,我们只需要去调用就行了。Dlib里面有人脸检测器,有训练好的人脸关键点检测器,也有训练好的人脸识别模型。今天我们主要目的是实现,而不是深究原理。感兴趣的同学可以到官网查看源码以及实现的参考文献。今天的例子既然代码不超过40行,其实是没啥难度的。有难度的东西都在源码和论文里。
首先先通过文件树看一下今天需要用到的东西:
准备了六个候选人的图片放在candidate-faces文件夹中,然后需要识别的人脸图片test.jpg。我们的工作就是要检测到test.jpg中的人脸,然后判断她到底是候选人中的谁。另外的girl-face-rec.py是我们的python脚本。shape_predi