Accurate identification of bank card information - Smart fast card binding

1. Preface

Under the trend of AI Artificial Intelligence, there are many products that are convenient for people's life: face recognition technology - complete face unlocking and face core; License plate recognition - complete the design of parking lot unmanned billing system; Automatic driving - assisted driving, automatic parking and so on, there are many related applications.

This article uses the bank card information identification interface provided by Huawei cloud to extract the detailed information of the identified bank card. This interface is one of the character recognition interfaces. Bank card information identification is mainly used in many places, such as binding cards in various shopping app s, filling in card numbers for insurance online claims, binding cards with social communication software, binding cards with securities software, etc. in the past, the card numbers were manually entered, It's very inconvenient. With the AI recognition function, you can save the bank card picture in the mobile phone in advance or choose to shoot on site. In this way, the software can quickly identify the current bank card category, bank, card number and other information through the picture, and complete the automatic filling, which is very convenient for the user experience.

2. Character recognition cloud service

2.1 open character recognition service function

Address: https://console.huaweicloud.com/ocr/?region=cn -north-4&locale=zh-cn#/ocr/overview

The character recognition service interface supports API calls and billing on demand. Each user has a free call quota of 1000 times a month. The early experience debugging is more convenient.

Charging instructions of interface: https://support.huaweicloud.com/productdesc-ocr/ocr_01_0070.html

2.2 introduction to API interface

Help document address: https://support.huaweicloud.com/api-ocr/ocr_03_0104.html

After identifying the key text information on the bank card, the interface returns the recognition result in json format, and the information can be obtained by parsing according to the instructions.

Interface format:

URL Request format: POST https://{endpoint}/v2/{project_id}/ocr/bankcard

endpoint Specify bearer REST The server domain name or of the service endpoint IP,Different services in different regions endpoint Different, it can be obtained from the terminal node.
For example, OCR Service in"North China-Beijing IV"Regional"endpoint"by"ocr.cn-north-4.myhuaweicloud.com". 

project_id It's a project ID,From here https://support.huaweicloud.com/api-ocr/ocr_03_0130.html.


Full request example: 
https://ocr.cn-north-4.myhuaweicloud.com/v2/0e5957be8a00f53c2fa7c0045e4d8fbf/ocr/bankcard

Request header:
{
 "X-Auth-Token": "******",
 "Content-Type": "application/json;charset=UTF-8"
}

X-Auth-Token Reference is obtained here:https://support.huaweicloud.com/api-ocr/ocr_03_0005.html

The request body contains the image bash Data coding
{
 "image": ..............
}


Result of response after identification:
{
 "result": {
  "bank_name": "China Construction Bank",
  "card_number": "6217003860002354304",
  "issue_date": "",
  "expiry_date": "09/22",
  "type": "Debit Card",
  "confidence": {
   "bank_name": 0.9608,
   "card_number": 0.9793,
   "issue_date": 0,
   "expiry_date": 0.8646,
   "type": 0
  }
 }
}

Explanation of field meaning in response result:

bank_name  Issuer.

card_number Bank card number.

issue_date Validity start date.

expiry_date Expiry date.

type Types of bank cards, such as debit card, credit card, quasi credit card and prepaid card.

2.3 online commissioning

Online debugging address: https://apiexplorer.developer.huaweicloud.com/apiexplorer/debug?product=OCR&api=RecognizeBankcard

After debugging the interface first and then writing the code, you can avoid some detours, and many parameters are relatively clear.

Paste the base64 code of the picture into the image field, and click debug to view the results.

3. Example code

The code is written in QT, mainly HTTP requests, obtaining results and parsing results. The API interface does not depend on language. The use of any language is the same process.

3.2 initiate a request to obtain bank card information

//Obtain bank card information
void  Widget::getCardInfo(QString file)
{
    function_select=1;
    QString requestUrl;
    QNetworkRequest request;

    //BASE64 code for storing pictures
    QString imgData;

    //Set request address
    QUrl url;

    //Face search request address
    requestUrl = QString("https://ocr.%1.myhuaweicloud.com/v2/%2/ocr/bankcard")
            .arg(SERVER_ID)
            .arg(PROJECT_ID);

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

    //Base64 encode the picture
    imgData = QString(toBase64(QImage(file))); //The size of the encoded picture shall not exceed 2M
    //Set token
    request.setRawHeader("X-Auth-Token",Token);

    //Construction request
    url.setUrl(requestUrl);
    request.setUrl(url);

    QString post_param=QString
               ("{"
                 "\"image\": \"%1\""
                "}").arg(imgData);

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

3.3 get token

/*
Function: get token
*/
void Widget::GetToken()
{
    //Indicates to get the token
    function_select=3;

    QString requestUrl;
    QNetworkRequest request;

    //Set request address
    QUrl url;

    //Get token request address
    requestUrl = QString("https://iam.%1.myhuaweicloud.com/v3/auth/tokens")
                 .arg(SERVER_ID);

    //Create your own TCP server for testing
    //requestUrl="http://10.0.0.6:8080";

    //Format data submission
    request.setHeader(QNetworkRequest::ContentTypeHeader, QVariant("application/json;charset=UTF-8"));

    //Construction request
    url.setUrl(requestUrl);

    request.setUrl(url);

    QString text =QString("{\"auth\":{\"identity\":{\"methods\":[\"password\"],\"password\":"
    "{\"user\":{\"domain\": {"
    "\"name\":\"%1\"},\"name\": \"%2\",\"password\": \"%3\"}}},"
    "\"scope\":{\"project\":{\"name\":\"%4\"}}}}")
            .arg(MAIN_USER)
            .arg(IAM_USER)
            .arg(IAM_PASSWORD)
            .arg(SERVER_ID);

    //Send request
    manager->post(request, text.toUtf8());
}

3.4 analysis results

//Analyze feedback results
void Widget::replyFinished(QNetworkReply *reply)
{
    QString displayInfo="";
    int statusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt();

    //Read all data
    QByteArray replyData = reply->readAll();

    qDebug()<<"Status code:"<<statusCode;
    qDebug()<<"Feedback data:"<<QString(replyData);

    //Update token
    if(function_select==3)
    {
        displayInfo="token Update failed.";
        //Read the data of HTTP response header
        QList<QNetworkReply::RawHeaderPair> RawHeader=reply->rawHeaderPairs();
        qDebug()<<"HTTP Number of response headers:"<<RawHeader.size();
        for(int i=0;i<RawHeader.size();i++)
        {
            QString first=RawHeader.at(i).first;
            QString second=RawHeader.at(i).second;
            if(first=="X-Subject-Token")
            {
                Token=second.toUtf8();
                displayInfo="token Update successful.";

                //Save to file
                SaveDataToFile(Token);
                break;
            }
        }
        QMessageBox::information(this,"Tips",displayInfo,QMessageBox::Ok,QMessageBox::Ok);
        return;
    }

    //Judgment status code
    if(200 != statusCode)
    {
        //Parse data
        QJsonParseError json_error;
        QJsonDocument document = QJsonDocument::fromJson(replyData, &json_error);
        if(json_error.error == QJsonParseError::NoError)
        {
            //Determine whether it is an object, and then start parsing the data
            if(document.isObject())
            {
                QString error_str="";
                QJsonObject obj = document.object();
                QString error_code;
                //Parse error code
                if(obj.contains("error_code"))
                {
                    error_code=obj.take("error_code").toString();
                    error_str+="error code :";
                    error_str+=error_code;
                    error_str+="\n";
                }
                if(obj.contains("error_msg"))
                {
                    error_str+="Error message:";
                    error_str+=obj.take("error_msg").toString();
                    error_str+="\n";
                }

                //Display error code
                QMessageBox::information(this,"Tips",error_str,QMessageBox::Ok,QMessageBox::Ok);
            }
         }
        return;
    }

    //Result return
    if(function_select==1)
    {
        //Parse data
        QJsonParseError json_error;
        QJsonDocument document = QJsonDocument::fromJson(replyData, &json_error);
        if(json_error.error == QJsonParseError::NoError)
        {
            //Determine whether it is an object, and then start parsing the data
            if(document.isObject())
            {
                QJsonObject obj = document.object();
                QString error_code;
                //analysis
                if(obj.contains("result"))
                {
                    QJsonObject obj1=obj.take("result").toObject();

                    QString bank_name;
                    QString card_number;
                    QString type;

                    QString text;
                    if(obj1.contains("bank_name"))
                    {
                        bank_name=obj1.take("bank_name").toString();
                    }
                    if(obj1.contains("card_number"))
                    {
                        card_number=obj1.take("card_number").toString();
                    }
                    if(obj1.contains("type"))
                    {
                        type=obj1.take("type").toString();
                    }


                    text="Issuer:"+bank_name+"\n";
                    text+="Card number:"+card_number+"\n";
                    text+="Card type:"+type+"\n";

                    ui->plainTextEdit->setPlainText(text);
                }
            }
        }
    }
}

Keywords: AI

Added by Tibster on Mon, 21 Feb 2022 18:43:45 +0200