Python调用face++API完成本地图片的人脸检测

Python调用face++API完成本地图片的人脸检测

简单调用face++API对本地图片进行人脸检测,输出基本信息到csv文件。

注册face++账号

face++网址 https://www.faceplusplus.com.cn/

在这里插入图片描述
注册完成之后,查看自己的 API Key 和 API Secret
在这里插入图片描述

改写官网代码示例完成人脸信息采集

原代码示例网址 https://console.faceplusplus.com.cn/documents/6329752
选用原代码示例中的python代码对其进行符合人脸检测信息采集需求的修改,代码如下,具体代码解释见下节:

# -*- coding: utf-8 -*- import urllib2 import time import os from pandas.core.frame import DataFrame result = [] http_url='https://api-cn.faceplusplus.com/facepp/v3/detect' key = "sJVodwPAjfbo18Vc2OCZjIUuM1u2BhWe" #这里是你申请的API Key  secret = "29dB1GxL9oXbv7P117CLa4ZyUdHzj1ad" #这里是你申请的API Secret filedir = r"C:\Users\Desktop\face\data\images" #这里是你要检测图片文件夹的路径 writepath = "C:\\Users\\Desktop\\face\\data\\note.csv" #这里替换为你写入csv文件的路径 filelist = os.listdir(filedir) for filename in filelist: filepath = os.path.join(filedir,filename) boundary = '----------%s' % hex(int(time.time() * 1000)) data = [] data.append('--%s' % boundary) data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_key') data.append(key) data.append('--%s' % boundary) data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_secret') data.append(secret) data.append('--%s' % boundary) fr=open(filepath,'rb') data.append('Content-Disposition: form-data; name="%s"; filename=" "' % 'image_file') data.append('Content-Type: %s\r\n' % 'application/octet-stream') data.append(fr.read()) fr.close() data.append('--%s' % boundary) data.append('Content-Disposition: form-data; name="%s"\r\n' % 'return_landmark') data.append('1') data.append('--%s' % boundary) data.append('Content-Disposition: form-data; name="%s"\r\n' % 'return_attributes') data.append("gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus") data.append('--%s--\r\n' % boundary) http_body='\r\n'.join(data) #buld http request req=urllib2.Request(http_url) #header req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary) req.add_data(http_body) #这里提取图片的性别、年龄、人脸框位置,并输出该图片的绝对路径。 #若提取其他属性,请修改以下代码,将result中加入所需属性并输出 try: resp = urllib2.urlopen(req, timeout=5) qrcont = resp.read() dict = eval(qrcont) faces = dict['faces'] for i in range(len(faces)): attribute = faces[i]['attributes'] gender = attribute['gender']['value'] age = attribute['age']['value'] face_rectangle = faces[i]['face_rectangle'] width = face_rectangle['width'] top = face_rectangle['top'] left = face_rectangle['left'] height = face_rectangle['height'] result.append([filepath,gender,age,width,top,left,height]) except urllib2.HTTPError as e: print e.read() DataFrame(result).to_csv(writepath,header=['filepath','gender','age','width','top','left','heigth']) # -*- coding: utf-8 -*- import urllib2 import time import os from pandas.core.frame import DataFrame result = [] http_url='https://api-cn.faceplusplus.com/facepp/v3/detect' key = "sJVodwPAjfbo18Vc2OCZjIUuM1u2BhWe" #这里是你申请的API Key  secret = "29dB1GxL9oXbv7P117CLa4ZyUdHzj1ad" #这里是你申请的API Secret filedir = r"C:\Users\Desktop\face\data\images" #这里是你要检测图片文件夹的路径 writepath = "C:\\Users\\Desktop\\face\\data\\note.csv" #这里替换为你写入csv文件的路径 filelist = os.listdir(filedir) for filename in filelist: filepath = os.path.join(filedir,filename) boundary = '----------%s' % hex(int(time.time() * 1000)) data = [] data.append('--%s' % boundary) data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_key') data.append(key) data.append('--%s' % boundary) data.append('Content-Disposition: form-data; name="%s"\r\n' % 'api_secret') data.append(secret) data.append('--%s' % boundary) fr=open(filepath,'rb') data.append('Content-Disposition: form-data; name="%s"; filename=" "' % 'image_file') data.append('Content-Type: %s\r\n' % 'application/octet-stream') data.append(fr.read()) fr.close() data.append('--%s' % boundary) data.append('Content-Disposition: form-data; name="%s"\r\n' % 'return_landmark') data.append('1') data.append('--%s' % boundary) data.append('Content-Disposition: form-data; name="%s"\r\n' % 'return_attributes') data.append("gender,age,smiling,headpose,facequality,blur,eyestatus,emotion,ethnicity,beauty,mouthstatus,eyegaze,skinstatus") data.append('--%s--\r\n' % boundary) http_body='\r\n'.join(data) #buld http request req=urllib2.Request(http_url) #header req.add_header('Content-Type', 'multipart/form-data; boundary=%s' % boundary) req.add_data(http_body) #这里提取图片的性别、年龄、人脸框位置,并输出该图片的绝对路径。 #若提取其他属性,请修改以下代码,将result中加入所需属性并输出 try: resp = urllib2.urlopen(req, timeout=5) qrcont = resp.read() dict = eval(qrcont) faces = dict['faces'] for i in range(len(faces)): attribute = faces[i]['attributes'] gender = attribute['gender']['value'] age = attribute['age']['value'] face_rectangle = faces[i]['face_rectangle'] width = face_rectangle['width'] top = face_rectangle['top'] left = face_rectangle['left'] height = face_rectangle['height'] result.append([filepath,gender,age,width,top,left,height]) except urllib2.HTTPError as e: print e.read() DataFrame(result).to_csv(writepath,header=['filepath','gender','age','width','top','left','heigth'])

返回变量

在本示例中,只提取了检测到人脸的性别、年龄、人脸框位置,而face++人脸检测API提供了十分全面的返回值,具体返回值课件参考官网文档 https://console.faceplusplus.com.cn/documents/4888373
这里,解释上述代码提取各变量的含义。

字段 类型 说明
gender String 性别分析结果,Male为男性,Female为女性
age Int 年龄分析结果。返回值为一个非负整数
face_rectangle Object 人脸矩形框的位置,包括以下属性
top Int 矩形框左上角像素点的纵坐标
left Int 矩形框左上角像素点的横坐标
width Int 矩形框的宽度
height Int 矩形框的高度

代码结果

若路径filedir下有如下一张图片:
在这里插入图片描述
使用python2.7运行代码,可以得到一个绝对路径为writepath的csv文件如下
在这里插入图片描述
face++人脸检测API检测出5张人脸,并将人脸信息保存在了csv文件中。

注意事项

  1. 改进的示例代码使用python2编译
  2. filedir和writepath两个路径不要带有中文字符
  3. 需要事先安装urllib2