Python calls Baidu API for face comparison

1. About the author

Bai Xiaohua, female, School of Electronic Information, Xi'an Polytechnic University, graduate student of class 2021
Research direction: image processing, target detection
Email: [email protected]

Wu Yanzi , female, School of Electronic Information, Xi'an Polytechnic University, 2021 graduate student, Zhang Hongwei Artificial Intelligence Research Group
Research direction: Pattern Recognition and Artificial Intelligence
Email: [email protected]

2. Introduction to Base64 knowledge

2.1 What is Bsae64

Base64 is one of the most common encoding methods for transmitting 8Bit bytecodes on the Internet. Base64 is a method of representing binary data based on 64 printable characters.
What are "printable characters"? Why use it to transmit 8Bit bytecode?
First of all, before answering these two questions, it is necessary to think about when Base64 needs to be used. Base64 is generally used to transmit binary data under the HTTP protocol. Since the HTTP protocol is a text protocol, the binary data needs to be converted into character data to transmit binary data under the HTTP protocol. Direct conversion is not possible, however, because network transmissions can only transmit printable characters. The value range of the ASCII code is [0, 127], where [32, 126] are printable characters, and the rest are non-printable characters. That is to say, network transmission can only transmit these 95 characters, and characters that are not within this range cannot be transmitted. So how can other characters be transmitted? One way is to use Base64.

2.1 Bsae64 encoding principle

The idea of ​​Base64 encoding is to use 64 basic ASCII characters to re-encode the data.
1. Divide the data to be encoded into byte arrays, take 3 bytes as a group, arrange the 24-bit data in sequence, and then divide the 24-bit data into 4 groups, that is, 6 bits in each group;
2. Then in The highest bit of each group is filled with two 0s to make up one byte, so that a 3-byte group of data is re-encoded into 4 bytes;
3. When the number of bytes of the data to be encoded is not Integer multiples of 3, that is to say, the last group is not enough for 3 bytes when grouping. At this time, 1 to 2 0 bytes are filled in the last group, and 1 to 2 = signs are added at the end after the final encoding is completed. .
This experiment mainly uses Base64 to encode the face picture, and then compares the encoded files to complete the similarity comparison.

3. Experimental procedure

3.1 Experimental process

1. First register a Baidu account
2. Baidu AI platform https://ai.baidu.com/, find Open Capabilities > Face and Human Detection > Face Comparison > Use Now > Create App
insert image description here

, click Create to get API Key and Secret Key
insert image description here
3. Install the required libraries: pip install baidu-aip

3.2 Experimental code

from urllib import request
import requests
import json
import base64

def gettoken():
    ak = '******' #获取到的API Key
    sk = '******' #获取到的Secret Key
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+ak+'&client_secret='+sk
    my_request = request.Request(host)
    my_request.add_header('Content-Type', 'application/json; charset=UTF-8')
    response = request.urlopen(my_request)
    content = response.read() #获得请求结果
    content = bytes.decode(content)#结果转化为字符
    content = eval(content[:-1])#转化为字典
    return content['access_token']
#图片转码
def to_base64(file_name1,file_name2):
    with open(file_name1,'rb')as f1:
        base64_data1 = base64.b64encode(f1.read())
        image_1 = str(base64_data1,'utf-8')
    with open(file_name2,'rb')as f2:
        base64_data2 = base64.b64encode(f2.read())
        image_2 = str(base64_data2,'utf-8')
        return image_1,image_2

request_url = "https://aip.baidubce.com/rest/2.0/face/v3/match"
image_1, image_2 = to_base64('1.jpg','3.jpg')
params = json.dumps(
[{
    
    "image": image_1, "image_type": "BASE64", "face_type": "LIVE", "quality_control": "LOW"},
{
    
    "image": image_2, "image_type": "BASE64", "face_type": "CERT", "quality_control": "LOW"}]).encode(encoding='UTF8')

access_token = gettoken()
request_url = request_url + "?access_token=" + access_token
my_request = request.Request(url=request_url,data = params)
my_request.add_header('Content-Type','json')
#urlencode处理需提交的数据
response = request.urlopen(my_request)
null =0
content = response.read()
content = bytes.decode(content)
content = eval(content)
result = content['result']
score = result['score']
print('相似度:',score)

3.3 Running Results

The face similarity 0~100 is output (the similarity in this experiment is 91.96734319)
insert image description here

3.4 Problem Analysis

insert image description here
Description of the problem encountered: The running result reports an error showing KeyError: 'result'

Reason for the error: Through debugging, it is found that the error code: 18 will be displayed at the result, and the corresponding error is Open api qps request limit reached. Check the error code (link) in the text recognition document and find that the reason is: QPS exceeds the quota, the free quota concurrency limit is 2QPS, and the concurrency limit is 10QPS after opening the pay-as-you-go or purchasing the times package, if you need more concurrency , you can choose to purchase the QPS overlay package; for APIs that do not support billing, you can submit a work order on the console to apply for a limit increase. That is to say, we have no free credit to call the interface, so the identification has no result.
Solution: After completing personal authentication, Baidu Smart Cloud can receive free resources, so get resources under the created application, wait for about half an hour to return, and then run the code to complete. identify.

refer to

Baidu API realizes face comparison .
What is Base64 .

Guess you like

Origin blog.csdn.net/m0_37758063/article/details/123645068