欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  科技

百度云人脸识别API人脸对比

程序员文章站 2022-04-01 18:11:53
利用百度云人脸识别API人脸对比接口,将对比分数较高的图片存入指定的文件夹 ......
 1 from urllib import request
 2 import base64
 3 import requests
 4 import re
 5 import json
 6 import urllib
 7 import os
 8 
 9 
10 # 获取token
11 def get_token(client_id,client_secret):
12     host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+ client_id + '&client_secret='+ client_secret + ''
13     headers = {'content-type': 'application/json; charset=utf-8'}
14     res = requests.post(host, headers=headers)
15     access_token = re.findall('"access_token":"(.*?)"', res.text)[0]
16     return access_token
17 
18 # 打开文件夹
19 def geturlpath(path):
20     dirs = os.listdir(path)
21     lst = []
22     for dir1 in dirs:
23         pa = path + dir1
24         lst.append(pa)
25     return lst
26 
27 # 打开本地图片,并转化为base64
28 def open_pic2base(image):
29     f = open(image,'rb')
30     img = base64.b64encode(f.read()).decode('utf-8')
31     return img
32 
33 # 对两张图片进行对比
34 def check2pic(client_id,client_secret,image1,image2):
35     request_url = "https://aip.baidubce.com/rest/2.0/face/v3/match"
36     for image in image2:
37         a = open_pic2base(image)
38         b = base64.b64decode(a)
39         params = json.dumps(
40             [{"image": open_pic2base(image1), "image_type": "base64","quality_control": "low"},
41              {"image": a, "image_type": "base64","quality_control": "low"}])
42 
43         # 调用接口
44         access_token = get_token(client_id, client_secret)
45         request_url = request_url + "?access_token=" + access_token
46         params = params.encode("utf-8")
47         request = urllib.request.request(url=request_url, data=params)
48         request.add_header('content-type', 'application/json')
49 
50         response = urllib.request.urlopen(request)
51         content = response.read()
52         score = 0
53         if content:
54             result = json.loads(content.decode('utf-8'))
55             if result["error_code"] == 0:
56                 score = result["result"]["score"]
57                 if score > 75:
58                     with open('g:/images6/'+ image.split('/')[-1],'wb') as f:
59                         f.write(b)
60                         f.close()
61             else:
62                 errors = {}
63                 error_msg = result["error_msg"]
64                 errors[image.split('/')[-1]] = error_msg
65                 print(errors)
66 if __name__ == '__main__':
67     client_id = 'mezaakibot5dgp4cfxgpv4wa'
68     client_secret = 'imadhittnavtgkleugrnunug3nodie7q'
69     path = r'g:/images5/'
70 
71     image1 = 'g:\images2\gu1.jpg'
72     image2 = geturlpath(path)
73 
74     # 将两张图片进行对比,得出相似分
75     check2pic(client_id,client_secret,image1,image2)