Based on Python2.7, Baidu face recognition online API call

1. Apply for Baidu face recognition application

First of all, you need to log in to baidu intelligent cloud platform and create applications after logging in. The application created is face recognition. By default, you have checked the relevant functions.

Once you’ve created your app, click Manage Apps and you’ll get the API Key and Secret Key.

2. Obtain the token

Now you can write code to call the online face detection API

The first step is to obtain the token for verification. The code is as follows. Note that the API Key and Secret Key applied by yourself are replaced.

def getToken(a):
    global token
    # client_id indicates the AK obtained from the official website, and client_secret indicates the SK obtained from the official website
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id= API Key & client_secret = your Secret Key'
    request = urllib2.Request(host)
    request.add_header('Content-Type'.'application/json; charset=UTF-8')
    response = urllib2.urlopen(request)
    content = response.read()
    if (content):
        token=json.loads(content)['access_token']
Copy the code

3. Base64 encoding of pictures

Images uploaded for detection must be Base64 encoded. Note that the base64 encoding of the image does not contain the image header, as follows:

def imgToBase64(imgPath):
    with open(imgPath, "rb") as f:  Convert to binary format
        base64_data = base64.b64encode(f.read())  Use base64 encryption
        return base64_data
Copy the code

4, face recognition

Call interface for face recognition, the code is as follows:

def faceDetect(imgBase64):
    Face Detection and Attribute Analysis
    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
    request_url = request_url + "? access_token=" + token
    request = urllib2.Request(request_url)
    request.add_header('Content-Type'.'application/json')
    data = {"image": imgBase64, "image_type": "BASE64"."face_field":"age,beauty,expression,face_shape,gender"}
    response = urllib2.urlopen(request, urllib.urlencode(data))
    content = response.read()
    if content:
        return content
Copy the code

Face_field is the most important parameter in the request. By default, face_field only returns the position, probability and rotation Angle of the face frame, age (age prediction),beauty (appearance level scoring),expression (expression) and other attributes, which need to be added to this parameter. Please refer to the official documentation for details:

5. Result rendering and visualization

Face recognition finally returns JSON data, but we often need to draw a frame, frame the face, and put some predicted properties on the label.

6. Source code

#coding:utf-8
import urllib,urllib2, sys
import ssl
import json
import base64
import cv2
global token
 
def getToken(a):
    global token
    # client_id indicates the AK obtained from the official website, and client_secret indicates the SK obtained from the official website
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id= your API Key&client _secret = your Secret Key'
    request = urllib2.Request(host)
    request.add_header('Content-Type'.'application/json; charset=UTF-8')
    response = urllib2.urlopen(request)
    content = response.read()
    if (content):
        token=json.loads(content)['access_token']
 
def faceDetect(imgBase64):
    Face Detection and Attribute Analysis
    request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
    request_url = request_url + "? access_token=" + token
    request = urllib2.Request(request_url)
    request.add_header('Content-Type'.'application/json')
    data = {"image": imgBase64, "image_type": "BASE64"."face_field":"age,beauty,expression,face_shape,gender"}
    response = urllib2.urlopen(request, urllib.urlencode(data))
    content = response.read()
    if content:
        return content
 
def imgToBase64(imgPath):
    with open(imgPath, "rb") as f:  Convert to binary format
        base64_data = base64.b64encode(f.read())  Use base64 encryption
        return base64_data
 
 
if __name__=="__main__":
 
    getToken()
    imgPath=r"C:\Users\lee\Pictures\lena.jpg"
    result=json.loads(faceDetect(imgToBase64(imgPath)))['result']
    face_list=result['face_list'] [0]
    location=face_list['location']
    age=face_list['age']
    beauty=face_list['beauty']
    expression=face_list['expression'] ['type']
    gender=face_list['gender'] ['type']
 
    img = cv2.imread(imgPath, cv2.IMREAD_COLOR)
    leftTopX=int(location['left'])
    leftTopY=int(location['top'])
    rightBottomX=int(leftTopX+int(location['width']))
    rightBottomY = int(leftTopY + int(location['height']))
    cv2.rectangle(img, (leftTopX, leftTopY), (rightBottomX, rightBottomY), (0.255.0), 2)
    font = cv2.FONT_HERSHEY_SIMPLEX
    # The first coordinate represents the starting position
    cv2.putText(img,"age:"+str(age),(0.20),font, 0.5, (200.255.255), 1)
    cv2.putText(img, "gender:" + gender.encode("utf-8"), (0.40), font, 0.5, (200.255.255), 1)
    cv2.putText(img, "beauty:" + str(beauty), (0.60), font, 0.5, (200.255.255), 1)
    cv2.putText(img, "expression:" + str(expression), (0.80), font, 0.5, (200.255.255), 1)
    cv2.imshow('image', img)
    cv2.waitKey(0)
 
    print("end")
Copy the code