Baidu AI - face recognition

AI is a hot word now. BAT three companies are also on the way of AI open source. At present, baidu is a little ahead in AI.

Today, we use the functions provided by Baidu AI open platform to realize the function of face detection.

Interface documentation:

Before you start, you need to apply for an application, which has some permissions to use Baidu AI.

See this website for details. It's very simple:

You also need to prepare some python libraries:

pip install baidu-aip

pip install Pillow

According to the documents provided by Baidu AI platform, what we need to do is to build a AipFace and then call the detect method.

Script directly: (

# -- coding: utf-8 --

from aip import AipFace

from PIL import Image, ImageDraw

import sys

# Test parameters, if there is no picture path, return

if len(sys.argv) <= 1:

    print 'Now params are: ', sys.argv,len(sys.argv)

    print "You should input a imagepath!"


# Get picture content

filepath = sys.argv[1]

with open(filepath, 'rb') as fp:

    image =

# Open the ai client. The following parameters are obtained after application: AppID, API Key, Secret Key

client = AipFace(' AppID ', ' API Key ',' Secret Key ')

# Filling parameter, only one face is detected here

options = {}

options['max_face_num'] = 1

options['face_fields'] = {'age'}

# Call the detect method of ai client. The result of this method is the data after face detection

result = client.detect(image, options)

print result

# Analyze the position parameters in the returned data to obtain the rectangular information of the face

location = result['result'][0]['location']

width = location['width']

height = location['height']

left = location['left']

top = location['top']

right = left + width

bottom = top + height

# Use PIL to reopen the picture and draw the rectangle where the face is

img =

imgDraw = ImageDraw.Draw(img)

imgDraw.rectangle(((left, top), (right, bottom)), outline=(255, 0, 0))

Execute command:

python your_img_path

The results of the detection are as follows:


  u'log_id': 3799754530011917,

  u'result_num': 1,

  u'result': [


      u'rotation_angle': -5,

      u'yaw': -10.247494697571,

      u'age': 22,

      u'location': {

        u'width': 197,

        u'top': 94,

        u'height': 177,

        u'left': 72


      u'pitch': 7.9190526008606,

      u'roll': -5.076274394989,

      u'face_probability': 1




Compare the results before and after:

As can be seen from the above, the detection is basically accurate.

I tested several sets of pictures and found that the test results were slightly lower.

Other references:

Picture processing frame PIL:

Tags: Python pip SDK

Posted on Thu, 30 Apr 2020 06:26:49 -0700 by matt1019