百度人脸识别:最简单的Python调用

  • 安装
​pip install baidu-aip
  •  代码
# -*- coding: UTF-8 -*-  
 
from aip import AipFace
import base64
 
# 参考《百度人脸识别:功能开通》
BAIDU_APP_ID     = "15"
BAIDU_API_KEY    = "4o"
BAIDU_SECRET_KEY = "PY"
 
BAIDU_IMAGE_TYPE = "BASE64"
BAIDU_GROUP_ID   = "quantum6"
 
AVATAR_PATH      = "../faceid_avatar/"
 
# 图片转换为base64
def baidu_face_image_to_base64(image_file):
    image_open = open(image_file, 'rb')
    image_data = base64.b64encode(image_open.read())
    image_data = str(image_data)
    return image_data
 
# 初始化,读取某个目录的员工头像,并加到百度上
def baidu_face_init():
    global baidu_face_client
    baidu_face_client = AipFace(BAIDU_APP_ID, BAIDU_API_KEY, BAIDU_SECRET_KEY)
    images = glob.glob(os.path.join(AVATAR_PATH, "*.jpg"))
    if len(images) == 0:
        raise RuntimeError("no person in the database, please check folder.")
    for image in images:
        image_base64 = baidu_face_image_to_base64(image)
        # 从文件名中截取
        user_id = os.path.basename(image)[:-4]
        response = baidu_face_client.addUser(image_base64, BAIDU_IMAGE_TYPE, BAIDU_GROUP_ID, user_id)
        print(response)
 
# 检查这个图片是否是员工
def baidu_face_check(image):
    image_base64 = baidu_face_image_to_base64(image)
    response = baidu_face_client.search(image_base64, BAIDU_IMAGE_TYPE, BAIDU_GROUP_ID)
    print(response)
 
    if (0 == response["error_code"]):
        response = response["result"]["user_list"][0]
        user_id  = response["user_id"]
        score    = response["score"]
        print(user_id, score)
        return user_id, score
    else:
        return "error"
 
 
# 检查是否有人脸
def baidu_face_dected(image_file):
    options = {}
    options["max_face_num"] = 3
 
    image_base64 = baidu_face_image_to_base64(image)
    response = baidu_face_client.detect(image_base64, BAIDU_IMAGE_TYPE, options)
    if (0 == response["error_code"]):
        print(response["result"])
    else:
        return TEXT_NOT_FOUND
 
# TEST
baidu_face_init()
TEST_STRANGER_FILE="../faceid_stranger_avatar/2.jpg"
# 可以先判断是否有人脸,再进行比较
#baidu_face_dected(TEST_STRANGER_FILE)
 
baidu_face_check(TEST_STRANGER_FILE)
上一篇:Delphi编辑器使用指南


下一篇:网页自适应跟随系统深色模式