c++向python传输图片 高效方法 mat转numpy

c++向python传输图片 效率最好的自然是传到python的格式自动为图像格式,不需要做二次转换

将图片数据转化为python中numpy的格式,opencv在python中图像表示方法为numpy的array格式,

如果是多通道情况,最常见的就是红绿蓝(RGB)三通道,则第一个维度是高度,第二个维度是宽度,第三个维度是通道数

在代码中表达方式如下

import numpy as np
import cv2
img = np.array([
    [[255, 0, 0], [0, 255, 0], [0, 0, 255]],
    [[255, 255, 0], [255, 0, 255], [0, 255, 255]],
    [[255, 255, 255], [128, 128, 128], [0, 0, 0]],
], dtype=np.uint8)
 
# 用opencv存储
cv2.imwrite('img_cv2.jpg',img)

那么c++中讲mat格式图像转化为numpy格式如下

#include "Python.h"
#include "object.h"
#include <numpy/arrayobject.h>
#include <opencv2/opencv.hpp>

void init_numpy()
{
    import_array();
}

void main(){
// 初始化Python
    //在使用Python系统前,必须使用Py_Initialize对其
    //进行初始化。它会载入Python的内建模块并添加系统路
    //径到模块搜索路径中。这个函数没有返回值,检查系统
    //是否初始化成功需要使用Py_IsInitialized。
    Py_Initialize();
    init_numpy();
    // 检查初始化是否成功
    if ( !Py_IsInitialized() )
    {
        return -1;
    }

    PyRun_SimpleString("print 'hello'");
    PyObject *pName,*pModule,*pDict,*pFunc,*pArgs;
    // 载入名为pytest的脚本
    //pName = PyString_FromString("testvideo");
    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.path.append('/home/vetec-p/Pan/project/run-maskrcnn')");
    PyRun_SimpleString("sys.path.append('/home/vetec-p/Pan/project/run-maskrcnn/build')");
    PyRun_SimpleString("sys.path.append('/home/vetec-p/Pan/Detectron-master')");
    //    PyRun_SimpleString("print sys.path");
    //();
    pModule = PyImport_ImportModule("infer_one_pic");
    if ( !pModule )
    {
        printf("can't find testvideo.py");
        //getchar();
        return -1;
    }
    pDict = PyModule_GetDict(pModule);
    if ( !pDict )
    {
        return -1;
    }
    pFunc = PyDict_GetItemString(pDict, "run");
    if ( !pFunc || !PyCallable_Check(pFunc) )
    {
        printf("can't find function [run]");
        getchar();
        return -1;
    }
    for(int i=1;i<200;i++)
    {
        clock_t start,finish;
        double totaltime;
        start=clock();
        Mat img=imread("/media/vetec-p/Data/Rubbish/maskrcnn_dataset/0803_mask/train_all/pic/"+to_string(i)+".png");
        if(img.empty())
            return -1;
        //        imshow("img",img);
        //        waitKey(0);

        clock_t s1;
        s1=clock();
        //PyObject *PyList  = PyList_New(data_size);//定义一个与数组等长的PyList对象数组
        PyObject *ArgList = PyTuple_New(1);


        auto sz = img.size();
        int x = sz.width;
        int y = sz.height;
        int z = img.channels();
        uchar *CArrays = new uchar[x*y*z];//这一行申请的内存需要释放指针,否则存在内存泄漏的问题
        int iChannels = img.channels();
        int iRows = img.rows;
        int iCols = img.cols * iChannels;
        if (img.isContinuous())
        {
            iCols *= iRows;
            iRows = 1;
        }

        uchar* p;
        int id = -1;
        for (int i = 0; i < iRows; i++)
        {
            // get the pointer to the ith row
            p = img.ptr<uchar>(i);
            // operates on each pixel
            for (int j = 0; j < iCols; j++)
            {
                CArrays[++id] = p[j];//连续空间
            }
        }

        npy_intp Dims[3] = { y, x, z}; //注意这个维度数据!
        PyObject *PyArray = PyArray_SimpleNewFromData(3, Dims, NPY_UBYTE, CArrays);
        PyTuple_SetItem(ArgList, 0, PyArray);
        clock_t e1=clock();



        cout<<"\n赋值为"<<(double)(e1-s1)/CLOCKS_PER_SEC<<"秒!"<<endl;

        //PyTuple_SetItem(ArgList, 0, PyList);//将PyList对象放入PyTuple对象中
        PyObject *pReturn = PyObject_CallObject(pFunc, ArgList);
        clock_t e2=clock();
        //cout<<"\n detect为"<<(double)(e2-e1)/CLOCKS_PER_SEC<<"秒!"<<endl;
        delete []CArrays ;
        CArrays =nullptr;
    }


    Py_DECREF(pModule);

    // 关闭Python
    Py_Finalize();


    return 0;
}

在python端直接当做图像格式使用即可

import cv2

def run(imgdata):
    cv2.imshow("img", img)
    cv2.waitKey(0)

 

发布了21 篇原创文章 · 获赞 24 · 访问量 7万+
展开阅读全文

在c语言程序中调用python脚本

03-05

最近在研究yolo,想在yolo源码(c语言)中调用随机森林算法来判断各检测框之间的关系。 只针对行人出检测框,提取框与框之间的四个参数:交并比、中心点距离、颜色直方图差值、面积差。以此作为输入参数。 先利用python完成了模型的训练并保存。在服务器上模拟调用也是可行的。随机生成数据,通过模型判断。 部分代码如下:test.c srand((unsigned)time(NULL)); for (i=0;i<50;i++){ io = rand()/(double)(RAND_MAX); printf("iou:%f\n",io); dist = rand()/(double)(RAND_MAX/100); printf("distance:%f\n",dist); su = rand()/(double)(RAND_MAX/100); printf("sub:%f\n",su); sua = rand()%50000; printf("suba:%d\n",sua); Py_Initialize(); if(!Py_IsInitialized()) { printf("Python init failed!\n"); return; } PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('//home//wangxiangsheng//wuhao//test')"); PyObject *pName = NULL; PyObject *pModule = NULL; PyObject *pDict = NULL; PyObject *pFunc = NULL; PyObject *pArgs = NULL; PyObject *pResult = NULL; pName = PyString_FromString("RF"); pModule = PyImport_Import(pName); pDict = PyModule_GetDict(pModule); pFunc = PyDict_GetItemString(pDict,"randomF"); pArgs = Py_BuildValue("(f,f,f,i)",io,dist,su,sua); pResult = PyObject_CallObject(pFunc,pArgs); PyArg_Parse(pResult, "i", &res); printf("result is %d\n",res); ``` 调用的python脚本:RF.py ``` import sklearn as skl from sklearn.externals import joblib from sklearn.ensemble import RandomForestClassifier def randomF(iou,distance,sub,suba): test_data = [[iou,distance,sub,suba]] clf = joblib.load("//home//wangxiangsheng//wuhao//train_model.m") output = clf.predict(test_data) print output return output 但是,当我按照这样改写yolo源码之后,运行起来就会出问题, ![图片说明](https://img-ask.csdn.net/upload/201803/05/1520231552_54452.jpg) 第一帧有数据,没画面,第二帧就直接卡住了。 代码较多,放部分片断 ``` Py_Initialize(); if(!Py_IsInitialized()) { printf("Python init failed!\n"); return; } PyRun_SimpleString("import sys"); PyRun_SimpleString("sys.path.append('//home//wangxiangsheng//darknet//src')"); PyObject *pName = NULL; PyObject *pModule = NULL; PyObject *pDict = NULL; PyObject *pFunc = NULL; PyObject *pArgs = NULL; PyObject *pResult = NULL; pName = PyString_FromString("RF"); pModule = PyImport_Import(pName); if(!pModule) { printf("Load RF.py failed!\n"); getchar(); } pDict = PyModule_GetDict(pModule); if(!pDict) { printf("Can't find dict in RF!\n"); } pFunc = PyDict_GetItemString(pDict,"randomF"); if(!pFunc || !PyCallable_Check(pFunc)) { printf("Can't find function!\n"); getchar(); } for(j=0;j<10;j++){ for(w=j+1;w<39;w++){ float media = box_iou(para[j].p, para[w].p); float iout; if (media<=0){ iout = 0.000000; } else { iout = media; } int p,suba; float res; suba = abs(para[j].barea-para[w].barea); float sub=0; for(p=0;p<64;p++){ sub = sub + pow(para[j].hist[p]-para[w].hist[p],2); } float distance; distance = sqrt(pow(para[w].p.x-para[j].p.x,2)+pow(para[w].p.y-para[j].p.y,2)); printf("%f-%f-%f-%d \n",iout,distance,sub,suba); pArgs = Py_BuildValue("(f,f,f,i)",iout,distance,sub,suba); pResult = PyObject_CallObject(pFunc,pArgs); PyArg_Parse(pResult, "f", &res); printf("result is %f\n",res); ``` 求哪位指导一下,感激不尽! 问答

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览