raspberrypi树莓派+百度人脸识别api

官方教学视频:

link
all tutorial vedios

准备工作:

注册的百度云账号,申请人脸接口使用
将页面下拉

在这里插入图片描述
直达连接:link

相关文本文档:

在这里插入图片描述

安装api:

在这里插入图片描述

安装过程(采用第二中方式):

在这里插入图片描述

人脸识别管理:

创建应用:

在这里插入图片描述


直达link

创建用户组

在这里插入图片描述
在这里插入图片描述

新建用户

这里开始上传照片
在这里插入图片描述

test code(in the raspberryPi):

# accroding to the specified situation(your environment),do some modify to fit you.
from aip import AipFace
from picamera import PiCamera
import urllib.request
import RPi.GPIO as GPIO
import base64
import time
# 百度人脸识别API账号信息
APP_ID = '24400102'
API_KEY = 'obDY8f3e59LB3G0qH68T2x9F'
SECRET_KEY = 'bMOPk5TgTXkOealxksgX6H9ZYrFXqP63'
client = AipFace(APP_ID, API_KEY, SECRET_KEY)  # 创建一个客户端用以访问百度云
# 图像编码方式
IMAGE_TYPE = 'BASE64'
camera: PiCamera = PiCamera()  # 定义一个摄像头对象
# 用户组(改为你自己的用户组(在百度云中一致)
print("接入用户组:cxxu...")
GROUP: str = 'cxxu'

# 照相函数


def getimage() -> None:
    camera.resolution = (1024, 768)  # 摄像界面为1024*768
    print("#开始摄像")
    camera.start_preview()  # 开始摄像
    time.sleep(2)
    camera.capture('faceimage.jpg')
    print("拍照并保存")
    time.sleep(2)
# 对图片的格式进行转换


def transimage() -> bytes:
    print("转换图片格式...")
    f = open('faceimage.jpg', 'rb')
    img = base64.b64encode(f.read())
    return img
# 上传到百度api进行人脸检测


def upload_api(image:bytes) -> int:
    print("在百度云人脸库对应的分组中寻找有没有匹配的人脸")
    result = client.search(str(image, 'utf-8'), IMAGE_TYPE,
                           GROUP)  # 在百度云人脸库中寻找有没有匹配的人脸
    if result['error_msg'] == 'SUCCESS':  # 如果成功了
        name: str = result['result']['user_list'][0]['user_id']  # 获取名字
        score: float = result['result']['user_list'][0]['score']  # 获取相似度
        print("相似度:", score)
        if score > 80:  # 如果相似度大于80
            print("welcome!:"+name)
        else:
            print("Stranger")
            name = 'Unknow'
            return 0
        curren_time = time.asctime(time.localtime(time.time()))  # 获取当前时间

        # 将人员出入的记录保存到Log.txt中
        f = open('Log.txt', 'a')
        f.write("Person: " + name + "     " + "Time:" + str(curren_time)+'\n')
        f.close()
        return 1
    if result['error_msg'] == 'pic not has face':
        print("no faces found! ")
        time.sleep(2)
        return 0
    else:
        print(str(result['error_code'])+' ' + str(result['error_code']))
        return 0


# 主函数
if __name__ == '__main__':
    while True:
        print('system starting...')
        if True:
            getimage()  # take photo by the camera
            img = transimage()  # 转换照片格式
            res = upload_api(img)  # 将转换了格式的图片上传到百度云
            if(res == 1):  # 是人脸库中的人
                print("open the door(analog)")
            else:
                print("close the door (analog)")
            print('模拟门禁系统:稍等1+秒进入下一个')
            time.sleep(1)

the result(analog):

在这里插入图片描述

posted @ 2024-08-01 00:25  xuchaoxin1375  阅读(24)  评论(0)    收藏  举报  来源