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

编程

 1from urllib import request

2import base64

3import requests

4import re

5import json

6import urllib

7import os

8

9

10# 获取token

11def 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]

16return access_token

17

18# 打开文件夹

19def geturlPath(path):

20 dirs = os.listdir(path)

21 lst = []

22for dir1 in dirs:

23 pa = path + dir1

24 lst.append(pa)

25return lst

26

27# 打开本地图片,并转化为base64

28def open_pic2base(image):

29 f = open(image,"rb")

30 img = base64.b64encode(f.read()).decode("utf-8")

31return img

32

33# 对两张图片进行对比

34def check2pic(client_id,client_secret,image1,image2):

35 request_url = "https://aip.baidubce.com/rest/2.0/face/v3/match"

36for 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

53if content:

54 result = json.loads(content.decode("utf-8"))

55if result["error_code"] == 0:

56 score = result["result"]["score"]

57if score > 75:

58 with open("G:/images6/"+ image.split("/")[-1],"wb") as f:

59 f.write(b)

60 f.close()

61else:

62 errors = {}

63 error_msg = result["error_msg"]

64 errors[image.split("/")[-1]] = error_msg

65print(errors)

66if__name__ == "__main__":

67 client_id = "MeZaaKIbOt5DGp4cfxGpv4wa"

68 client_secret = "ImadHITTnAvtGkLeugrNUNuG3NOdiE7Q"

69 path = r"G:/images5/"

70

71 image1 = "G:images2gu1.jpg"

72 image2 = geturlPath(path)

73

74# 将两张图片进行对比,得出相似分

75 check2pic(client_id,client_secret,image1,image2)

 

以上是 百度云人脸识别API人脸对比 的全部内容, 来源链接: utcz.com/z/510473.html

回到顶部