1.缘起
机缘巧合,去年加了个计算机视觉的QQ群,现在赶上校招,偶然看见了旷视的公告。多亏南京研发中心的魏秀参博士推荐,再投递简历的第二天就收到了面试通知,后天面试旷视科技。了解一家公司的办法之一就是使用这家公司的产品,于是利用午休的时间申请了个开发者账号,然后体验了一把Face++的API,真的好强。
2.铺垫
怎么申请就不多说了,就是注册个账号那么简单。接口使用的是HTTP协议,各种平台各种语言只要能解析HTTP,就能使用。密钥有一对,公钥和私钥。下面我使用在Pycharm的IDE里,使用Python的request和opencv来进行试验。
3.配置opencv
很简单,把opencv\build\python\2.7\x64\cv2.pyd这个文件拷贝到C:\Python27\Lib\site-packages文件夹下即可。
4.代码
# -*- coding: utf-8 -*-
import urllib2
import urllib
import ssl
import time
import cv2
http_url='https://api-cn.faceplusplus.com/facepp/v3/detect'
key = "89W9C9NTm0Je9BBGZbro2fmnit41ajT7"
secret = "j0dCqm5hwKcNy1xhu0z1XIO1hFix4LzP"
filepath = r"./they.jpg"
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)
img = cv2.imread('they.jpg')
cv2.imshow('img1',img)
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/')
context = ssl._create_unverified_context()
resp = urllib2.urlopen(req, timeout=5, context=context)
# get response
qrcont = resp.read()
print qrcont
dict = eval(qrcont)
faces = dict['faces']
print len(faces)
for i in range(len(faces)):
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 = (55, 255, 155)
thickness = 3
cv2.rectangle(img, start, end, color, thickness)
cv2.namedWindow("img2")
cv2.imshow("img2", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
except urllib2.HTTPError as e:
print e.read()
5.执行结果
6.可能会踩的坑
face++官方是给了Python调用的例子的,但是Python升级到 2.7.9 之后引入了一个新特性,当使用urllib.urlopen打开一个 https 链接时,会验证一次 SSL 证书。所以很可能在
resp = urllib2.urlopen(req, timeout=5)
的时候,出现sll证书认证失败的情况。
URLError: <urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed这个时候有两种解决办法
context = ssl._create_unverified_context() resp = urllib2.urlopen(req, timeout=5, context=context)
import sslimport urllib2 ssl._create_default_https_context = ssl._create_unverified_context