Call Baidu API to realize face recognition

1. Code

from aip import AipFace
import cv2
import time
import base64
from PIL import Image
from io import BytesIO
import pyttsx3
# """ 你的 APPID AK SK """
APP_ID = '1965####'
API_KEY = 'YXL65ekIloykyjrT4kzc####'
SECRET_KEY = 'lFiapBoZ5eBwOFyxMbiwQDmClg1u####'

client = AipFace(APP_ID, API_KEY, SECRET_KEY)

# def frame2base64(frame):
#     img = Image.fromarray(frame) #将每一帧转为Image
#     output_buffer = BytesIO() #创建一个BytesIO
#     img.save(output_buffer, format='JPEG') #写入output_buffer
#     byte_data = output_buffer.getvalue() #在内存中读取
#     image = base64.b64encode(byte_data) #转为BASE64
#     return image #转码成功 返回base64编码

def generate():
    camera = cv2.VideoCapture(0)
    engine = pyttsx3.init()
    try:
        while True:
            engine = pyttsx3.init()
            ret, img = camera.read()
            cv2.imwrite("E://Ana/face.png",img)
            cv2.imshow("调用摄像头", img)
            imageType = "BASE64"
            groupIdList = "1,2,3,4"


            """ 如果有可选参数 """
            options = {}
            options["max_face_num"] = 4
            options["match_threshold"] = 70
            options["quality_control"] = "NORMAL"
            options["liveness_control"] = "NONE"
            # options["user_id"] = "233451"
            options["max_user_num"] = 4

#             """ 带参数调用人脸搜索 """
            with open("E://Ana/face.png", 'rb') as fp:
                imageB = base64.b64encode(fp.read())
            image = str(imageB, 'utf-8')
            """ 调用人脸搜索 """
            result = client.search(image, imageType, groupIdList, options)
            engine.runAndWait()
            print(2)
            if result:
                if not result['result']:
                    continue
                name = result['result']['user_list'][0]['user_id']#获取名字
                score = result['result']['user_list'][0]['score']#获取相似度
                if name == 'cgh_1':
                    if score>80:
                        print(score)
                        print(name)
                        engine.say("华来了")
                elif name == 'yjc_1':
                    if score > 80:
                        print(score)
                        print(name)
                        engine.say("杨来了")
                elif name == 'cjy_1':
                    if score > 80:
                        print(score)
                        print(name)
                        engine.say("言来了")
                elif name == 'hjy_1':
                    if score > 80:
                        print(score)
                        print(name)
                        engine.say("怡来了")
                else:
                    print("匹配失败")
            else:
                continue
    except Exception as e:
        print(e)
    finally:
        # 释放资源
        engine.runAndWait()
        camera.release()
        cv2.destroyAllWindows()
 
generate()

2. Implementation steps

2.1. Get Baidu ID and key

You can apply for a free API account in the Baidu API. There are thousands of free face recognitions every day. The picture below shows the API account I applied for, and then create the face that needs to be recognized in the face database.
Insert picture description here
Insert picture description here

2.2, create a client
APP_ID = '1965####'
API_KEY = 'YXL65ekIloykyjrT4kzc####'
SECRET_KEY = 'lFiapBoZ5eBwOFyxMbiwQDmClg1u####'
client = AipFace(APP_ID, API_KEY, SECRET_KEY)
2.3, realize face recognition

The main content is that the parameters need to be modified by yourself, then get the video image, and then look at it by comparison, the name of the comparison, and then look at the score. I added a computer to broadcast it, so as long as it is recognized, the computer will Broadcast, the delay does not exceed seconds.

Guess you like

Origin blog.csdn.net/qq_45125250/article/details/107034691