Face++是一套成熟的人脸检测、识别和跟踪等视觉技术服务平台,每个人在Face++的官网注册账号后可以申请新建API,随后会分配API key和 API Secrect,这样我们就可以使用这些API进行简单的人脸识别了。
原文链接传送门
代码如下:
# coding=UTF-8
import cv2
import urllib
import urllib2
import time
# 读取图像
image = cv2.imread('girls.jpg')
# URL
http_url='https://api-cn.faceplusplus.com/facepp/v3/detect'
# 用户信息
key = '06LVocdF5FVMyNkMRknGzXYlMf_N-MUA'
secret = 'WAi7gNtc3NPwpf-iHGUk9pxjxyws43aq'
# 图片存储路径
filepath = 'girls.jpg'
# 调用API接口
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--\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)
try:
# req.add_header('Referer','http://remotserver.com/')
# post data to server
resp = urllib2.urlopen(req, timeout=5)
# get response
qrcont=resp.read()
print qrcont # 打印出得到的结果
except urllib2.HTTPError as e:
print e.read()
# 进过测试前面的程序会返回一个字典,其中指出了人脸所在的矩形的位置和大小等,所以直接进行标注
mydict = eval(qrcont)
faces = mydict["faces"]
faceNum = len(faces)
print("识别到了%d个人脸"%( faceNum ))
for i in range(faceNum):
face_rectangle = faces[i]['face_rectangle']
width = face_rectangle['width']
top = face_rectangle['top']
left = face_rectangle['left']
height = face_rectangle['height']
start = (left, top)
end = (left+width, top+height)
color = (255,55,55)
thickness = 5
cv2.rectangle(image, start, end, color, thickness)
cv2.namedWindow("Detection:")
cv2.imshow("Detection:", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果如下图: