Qt调用python脚本,一直没试过,就尝试了下。找了个百度云人脸识别接口,做了个小程序,现在和大家分享下,先看截图:
Qt调用python解析百度云API实现人脸图像识别
Qt调用python解析百度云API实现人脸图像识别
一开始先输入APIKey和SecretKey,这两个值就是注册百度云添加应用后给的,如下:
Qt调用python解析百度云API实现人脸图像识别
做的登录界面只是为了提醒输入两个key值,并没有验证的功能,根据两个key值可以得到一个accesstoken,请求参数上要用,具体写在了python脚本上。

一,先看下用Qt是怎么调用Python的

1,添加Python的libs和include路径到pro下:
Qt调用python解析百度云API实现人脸图像识别
我的路径如上图,则在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>,这时候会有个错误提示:
Qt调用python解析百度云API实现人脸图像识别
点开错误,加上以下两行
Qt调用python解析百度云API实现人脸图像识别这是因为Python中的slots和Qt的冲突了。取消定义后就好。
接下来如果是在Debug模式下运行还会有个错误:
Qt调用python解析百度云API实现人脸图像识别
在pyconfig.h中
Qt调用python解析百度云API实现人脸图像识别
看到在debug模式下是要打开python36_d.lib的,把_d去掉就好,然后把中间这句注释掉。
Qt调用python解析百度云API实现人脸图像识别
嫌麻烦的,可以直接使用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

相关文章: