python下的face++ 人脸检测API调用及画特征点和人脸框

本文阐述了调用face++ API的方法,及把接收到的特征点绘制在图片上的方法。

python版本:python 3.6

需要的包:opencv

# -*- coding: utf-8 -*-
"""
Created on Tue Apr 17 17:39:08 2018

@author: DSY
"""

import cv2  
import requests  
import json  

url = 'https://api-cn.faceplusplus.com/facepp/v3/detect'  
files = {'image_file':open('your-image-address', 'rb')}  
payload = {'api_key': 'your-api-key',  
           'api_secret':'your-api-secret',  
           'return_landmark': 2,  
           'return_attributes':'none'}  
r = requests.post(url,files=files,data=payload)  
data=json.loads(r.text)

#%%
#print request content,you can also use r.+tab to see more things.
#print(r.text)  
width = data['faces'][0]['face_rectangle']['width']  
top = data['faces'][0]['face_rectangle']['top']  
height = data['faces'][0]['face_rectangle']['height']  
left = data['faces'][0]['face_rectangle']['left']  
img = cv2.imread("E:\\3Dface\\3D\\obj\\TL2807.bmp")  
vis = img.copy()
#draw face rectangle
#cv2.rectangle(vis, (left, top), (left+width, top+height),(0, 255, 0), 1)

#%%
#draw face landmarks
for j in (0,len(data['faces'])-1):
    for i in data['faces'][j]['landmark']:
        cor=data['faces'][j]['landmark'][i]
        x=cor["x"]
        y=cor["y"]
        cv2.circle(vis, (x,y), 2, (0,255,0),-1)
#%%
cv2.imshow("Image", vis)  
cv2.waitKey(0)
#save image with landmarks
cv2.imwrite("file-save-address",vis)
cv2.destroyAllWindows()

上述是总的程序,下面分块展开。

1、访问API并接收API的数据,存到变量data(r.text)中。变量类型为一个dict。可以自己print看具体。具体API的参数可以访问face++的网页,在payload里添加或删除。值得一提的是return_landmark中可以选择0,1,2。0是无landmark,1是83个,2是106个。

import cv2  
import requests  
import json  

url = 'https://api-cn.faceplusplus.com/facepp/v3/detect'  
files = {'image_file':open('your-image-address', 'rb')}  
payload = {'api_key': 'your-api-key',  
           'api_secret':'your-api-secret',  
           'return_landmark': 2,  
           'return_attributes':'none'}  
r = requests.post(url,files=files,data=payload)  
data=json.loads(r.text)

2、通过遍历字典,用opencv来在在图上进行绘画。opencv的基本操作。前半部分绘制人脸框,后半部分遍历点,并绘制,对于多张人脸,也都能画上。

width = data['faces'][0]['face_rectangle']['width']  
top = data['faces'][0]['face_rectangle']['top']  
height = data['faces'][0]['face_rectangle']['height']  
left = data['faces'][0]['face_rectangle']['left']  
img = cv2.imread("E:\\3Dface\\3D\\obj\\TL2807.bmp")  
vis = img.copy()
#draw face rectangle
#cv2.rectangle(vis, (left, top), (left+width, top+height),(0, 255, 0), 1)

#%%
#draw face landmarks
for j in (0,len(data['faces'])-1):
    for i in data['faces'][j]['landmark']:
        cor=data['faces'][j]['landmark'][i]
        x=cor["x"]
        y=cor["y"]
        cv2.circle(vis, (x,y), 2, (0,255,0),-1)
#%%
cv2.imshow("Image", vis)  
cv2.waitKey(0)
#save image with landmarks
cv2.imwrite("file-save-address",vis)
cv2.destroyAllWindows()

求打赏!谢谢老板!

你可能感兴趣的:(Python,人脸)