首页 > 编程知识 正文

python的face(python的face库)

时间:2023-12-02 11:48:16 阅读:311422 作者:RQCB

本文目录一览:

  • 1、人脸识别为什么用python开发
  • 2、如何使用Python,基于OpenCV与Face++实现人脸解锁的功能
  • 3、谁用过python中的第三方库face recognition

人脸识别为什么用python开发

可以使用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:

 

# 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,基于OpenCV与Face++实现人脸解锁的功能

近几天微软的发布会上讲到了不少认脸解锁的内容,经过探索,其实利用手头的资源我们完全自己也可以完成这样一个过程。

本文讲解了如何使用Python,基于OpenCV与Face++实现人脸解锁的功能。

本文基于Python 2.7.11,Windows 8.1 系统。

主要内容

Windows 8.1上配置OpenCV

OpenCV的人脸检测应用

使用Face++完成人脸辨识(如果你想自己实现这部分的功能,可以借鉴例如这个项目)

Windows 8.1上配置OpenCV

入门的时候配置环境总是一个非常麻烦的事情,在Windows上配置OpenCV更是如此。

既然写了这个推广的科普教程,总不能让读者卡在环境配置上吧。

下面用到的文件都可以在这里(提取码:b6ec)下载,但是注意,目前OpenCV仅支持Python2.7。

将cv2加入site-packages

将下载下来的cv2.pyd文件放入Python安装的文件夹下的Libsite-packages目录。

就我的电脑而言,这个目录就是C:/Python27/Lib/site-packages/。

记得不要直接使用pip安装,将文件拖过去即可。

安装numpy组件

在命令行下进入到下载下来的文件所在的目录(按住Shift右键有在该目录打开命令行的选项)

键入命令:

1

   

pip install numpy-1.11.0rc2-cp27-cp27m-win32.whl

   

如果你的系统或者Python不适配,可以在这里下载别的轮子。

测试OpenCV安装

在命令行键入命令:

1

   

python -c "import cv2"

   

如果没有出现错误提示,那么cv2就已经安装好了。

OpenCV的人脸检测应用

人脸检测应用,简而言之就是一个在照片里找到人脸,然后用方框框起来的过程(我们的相机经常做这件事情)

那么具体而言就是这样一个过程:

获取摄像头的图片

在图片中检测到人脸的区域

在人脸的区域周围绘制方框

获取摄像头的图片

这里简单的讲解一下OpenCV的基本操作。

以下操作是打开摄像头的基本操作:

1

2

3

4

5

6

7

   

#coding=utf8

import cv2

# 一般笔记本的默认摄像头都是0

capInput = cv2.VideoCapture(0)

# 我们可以用这条命令检测摄像头是否可以读取数据

if not capInput.isOpened(): print('Capture failed because of camera')

   

那么怎么从摄像头读取数据呢?

1

2

3

4

5

6

7

8

   

# 接上段程序

# 现在摄像头已经打开了,我们可以使用这条命令读取图像

# img就是我们读取到的图像,就和我们使用open('pic.jpg', 'rb').read()读取到的数据是一样的

ret, img = capInput.read()

# 你可以使用open的方式存储,也可以使用cv2提供的方式存储

cv2.imwrite('pic.jpg', img)

# 同样,你可以使用open的方式读取,也可以使用cv2提供的方式读取

img = cv2.imread('pic.jpg')

   

为了方便显示图片,cv2也提供了显示图片的方法:

1

2

3

4

5

6

   

# 接上段程序

# 定义一个窗口,当然也可以不定义

imgWindowName = 'ImageCaptured'

imgWindow = cv2.namedWindow(imgWindowName, cv2.WINDOW_NORMAL)

# 在窗口中显示图片

cv2.imshow(imgWindowName, img)

   

当然在完成所有操作以后需要把摄像头和窗口都做一个释放:

1

2

3

4

5

   

# 接上段程序

# 释放摄像头

capInput.release()

# 释放所有窗口

cv2.destroyAllWindows()

   

在图片中检测到人脸的区域

OpenCV给我们提供了已经训练好的人脸的xml模板,我们只需要载入然后比对即可。

1

2

3

4

5

6

7

8

   

# 接上段程序

# 载入xml模板

faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

# 将图形存储的方式进行转换

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# 使用模板匹配图形

faces = faceCascade.detectMultiScale(gray, 1.3, 5)

print(faces)

   

在人脸的区域周围绘制方框

在上一个步骤中,faces中的四个量分别为左上角的横坐标、纵坐标、宽度、长度。

所以我们根据这四个量很容易的就可以绘制出方框。

1

2

3

   

# 接上段程序

# 函数的参数分别为:图像,左上角坐标,右下角坐标,颜色,宽度

img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)

   

成果

根据上面讲述的内容,我们现在已经可以完成一个简单的人脸辨认了:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

   

#coding=utf8

import cv2

print('Press Esc to exit')

faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

imgWindow = cv2.namedWindow('FaceDetect', cv2.WINDOW_NORMAL)

def detect_face():

capInput = cv2.VideoCapture(0)

# 避免处理时间过长造成画面卡顿

nextCaptureTime = time.time()

faces = []

if not capInput.isOpened(): print('Capture failed because of camera')

while 1:

ret, img = capInput.read()

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

if nextCaptureTime time.time():

nextCaptureTime = time.time() + 0.1

faces = faceCascade.detectMultiScale(gray, 1.3, 5)

if faces:

for x, y, w, h in faces:

img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)

cv2.imshow('FaceDetect', img)

# 这是简单的读取键盘输入,27即Esc的acsii码

if cv2.waitKey(1) 0xFF == 27: break

capInput.release()

cv2.destroyAllWindows()

if __name__ == '__main__':

detect_face()

   

使用Face++完成人脸辨识

第一次认识Face++还是因为支付宝的人脸支付,响应速度还是非常让人满意的。

现在只需要免费注册一个账号然后新建一个应用就可以使用了,非常方便。

他的官方网址是这个,注册好之后在这里的我的应用中创建应用即可。

创建好应用之后你会获得API Key与API Secret。

Face++的API调用逻辑简单来说是这样的:

上传图片获取读取到的人的face_id

创建Person,获取person_id(Person中的图片可以增加、删除)

比较两个face_id,判断是否是一个人

比较face_id与person_id,判断是否是一个人

上传图片获取face_id

在将图片通过post方法上传到特定的地址后将返回一个json的值。

如果api_key, api_secret没有问题,且在上传的图片中有识别到人脸,那么会存储在json的face键值下。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

   

#coding=utf8

import requests

# 这里填写你的应用的API Key与API Secret

API_KEY = ''

API_SECRET = ''

# 目前的API网址是这个,你可以在API文档里找到这些

BASE_URL = 'httlus.com/v2'

# 使用Requests上传图片

url = '%s/detection/detect?api_key=%sapi_secret=%sattribute=none'%(

BASE_URL, API_KEY, API_SECRET)

files = {'img': (os.path.basename(fileDir), open(fileDir, 'rb'),

mimetypes.guess_type(fileDir)[0]), }

r = requests.post(url, files = files)

# 如果读取到图片中的头像则输出他们,其中的'face_id'就是我们所需要的值

faces = r.json().get('face')

print faces

   

创建Person

这个操作没有什么可以讲的内容,可以对照这段程序和官方的API介绍。

官方的API介绍可以见这里,相信看完这一段程序以后你就可以自己完成其余的API了。

1

2

3

4

5

6

7

8

9

10

11

12

13

14

   

# 上接上一段程序

# 读取face_id

if not faces is None: faceIdList = [face['face_id'] for face in faces]

# 使用Requests创建Person

url = '%s/person/create'%BASE_URL

params = {

'api_key': API_KEY,

'api_secret': API_SECRET,

'person_name': 'LittleCoder',

'face_id': ','.join(faceIdList), }

r = requests.get(url, params = params)

# 获取person_id

print r.json.()['person_id']

   

进度确认

到目前为止,你应该已经可以就给定的两张图片比对是否是同一个人了。

那么让我们来试着写一下这个程序吧,两张图片分别为’pic1.jpg’, ‘pic2.jpg’好了。

下面我给出了我的代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

   

def upload_img(fileDir, oneface = True):

url = '%s/detection/detect?api_key=%sapi_secret=%sattribute=none'%(

BASE_URL, API_KEY, API_SECRET)

if oneface: url += 'mode=oneface'

files = {'img': (os.path.basename(fileDir), open(fileDir, 'rb'),

mimetypes.guess_type(fileDir)[0]), }

r = requests.post(url, files = files)

faces = r.json().get('face')

if faces is None:

print('There is no face found in %s'%fileDir)

else:

return faces[0]['face_id']

def compare(faceId1, faceId2):

url = '%s/recognition/compare'%BASE_URL

params = BASE_PARAMS

params['face_id1'] = faceId1

params['face_id2'] = faceId2

r = requests.get(url, params)

return r.json()

faceId1 = upload_img('pic1.jpg')

faceId2 = upload_img('pic2.jpg')

if face_id1 and face_id2:

print(compare(faceId1, faceId2))

else:

print('Please change two pictures')

   

成品

到此,所有的知识介绍都结束了,相比大致如何完成这个项目各位读者也已经有想法了吧。

下面我们需要构思一下人脸解锁的思路,大致而言是这样的:

使用一个程序设置账户(包括向账户中存储解锁用的图片)

使用另一个程序登陆(根据输入的用户名测试解锁)

这里会有很多重复的代码,就不再赘述了,你可以在这里或者这里(提取码:c073)下载源代码测试使用。

这里是设置账户的截图:

设置账户

这里是登陆的截图:

登陆

结束语

希望读完这篇文章能对你有帮助,有什么不足之处万望指正(鞠躬)。

谁用过python中的第三方库face recognition

简介

该库可以通过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啊!

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。