Qt之调用百度API

近几年来,语音识别、图像识别等AI技术发展得如火如荼。国内外各大科技巨头积极布局(各大AI 开放平台一览),百度是其中比较优秀的一家。百度希望通过百度大脑来实现战略转型,从一家无恶不作的广告推送、流量变现公司转型为一个高大上的AI开放平台。本篇文章介绍了如何利用Qt来调用百度云的AI接口实现图像识别。

本次设计的最终效果如下

Qt之调用百度API_第1张图片

官方的新手指南对如何接入AI开放平台做了详尽的引导。下面介绍如何利用Qt进行AI接口调用,本次调用以身份证为例。

阅读完新手指南后,获得了Access_Token,将其保存在QString中

QString accessToken = "24.48d309c18be44c2e73fc9e91162be40e.2592000.1592381475.282335-19936265";

准备好如下三个对象用于发送请求与接受返回数据

QNetworkRequest request;
url.setUrl("https://aip.baidubce.com/rest/2.0/ocr/v1/idcard"  + "?access_token=" + accessToken );
request.setUrl(url);//设置完url的request

QNetworkReply *reply;//用于接受返回数据

QNetworkAccessManager *manager;//用于管理请求数据的发送

图片base64转码

void BaiDuAI::getImageData(QString filePath)
{
    QImage img(filePath);
    imageLabel->setScaledContents(true);
    imageLabel->setFixedSize(imageLabel->width(), imageLabel->height());
    imageLabel->setPixmap(QPixmap::fromImage(img));

    QByteArray imageData;
    QBuffer buffer(&imageData);
    img.save(&buffer, "jpg");
    imgBase64 = QString( imageData.toBase64(QByteArray::OmitTrailingEquals) );
    buffer.close();
    identifyImage(manager, imgBase64, request);
}

发送请求数据

void BaiDuAI::identifyIDCard(QNetworkAccessManager *manager,
                                  QString imgBase64,
                                  QNetworkRequest request)
{
    QHttpMultiPart *mulPart = new QHttpMultiPart(QHttpMultiPart::FormDataType);

    QHttpPart part1;
    part1.setRawHeader("Content-Type","application/x-www-form-urlencoded");
    part1.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QString("form-data;name=\"%1\"").arg("image")));
    part1.setBody(imgBase64.toUtf8());
    QHttpPart part2;
    part2.setRawHeader("Content-Type","application/x-www-form-urlencoded");
    part2.setHeader(QNetworkRequest::ContentDispositionHeader, QVariant(QString("form-data;name=\"%1\"").arg("id_card_side")));
    part2.setBody("front");

    mulPart->append(part1);
    mulPart->append(part2);

    //发送数据
    QNetworkReply *reply = manager->post(request, mulPart);
    mulPart->setParent(reply);
}

处理返回数据

void BaiDuAI::handleIDCardReply(QNetworkReply *re, QTextBrowser *imageIdentify)
{
    QByteArray replyData;
    QNetworkReply *reply = re;
    replyData = reply->readAll();
    //imageIdentify->setText(replyData);

    //Json数据解析
    QJsonDocument document = QJsonDocument::fromJson(replyData.data());
    if( !document.isNull() )
    {
        QString result;
        QJsonObject jsonObject = document.object();
        QJsonObject jsonObject1 = jsonObject.value(QString("words_result")).toObject();
        QJsonObject::const_iterator it = jsonObject1.constBegin();
        QJsonObject::const_iterator end = jsonObject1.constEnd();
        while (it != end) {
            QString key = it.key();
            QString value = it.value().toObject().value("words").toString();
            QString pair = key + ": " + value + "\n";
            result += pair;
            it++;
        }
        imageIdentify->setText(result);
    }
}

支持拖拽上传图片的Label

class JLabel : public QLabel
{
    Q_OBJECT
public:
    explicit JLabel(QWidget *parent = nullptr) : QLabel(parent)
    {
        setAcceptDrops(true);
    }
protected:
    void dragEnterEvent(QDragEnterEvent *event)
    {
        event->acceptProposedAction();
    }
    void dropEvent(QDropEvent *event)
    {
        QString filePath = event->mimeData()->urls().first().toLocalFile();
        emit imageArrived(filePath);
    }
signals:
    void imageArrived(QString filePath);

};

总结

拖拽图片上传,触发getImageData,getImageData对图片进行base64转码,并调用identifyIDCard;identifyIDCard发送请求数据;当请求数据到来,handleIDCardReply负责进行处理。

扩展阅读

Qt封装百度人脸识别+图像识别

你可能感兴趣的:(Qt基础)