c++调用python的混编程序(vs下调用pytorch的深度学习接口)

// WallTileCoreAlgorithm.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//

#include "RV_GetBirckInfo_all.h"
#include <iostream>

#include <Python.h>
#include <numpy/arrayobject.h>

void getName(char *imgPath, char*imgName)
{
    std::stack<char> tempName;
    int count = 0;
    while (imgPath[count] != '.')
    {
        count++;
    }

    count--;
    while (imgPath[count] != '\\')
    {
        tempName.push(imgPath[count]);
        count--;
    }
    int i = 0;
    while (!tempName.empty())
    {

        imgName[i] = tempName.top();
        tempName.pop();
        i++;
    }
    return;
}


//
typedef struct DizhuanPointInfo
{
    double _x;
    double _y;
    DizhuanPointInfo() :_x(-1), _y(-1) {};
}DizhuanPointInfo;

double convertPythonObjectToDouble(PyObject *obj)
{
    double result = 0;
    PyArg_Parse(obj, "d", &result);
    return result;
}

//数据转换

void convertPythonListObjectToDizhuanData(PyObject *pRet, std::vector<DizhuanPointInfo> &_dizhuanInfos)
{
    _dizhuanInfos.clear();
    if (!pRet)
    {
        return;
    }
    if (!PyList_Check(pRet))
    {
        return;
    }
    //dizhuan python returns lead to this strange code.
    PyArrayObject *pObj = (PyArrayObject *)PyList_GetItem(pRet, 0);
    if (!PyList_Check(pObj))
    {
        return;
    }
    int listSize = PyList_Size((PyObject*)pObj);
    for (int i = 0; i < listSize; i++)
    {
        PyArrayObject *currentPoint = (PyArrayObject *)PyList_GetItem((PyObject*)pObj, i);
        if (!PyList_Check(currentPoint))
        {
            continue;
        }
        int sz = PyList_Size((PyObject*)currentPoint);
        if (sz < 2)
        {
            continue;
        }
        //
        PyObject *p0 = PyList_GetItem((PyObject *)currentPoint, 0);
        PyObject *p1 = PyList_GetItem((PyObject *)currentPoint, 1);
        //
        auto d0 = convertPythonObjectToDouble(p0);
        auto d1 = convertPythonObjectToDouble(p1);
        DizhuanPointInfo tempInfo;
        tempInfo._x = d0;
        tempInfo._y = d1;
        _dizhuanInfos.push_back(tempInfo);
    }
}


void *test()
{
    //初始化python模块
    Py_SetPythonHome(L"C:\\Users\\dell\\Anaconda3\\envs\\pytorch");//add by wk_zhong
    Py_Initialize();

    import_array();
    if (!Py_IsInitialized())
    {
        exit(1);
    }

    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('E:/Application_of_algorithm_project/DiZhuan_Robot/VisualAlgorithmProgram/FloorTileCoreAlgorithm/dizhuan_wmx/dizhuan')");
    //PyRun_SimpleString("import evaluation-gai");

    PyObject * pModule = nullptr;
    pModule = PyImport_ImportModule("evaluationgai");
    string _pvFuncName;
    _pvFuncName = "evaluate2";
    PyObject *_pv = nullptr;
    _pv = PyObject_GetAttrString(pModule, _pvFuncName.c_str());
    std::vector<DizhuanPointInfo> DLResult;

    if (pModule == nullptr)
    {
        std::cout << "cannot find wkzhong" << std::endl;
        return nullptr;
    }

    char path[500];
    char savePath[500];
    char lebelname[500];
    char tempPath[500];
    
    ///
    FILE *fileIndex;
    FILE *fileLabelName;

    fileIndex = fopen(".\\index\\all_New.txt", "r");
    float numOfPic = 0;
    fscanf(fileIndex, "%f", &numOfPic);

    for (int i = 0; i < numOfPic; i++)
    {
        std::cout << i / numOfPic << std::endl;
        for (int i = 0; i < 500; i++)
        {
            lebelname[i] = 0;
        }

        std::cout << "Process Pic :" << i + 1 << std::endl;
        fscanf(fileIndex, "%s", path);
        getName(path, lebelname);

        cv::Mat input = cv::imread(path);
        //cv::Mat input = cv::imread("G:\\ProjectPic\\dizhuan\\待整理\\new-030405\\0520\\oriImg\\c52_20200516_132852.bmp");
        

        if (input.empty())
            return 0;
        clock_t start, end, start1, end1;

        start1 = clock();
        cv::Mat ProcesImg;
        RV_ImageProcess(input, ProcesImg);

        //end1 = clock();
        //std::cout << "total time:" << 1000 * (end1 - start1) / CLOCKS_PER_SEC << "ms" << std::endl;

        RVBRICK brick1;
        RVBRICK brick2;
        RVBRICK brick3;
        RVBRICK brick4;

        cv::Mat dlimg;                                            //传入DL算法的图片
        bool isRotated = RV_DLpreprocess(input, dlimg);            //DL算法预处理
        if (dlimg.channels() == 1)
            cv::cvtColor(dlimg, dlimg, cv::COLOR_GRAY2BGR);        //图像必须是三通道的:612*512
    
        //为接入深度学习,做数据转换
        npy_intp imageShape[1] = { 512 * 612 * 3 };
        PyByteArrayObject *pyImgArr;
        pyImgArr = reinterpret_cast<PyByteArrayObject *>(PyArray_SimpleNewFromData(1, imageShape, NPY_BYTE, reinterpret_cast<void *>(dlimg.data)));

        PyObject *args = PyTuple_New(4);
        PyObject *arg1 = Py_BuildValue("i", 612);
        PyObject *arg2 = Py_BuildValue("i", 512);
        PyObject *arg3 = Py_BuildValue("i", 3);
        PyTuple_SetItem(args, 0, reinterpret_cast<PyObject *>(pyImgArr));
        PyTuple_SetItem(args, 1, arg1);
        PyTuple_SetItem(args, 2, arg2);
        PyTuple_SetItem(args, 3, arg3);

        PyObject *pRet = PyObject_CallObject(_pv, args);
        convertPythonListObjectToDizhuanData(pRet, DLResult);
        Py_DecRef(pRet);

        RV_DLResultPoint roughPt;                                //DL算法得到的数据
        RV_DLResultPoint mapPos;                                //位置映射后的数据

        //此处模拟dl得到后的结果赋值

        if (DLResult.size() == 4)
        {
            roughPt.quadrant1.x = DLResult.at(0)._x;
            roughPt.quadrant1.y = DLResult.at(0)._y;

            roughPt.quadrant2.x = DLResult.at(1)._x;
            roughPt.quadrant2.y = DLResult.at(1)._y;

            roughPt.quadrant3.x = DLResult.at(2)._x;
            roughPt.quadrant3.y = DLResult.at(2)._y;

            roughPt.quadrant4.x = DLResult.at(3)._x;
            roughPt.quadrant4.y = DLResult.at(3)._y;
            cout << roughPt.quadrant1.x << endl;
        }
        else
        {
            roughPt.quadrant1 = cv::Point(-1, -1);
            roughPt.quadrant2 = cv::Point(-1, -1);
            roughPt.quadrant3 = cv::Point(-1, -1);
            roughPt.quadrant4 = cv::Point(-1, -1);
        }
        
        RV_mappingPosition(roughPt, mapPos, isRotated);        //位置映射函数

        brick1.RV_GetBirckInfo(ProcesImg, 1, mapPos);            //接入传统视觉算法
        brick2.RV_GetBirckInfo(ProcesImg, 2, mapPos);            //接入传统视觉算法
        brick3.RV_GetBirckInfo(ProcesImg, 3, mapPos);            //接入传统视觉算法
        brick4.RV_GetBirckInfo(ProcesImg, 4, mapPos);            //接入传统视觉算法

        end1 = clock();
        std::cout << "total time:" << 1000 * (end1 - start1) / CLOCKS_PER_SEC << "ms" << std::endl << std::endl;

        //cv::cvtColor(input, input, cv::COLOR_GRAY2BGR);
        cv::circle(input, brick1.crossPoint, 10, cv::Scalar(0, 0, 255), 3, 8);
        cv::circle(input, brick2.crossPoint, 10, cv::Scalar(0, 255, 0), 3, 8);
        cv::circle(input, brick3.crossPoint, 10, cv::Scalar(255, 0, 0), 3, 8);
        cv::circle(input, brick4.crossPoint, 10, cv::Scalar(0, 255, 255), 3, 8);

        std::sprintf(savePath, "G:\\ProjectPic\\dizhuan\\待整理\\DLResult345\\%s.jpg", lebelname);
        cv::imwrite(savePath, input);

    }
    return nullptr;
}

 

int main()
{
    test();
    return 1;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值