Qt調用python解析百度雲API實現人臉圖像識別

Qt調用python腳本,一直沒試過,就嘗試了下。找了個百度雲人臉識別接口,做了個小程序,現在和大家分享下,先看截圖:
在這裏插入圖片描述
在這裏插入圖片描述
一開始先輸入APIKey和SecretKey,這兩個值就是註冊百度雲添加應用後給的,如下:
在這裏插入圖片描述
做的登錄界面只是爲了提醒輸入兩個key值,並沒有驗證的功能,根據兩個key值可以得到一個accesstoken,請求參數上要用,具體寫在了python腳本上。

一,先看下用Qt是怎麼調用Python的

1,添加Python的libs和include路徑到pro下:
在這裏插入圖片描述
我的路徑如上圖,則在pro文件下爲:

LIBS += -LC:/Users/jojo/AppData/Local/Programs/Python/Python36-32/libs -lpython36
INCLUDEPATH += -I  C:/Users/jojo/AppData/Local/Programs/Python/Python36-32/include

接下來就可以包含頭文件#include<Python.h>,這時候會有個錯誤提示:
在這裏插入圖片描述
點開錯誤,加上以下兩行
在這裏插入圖片描述這是因爲Python中的slots和Qt的衝突了。取消定義後就好。
接下來如果是在Debug模式下運行還會有個錯誤:
在這裏插入圖片描述
在pyconfig.h中
在這裏插入圖片描述
看到在debug模式下是要打開python36_d.lib的,把_d去掉就好,然後把中間這句註釋掉。
在這裏插入圖片描述
嫌麻煩的,可以直接使用release模式編譯,沒有這些錯誤。
還有一個python庫位數必須和qt編譯器位數是一致的,比如我是32位的,我構建的qt項目也是32位的,否則也會出錯。
接下來就可以調用Python中的函數了。
先看下python文件getAccessToken.py中的函數:(具體接口信息查看文檔)

def getAccessToken(apiKey,secretKey):
    # client_id 爲官網獲取的AK, client_secret 爲官網獲取的SK
    host = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id='+apiKey+'&client_secret='+secretKey
    request = urllib.request.Request(host)
    request.add_header('Content-Type', 'application/json; charset=UTF-8')
    response = urllib.request.urlopen(request)
    content = response.read()
    #print(json.loads(content)['access_token'])
    return json.loads(content)['access_token']


def getResult(src,apiKey,secretKey):
    host = 'https://aip.baidubce.com/rest/2.0/face/v3/detect?access_token='+getAccessToken(apiKey,secretKey)
    request = urllib.request.Request(host)
    request.add_header('Content-Type', 'application/json; charset=UTF-8')
    data = {}
    data['image'] = src
    data['image_type']='BASE64'
    data['face_field']='age,beauty,gender,expression,faceshape,glasses,race'
    #print(host)
    data = urllib.parse.urlencode(data).encode("utf-8")
    response = urllib.request.urlopen(request,data=data)
    content = response.read()
    result = json.loads(content)['result']['face_list'][0]
    #print(result['age'],result['beauty'],result['gender']['type'],result['expression']['type'],result['face_shape']['type'],result['glasses']['type'],result['race']['type'])
    #這邊直接解析json格式返回所需要的信息
    return (result['age'],result['beauty'],result['gender']['type'],result['expression']['type'],result['face_shape']['type'],result['glasses']['type'],result['race']['type'])
  

接下來在Qt中調用:

	//初始化
    Py_Initialize();
    if (!Py_IsInitialized()) {
        qDebug()<<"python init error!";
        return;
    }
    //導入模塊,即*.py,py文件需放大exe同個文件夾下
    PyObject* pModule = PyImport_ImportModule("getAccessToken");
    if (!pModule) {
        qDebug()<<"import error!";
        return;
    }
    //獲取模塊中函數
    PyObject* pFunGetResult= PyObject_GetAttrString(pModule,"getResult");
    if(!pFunGetResult){
        qDebug()<< "get function error!";
        return;
    }
    //這邊的imgData爲圖片數據進行base64轉碼後轉爲QString類型
    PyObject* args = Py_BuildValue("(sss)", imgData.toStdString().c_str(),apiKey.toStdString().c_str(),secretKey.toStdString().c_str());//給python函數參數賦值,apiKey,secretKey即爲百度雲key值
    //調用函數
    PyObject* result = PyObject_CallObject(pFunGetResult,args);
    if(!result) {
        qDebug()<<"call function error!";
        return;
    }
    int age=0;
    float beauty=0.0;
    char *gender;
    char *expression;
    char *faceShape;
    char *glasses;
    char *race;
    if(!PyArg_ParseTuple(result, "ifsssss",&age,&beauty,&gender,&expression,&faceShape,&glasses,&race)){//轉換返回類型
        qDebug()<<"parse tuple error!";
        return;
    }
    //釋放
    Py_Finalize();

到此主要工作就完成了,把獲取的信息匹配下就可以在Qt界面上顯示了。具體代碼在
https://download.csdn.net/download/hdaioutgjht/10884328

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章