百度人脸识别:最简单的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)

 

识别结果大概是这样 {'result': {'face_num': 1, 'face_list': [{'quality': {'occlusion': {'right_eye': 0, 'left_cheek': 0.1459853947, 'right_cheek': 0.05144193396, 'left_eye': 0.465408802, 'mouth': 0.02919708006, 'chin_contour': 0.01420217194, 'nose': 0}, 'illumination': 116, 'blur': 7.266304692e-06, 'completeness': 1}, 'age': 22, 'face_token': 'dc6f8f9df5d977ea476e2d04acdf5063', 'race': {'type': 'white', 'probability': 0.6173604727}, 'glasses': {'type': 'common', 'probability': 0.9834988713}, 'gender': {'type': 'male', 'probability': 0.655915916}, 'face_probability': 0.9185044169, 'beauty': 51.21487427, 'angle': {'roll': -2.750922441, 'yaw': 28.97134399, 'pitch': 5.202290535}, 'location': {'height': 65, 'top': 112.0704803, 'width': 76, 'left': 76.20765686, 'rotation': -4}, 'face_type': {'type': 'human', 'probability': 0.9992217422}, 'face_shape': {'type': 'oval', 'probability': 0.4419156313}, 'expression': {'type': 'none', 'probability': 0.9999142885}}]}, 'error_msg': 'SUCCESS', 'timestamp': 1537413754, 'cached': 0, 'error_code': 0, 'log_id': 9465840013520} 年龄:22 颜值:51.21487427 表情-type(none:不笑;smile:微笑;laugh:大笑):none 表情-probability(表情置信度,范围【0~1】,0最小、1最大):0.9999142885 脸型-type(square: 正方形 triangle:三角形 oval: 椭圆 heart: 心形 round: 圆形):oval 脸型-probability(置信度,范围【0~1】,代表这是人脸形状判断正确的概率,0最小、1最大):0.4419156313 性别-type(male:男性 female:女性):male 性别-probability(性别置信度,范围【0~1】,0代表概率最小、1代表最大。):0.655915916 是否带眼镜-type(none:无眼镜,common:普通眼镜,sun:墨镜):common 是否带眼镜-probability(眼镜置信度,范围【0~1】,0代表概率最小、1代表最大。):0.9834988713 人种-type(yellow: 黄种人 white: 白种人 black:黑种人 arabs: 阿拉伯人):white 人种-probability(人种置信度,范围【0~1】,0代表概率最小、1代表最大。):0.6173604727 真实人脸/卡通人脸 -type(human: 真实人脸 cartoon: 卡通人脸):human 真实人脸/卡通人脸 -probability(人脸类型判断正确的置信度,范围【0~1】,0代表概率最小、1代表最大。):0.9992217422
### 回答1: 人脸识别是通过计算机视觉和人工智能技术识别和分析人脸图像,进而实现人脸检测、人脸比对、人脸验证等功能。而百度提供的人脸识别API可以帮助我们快速、准确地实现人脸相关的功能。 要使用百度API进行人脸识别,首先需要在百度AI平台上注册账号并创建应用。在创建应用的过程中,会获得一个API Key和Secret Key,这两个密钥在我们的代码中起到了身份认证的作用。 使用Python调用百度API的步骤如下: 1. 安装必要的Python模块:在终端中使用pip命令安装需要的模块,如requests、base64等。 2. 导入所需的模块:在代码的开头导入需要使用的Python模块,如requests、base64等。 3. 设置API Key和Secret Key:将获得的API Key和Secret Key分别赋值给两个变量。 4. 读取待识别的人脸图像:使用Python的文件操作函数读取待识别的人脸图像文件,可以使用PIL等图像处理库对图像进行预处理。 5. 将图像转换为base64编码:使用base64等编码工具将人脸图像转换为base64编码的字符串。 6. 构建请求参数:将API Key、Secret Key和base64编码的人脸图像作为参数传递给API,并设置一些可选参数,如人脸识别的功能和阈值等。 7. 发送请求并获取结果:使用Python的请求库发送HTTP POST请求,并接收返回的结果。 8. 解析结果:对返回的结果进行解析,提取出需要的信息,如人脸的位置、特征等。 9. 处理结果:根据解析的结果进行相应的处理,如展示人脸图像、打印人脸信息等。 以上就是使用百度API进行人脸识别的基本步骤。当然,在实际应用中,还可以根据具体需求对结果进行进一步的处理和分析,例如人脸情绪分析、人脸属性检测等。 ### 回答2: 人脸识别是一种通过计算机技术来识别人脸的方法,而百度API提供了一种简单方便的方式来实现人脸识别。下面是使用百度API和Python代码进行人脸识别的示例: 首先,我们需要通过百度云控制台的人脸识别服务创建一个应用,并获取到API Key和Secret Key。 接下来,我们可以使用Python中的`requests`库来进行HTTP请求。首先,我们需要导入相应的库和模块: ```python import requests import base64 ``` 然后,我们需要定义获取API token的函数: ```python def get_access_token(api_key, secret_key): url = 'https://aip.baidubce.com/oauth/2.0/token' data = { 'grant_type': 'client_credentials', 'client_id': api_key, 'client_secret': secret_key } response = requests.post(url, data=data) access_token = response.json()['access_token'] return access_token ``` 接下来,我们可以定义一个函数来进行人脸识别: ```python def face_detection(api_key, secret_key, image_path): access_token = get_access_token(api_key, secret_key) url = 'https://aip.baidubce.com/rest/2.0/face/v3/detect' headers = { 'Content-Type': 'application/json' } with open(image_path, 'rb') as f: image = base64.b64encode(f.read()).decode('utf-8') data = { 'image': image, 'image_type': 'BASE64', 'face_field': 'age,gender,beauty', 'max_face_num': 10 } params = { 'access_token': access_token } response = requests.post(url, headers=headers, params=params, json=data) result = response.json() return result ``` 最后,我们可以调用上述函数来进行人脸识别,传入对应的API Key、Secret Key和人脸图片路径: ```python api_key = 'your_api_key' secret_key = 'your_secret_key' image_path = 'your_image_path' result = face_detection(api_key, secret_key, image_path) print(result) ``` 通过以上代码,我们可以使用百度API和Python来进行人脸识别。当然,以上代码只是简单的示例,具体的人脸识别功能还可以通过API的其他参数进行更多的设置和修改。 ### 回答3: 人脸识别是一种通过计算机技术识别和验证人脸特征的方法。百度提供了一系列人脸识别的API,可以通过Python代码使用这些API。 首先,需要在百度AI开放平台上注册账号,并创建一个应用,获取API Key和Secret Key。 接下来,安装百度AI SDK包。在Python中,可以使用pip来安装: ``` pip install baidu-aip ``` 导入baidu-aip包,并初始化AipFace对象: ```python from aip import AipFace # 设置APPID/AK/SK APP_ID = 'your_app_id' API_KEY = 'your_api_key' SECRET_KEY = 'your_secret_key' client = AipFace(APP_ID, API_KEY, SECRET_KEY) ``` 接下来,可以使用AipFace对象调用百度API的人脸识别功能。以下是一个简单的人脸检测代码示例: ```python import base64 # 读取图片并进行Base64编码 with open("face.jpg", "rb") as f: image = base64.b64encode(f.read()).decode("utf-8") # 调用人脸检测API result = client.detect(image, 'BASE64') # 解析结果 if 'result' in result: face_num = result['result']['face_num'] face_list = result['result']['face_list'] for face in face_list: face_location = face['location'] left = face_location['left'] top = face_location['top'] width = face_location['width'] height = face_location['height'] print(f"人脸位置:left={left}, top={top}, width={width}, height={height}") else: print("人脸检测失败") ``` 以上是一个简单的人脸检测的例子,可以通过修改参数和调用其他API实现不同的人脸识别功能,如人脸对比、人脸搜索等。 通过百度API和Python代码,我们可以快速实现人脸识别的功能,方便地应用于各种项目和应用场景。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

柳鲲鹏

能给阁下一点帮助,非常荣幸

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值