Baidu AI calls for face retrieval

 1 import base64
 2 import json
 3 import requests
 4 class BaiduPicIndentify:
 5     def __init__(self, img):
 6         self.AK = "你的AK"
 7         self.SK = "你的SK"
 8         self.img_src = img
 9         self.headers = {
10             "Content-Type": "application/json; charset=UTF-8"
11         }
12 
13     def get_accessToken(self):
14         host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + self.AK + '&client_secret=' + self.SK
15         response = requests.get(host, headers=self.headers)
16         json_result = json.loads(response.text)
17         return json_result['access_token']
18 
19     def img_to_BASE64(slef, path):
20         with open(path, 'rb') as f:
21             base64_data = base64.b64encode(f.read())
22             return base64_data
23 
24     def detect_face(self):
25         # 人脸检测与属性分析
26         img_BASE64 = self.img_to_BASE64(self.img_src)
27         request_url = "https://aip.baidubce.com/rest/2.0/face/v3/detect"
28         post_data = {
29             "image": img_BASE64,
30             "image_type": "BASE64",
31             "face_field": "gender,age,beauty,gender,race,expression",
32             "face_type": "LIVE",
33             "max_face_num":5,
34         }
35         access_token = self.get_accessToken()
36         request_url = request_url + "?access_token=" + access_token
37         response = requests.post(url=request_url, data=post_data, headers=self.headers)
38         json_result =json.loads (response.text)
 39          Print (json_result)
 40          IF json_result [ ' ERROR_MSG ' !] = ' PIC Not face has ' :
 41 is              Print ( " image contains a face number: " , json_result [ ' Result ' ] [ ' face_num ' ])
 42              for i in the Range (json_result [ ' the Result ' ] [ ' face_num ' ]):
 43                  Print ( " picture characters contained Age:" , Json_result [ ' Result ' ] [ ' face_list ' ] [I] [ ' Age ' ])
 44 is                  Print ( " images containing character color values Rating: " , json_result [ ' Result ' ] [ ' face_list ' ] [I] [ ' Beauty ' ])
 45                  Print ( " images containing people gender: " , json_result [ ' Result ' ] [ ' face_list ' ] [I] [ 'gender'] [ ' Type ' ])
 46 is                  Print ( " image contains characters race: " , json_result [ ' Result ' ] [ ' face_list ' ] [I] [ ' Race ' ] [ ' type ' ])
 47                  Print ( " picture contains expressions of the characters: " , json_result [ ' the Result ' ] [ ' face_list ' ] [i] [ ' expression The ' ] [ ' of the type '])
48                 Print ( " next picture " )
 49  IF  the __name__ == ' __main__ ' :
 50      img_src = INPUT ( ' Enter local image path to be detected: ' )
 51 is      baiduDetect = BaiduPicIndentify (img_src)
 52 is      baiduDetect.detect_face ()

 

Guess you like

Origin www.cnblogs.com/tianqianlan/p/11615375.html