recg.py 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # encoding:utf-8
  2. import base64
  3. import urllib
  4. import urllib2, json
  5. from token import GetToken
  6. '''
  7. 人脸对比
  8. '''
  9. url = "https://aip.baidubce.com/rest/2.0/face/v3/match"
  10. def FaceRecg(face1, face2, token):
  11. global url
  12. f = open(face1, 'rb')
  13. # 参数images:图像base64编码
  14. img1 = base64.b64encode(f.read())
  15. # 二进制方式打开图文件
  16. f = open(face2, 'rb')
  17. # 参数images:图像base64编码
  18. img2 = base64.b64encode(f.read())
  19. params = json.dumps(
  20. [{"image": img1, "image_type": "BASE64", "face_type": "LIVE", "quality_control": "LOW"},
  21. {"image": img2, "image_type": "BASE64", "face_type": "LIVE", "quality_control": "LOW"}
  22. ])
  23. '''
  24. params = {"image":img1 + ',' + img2,
  25. "image_type":"BASE64",
  26. "face_type":"LIVE",
  27. "quality_control":"LOW",
  28. "liveness_control":"HIGH"}
  29. params = urllib.urlencode(params)
  30. '''
  31. request_url = url + "?access_token=" + token
  32. request = urllib2.Request(url=request_url, data=params)
  33. request.add_header('Content-Type', 'application/json')
  34. #response = urllib2.urlopen(request)
  35. response = None
  36. try:
  37. response = urllib2.urlopen(request)
  38. except urllib2.URLError,e:
  39. print e.reason
  40. print e.reason[0]
  41. print e.reason[1]
  42. if (response == None):
  43. print "response=null"
  44. return None
  45. content = response.read()
  46. if content:
  47. print content
  48. js = json.loads(content)
  49. if (js.has_key('error_msg') and js['error_msg'] == "SUCCESS"):
  50. if (js.has_key('result')):
  51. #for item in js['result']:
  52. print(u"%2.2f%% " % (float(js['result']['score'])))
  53. if(float(js['result']['score']) >= 80):
  54. print 'OK'
  55. else:
  56. print 'FAIL'
  57. if __name__ == "__main__":
  58. #前面两个参数是图片路径
  59. Token = GetToken()
  60. FaceRecg('pic/1.jpg', 'pic/2.jpg', Token)