erlchixiha
 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 = \'***************\'
68     client_secret = \'*******************\'
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)

 

   

分类:

技术点:

相关文章:

  • 2021-12-16
  • 2021-09-20
  • 2021-11-02
  • 2021-11-01
  • 2021-11-21
  • 2021-09-18
  • 2021-09-13
猜你喜欢
  • 2021-09-07
  • 2021-11-03
  • 2021-12-15
  • 2020-04-21
  • 2021-12-25
相关资源
相似解决方案