安装SDK:

pip install baidu-aip

如果在pycharm里也可以在setting----Project Interpreter---右边绿色加号,输入baidu,安装baidu-aip

入门代码:

先去百度AI开放平台注册一个账号,然后开通人脸识别,免费的

http://ai.baidu.com/tech/face

之后把得到的Api key secretkey 填进去。

from aip import AipFace
 
""" 你的 APPID AK SK """
APP_ID = '你的 App ID'
API_KEY = '你的 Api Key'
SECRET_KEY = '你的 Secret Key'
 
client = AipFace(APP_ID, API_KEY, SECRET_KEY)
 
""" 读取图片 """
def get_file_content(filePath):
  with open(filePath, 'rb') as fp:
    return fp.read()
 
images = [
  get_file_content('example0.jpg'),
  get_file_content('example1.jpg'),
]
 
""" 调用人脸比对 """
result_json=client.match(images);
print(result_json)

会自动把你当前工程目录下的example0.jpg 和example1.jpg进行比对。

最后会得到这样一个json字符串

{'result': [{'index_i': '0', 'index_j': '1', 'score': 21.207210540771}], 'result_num': 1, 'log_id': 2864712345030414}

里面的score就是两张人脸的相似度 了,这里我用的不同的人脸,只有21%左右

可以再写一个判断的方法:

def judge(images):
  result_json = client.match(images);
  result = result_json['result'][0]['score']
  if result > 80:
    print("同一個人")
  else:
    print("不是同一個人")