利用百度接口进行人脸识别,根据返回的人脸location用opencv切割保存。

# coding : UTF-8

from aip import AipFace
import cv2
import numpy as np

save_path = 'D:\\workspaces\\test_faces\\save_faces\\'
APP_ID = '你自己的ID'
API_KEY = '你自己的key'
SECRET_KEY = '你自己的secret'

# 初始化AipFace对象
client = AipFace(APP_ID, API_KEY, SECRET_KEY)
# 读取图片
filePath = r"D:\workspaces\test_faces\pic.jpg"
img = cv2.imread(filePath)
def get_file_content(filePath):
    with open(filePath, 'rb') as fp:
        return fp.read()

options = {
    'max_face_num':50,
    'face_fields': "age,gender",
    }
result = client.detect(get_file_content(filePath),options)

faces = result['result']
num = len(faces)
print "一共"+str(num)+"张脸!"
face_rect = []
for i in range(num):
    face_rectangle = faces[i]['location']
    temp_face_rect = [face_rectangle['left'],face_rectangle['top'],face_rectangle['width'],face_rectangle['height']]
    face_rect.append(temp_face_rect)
temp_face_rect = np.array(face_rect)

j=0

for x,y,z,w in temp_face_rect:
    roiImg = img[y:y+w,x:x+z]
    cv2.imwrite(save_path+str(j)+'.jpg',roiImg)
    j=j+1
04-14 08:03