Python2-调用Face++的接口进行人脸检测

参考博客: Python调用face++人脸检测API

结果如下:

检测结果如下:

Python2的运行代码如下:

# -*- coding:utf-8 -*-
# python 2.7
import cv2
import urllib2
import urllib
import time


#读取原图,并显示
img = cv2.imread("test2.jpg")
# cv2.namedWindow("Before")
# cv2.imshow("Before", img)
# cv2.waitKey(0)

#URL
http_url='https://api-cn.faceplusplus.com/facepp/v3/detect'
#用户信息
key = "JMuRNLHW5eJy08AgSjDaLQtCgPmdzi0H"
secret = "3wfQ_5tfVd2DjhCIJ83MP969bizMJpkE"
#图片存储路径
filepath = "test2.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 = (0,255,255)  # BGR
    thickness = 3
    cv2.rectangle(img, start, end, color, thickness)

cv2.namedWindow("After")
cv2.imshow("After", img)

cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite("res.png",img)

截图:

 注意:以上代码在Python2的环境可直接运行,但是在Python3的环境下,需要更改urllib2。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐