Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This paper adopts the AI interface provided by Baidu development platform to recognize and register faces and complete face comparison. Software uses QT design, real-time reading computer camera data display on the screen, click the button can register the current camera picture of the face, upload to the server’s face library, can also compare the current face, get the degree of acquaintance.

First, Baidu face comparison interface introduction

Baidu official website address: ai.baidu.com/tech/face/c…

Face comparison effect can be tested online:

High recognition rate:

Using the online API call interface to complete face comparison operations is free, but there is a limit to the number of concurrent operations. It also supports offline deployment and is flexible to use.

In the following pages can be opened service: console.bce.baidu.com/ai/?_=15764…

Face contrast using tutorial: cloud.baidu.com/doc/FACE/s/… Here the official provided a very detailed documentation, mainstream languages have SDK packages to download, but also code cases.

Second, sample code

2.1 The UI interface is developed using QT

2.2 Register face core code

// Register a face
void Widget::RegFace(const QImage image,QString group_id,QString user_id,QString user_info)
{

    QString requestUrl;
    QNetworkRequest request;

    // Store the image BASE64 encoding
    QString imgData;

    // Package request parameter assignment
    QJsonObject post_data;
    QJsonDocument document;

    // Set the request address
    QUrl url;
    QByteArray post_param;

    // Address of the request for face registration
    requestUrl = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add";

    // Set the data submission format
    request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));

    // Base64 encodes the image
    imgData = QString(toBase64(image)); // The size of the encoded image does not exceed 2M

    // Set request parameters: generic request parameters
    post_data.insert("image",imgData);

    // Set request parameters:
    post_data.insert("image_type"."BASE64"); //(The total data size should be less than 10M
    post_data.insert("group_id",group_id);  / / group ID
    post_data.insert("user_id",user_id);    / / user ID
    post_data.insert("user_info",user_info); // User information

    // Construct the request
    url.setUrl(requestUrl + "? access_token=" + ui->lineEdit_access_token->text());
    request.setUrl(url);

    document.setObject(post_data);
    post_param = document.toJson(QJsonDocument::Compact);

    // Send the request
    manager->post(request, post_param);
}

Copy the code

2.3 Face Search

// Face search function
void Widget::FindFace(const QImage image)
{
    QString requestUrl;
    QNetworkRequest request;

    // Store the image BASE64 encoding
    QString imgData;

    // Package request parameter assignment
    QJsonObject post_data;
    QJsonDocument document;

    // Set the request address
    QUrl url;
    QByteArray post_param;

    // Face search request address
    requestUrl = "https://aip.baidubce.com/rest/2.0/face/v3/search";

    // Set the data submission format
    request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json"));

    // Base64 encodes the image
    imgData = QString(toBase64(image)); // The size of the encoded image does not exceed 2M

    // Set request parameters: generic request parameters
    post_data.insert("image",imgData);

    // Set request parameters:
    post_data.insert("image_type"."BASE64"); //(The total data size should be less than 10M
    post_data.insert("group_id_list"."wbyq1");  / / group ID

    // Construct the request
    url.setUrl(requestUrl + "? access_token=" + ui->lineEdit_access_token->text());
    request.setUrl(url);

    document.setObject(post_data);
    post_param = document.toJson(QJsonDocument::Compact);

    // Send the request
    manager->post(request, post_param);
}

Copy the code

2.4 base64 encoding

/* Base64 encodes the image */
QByteArray Widget::toBase64(const QImage &image)
{
    // The image to be detected is BASE64 encoded
    QByteArray ba;
    QBuffer buffer(&ba);
    buffer.open(QIODevice::WriteOnly);
    // Write image data to BA in PNG format
    image.save(&buffer,"jpg");

    buffer.close(a);return ba.toBase64(a); }Copy the code

2.5 Analysis of feedback results

// Parse the feedback
void Widget::replyFinished(QNetworkReply *reply)
{
    displayInfo="";
    ui->label_state_display->setText("");

    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(a);// Read all data
    QByteArray replyData = reply->readAll(a);// Determine the status code
    if(200! = statusCode) {//qDebug()<<"reply data is:"<<QString(replyData);
       // qDebug() << "Status code is error:" << statusCode;
        displayInfo=tr("Parsing error, error code :%1,%2").arg(statusCode).arg(QString(replyData));
        ui->label_state_display->setText(displayInfo);
        return;
    }

    //qDebug()<<"reply data is:"<<QString(replyData);

    // Face register
    if(function_select==0)
    {
        // Parse the data
        QJsonParseError json_error;
        QJsonDocument document = QJsonDocument::fromJson(replyData, &json_error);
        if(json_error.error == QJsonParseError::NoError)
        {
            // Determine if it is an object and start parsing the data
            if(document.isObject())
            {
                QJsonObject obj = document.object(a);// Parse the error code
                if(obj.contains("error_code"))
                {
                    int error_code=obj.take("error_code").toInt(a);switch (error_code) {
                    case 0: / / success
                        displayInfo="-- Face registered successfully --";
                        break;
                    case 222202:
                        displayInfo="Face registration error: no face detected in picture";
                        break;
                    case 222210:
                        displayInfo="The number of faces under the user in the face library exceeds the limit \n The current maximum number of faces under the limit per user is 20.";
                        break;
                    case 110:
                    case 111:
                        displayInfo="Token is valid for 30 days and needs to be replaced regularly.\n Contact the software author.";
                        break;
                    default:
                        if(obj.contains("error_msg"))
                        {
                            displayInfo+=tr("Face registration error :%1\n").arg(error_code);
                            displayInfo+=obj.take("error_msg").toString(a); } } } } } }else if(function_select==1) // Face search
    {
        // Parse the data
        QJsonParseError json_error;
        QJsonDocument document = QJsonDocument::fromJson(replyData, &json_error);
        if(json_error.error == QJsonParseError::NoError)
        {
            // Determine if it is an object and start parsing the data
            if(document.isObject())
            {
                QJsonObject obj = document.object(a);// Parse the error code
                if(obj.contains("error_code"))
                {
                    int error_code=obj.take("error_code").toInt(a);switch (error_code) {
                    case 0: / / success
                        displayInfo="-- face search succeeded --\n";
                        break;
                    case 222202:
                        displayInfo="Face search error: no face detected in image";
                        break;
                    case 110:
                    case 111:
                        displayInfo="Token keys are valid for 30 days and need to be replaced regularly.\n Contact the author of the software.";
                        break;
                    default:
                        if(obj.contains("error_msg"))
                        {
                            displayInfo+=tr("Face search error :%1\n").arg(error_code);
                            displayInfo+=obj.take("error_msg").toString();
                        }
                    }

                    // Face search succeeded
                    if(error_code==0)
                    {
                         if(obj.contains("result"))
                          {
                                QJsonObject obj1=obj.take("result").toObject(a);// Find the array
                                QJsonArray faceArray = obj1.take("user_list").toArray(a);for(int i = 0; i < faceArray.size(a); i++) { QJsonObject faceObj = faceArray.at(i).toObject(a);/ / similarity
                                    if(faceObj.contains("score"))
                                    {
                                         displayInfo+=tr("Recognition similarity :%1\n").arg(faceObj.take("score").toDouble());
                                    }

                                    // Face group ID
                                    if(faceObj.contains("group_id"))
                                    {
                                         displayInfo+=tr("Face grouping :%1\n").arg(faceObj.take("group_id").toString());
                                    }
                                    / / user ID
                                    if(faceObj.contains("user_id"))
                                    {
                                         displayInfo+=tr("Telephone Number :%1\n").arg(faceObj.take("user_id").toString());
                                    }
                                    // User information
                                    if(faceObj.contains("user_info"))
                                    {
                                         displayInfo+=tr(Name: % 1 \ "n").arg(faceObj.take("user_info").toString());
                                    }

                                }
                          }
                    }
                }
             }
         }
    }
    ui->label_state_display->setText(displayInfo);
}

Copy the code