c python boost.python,使用BOOST.python从C ++将结构返回到Python

I have written a C++ method from which I need to return a structure to Python.

I'm already able to send an OpenCV mat from Python to C++ using BOOST following the method described in this link.

Now I need to go the other way; return from C++ to Python, and then access that structure in Python. Can it be done?

Any samples or reference links would be good. I have tried googling before posting this question and I couldn't get any samples or explanation links.

解决方案

You can use another function from modules/python/src2/cv2.cpp:

PyObject* pyopencv_from(const cv::Mat& m)

{

if( !m.data )

Py_RETURN_NONE;

cv::Mat temp, *p = (cv::Mat*)&m;

if(!p->refcount || p->allocator != &g_numpyAllocator)

{

temp.allocator = &g_numpyAllocator;

m.copyTo(temp);

p = &temp;

}

p->addref();

return pyObjectFromRefcount(p->refcount);

}

Then the Boost Python wrapper will look like:

boost::python::object toPython( const cv::Mat &frame )

{

PyObject* pyObjFrame = pyopencv_from( frame );

boost::python::object boostPyObjFrame(boost::python::handle<>((PyObject*)pyObjFrame));

return boostPyObjFrame;

}

Please have a look at this link: https://wiki.python.org/moin/boost.python/handle to make sure that you use the appropriate boost::python::handle<> function for your case.

If you need don't need to return a cv::Mat but different data you might consider to use boost::python::list or boost::python::dict. For example if you want to return a vectors of 2D points to Python you can do something like:

boost::python::dict toPython( std::vector<:point> newPoints, std::vector<:point> oldPoints )

{

boost::python::dict pointsDict;

boost::python::list oldPointsList;

boost::python::list newPointsList;

for( size_t ii = 0; ii < oldPoints.size( ); ++ii )

{

oldPointsList.append( boost::python::make_tuple( oldPoints[ii].x, oldPoints[ii].y ) );

}

for( size_t ii = 0; ii < newPoints.size( ); ++ii )

{

newPointsList.append( boost::python::make_tuple( newPoints[ii].x, newPoints[ii].y ) );

}

pointsDict["oldPoints"] = oldPointsList;

pointsDict["newPoints"] = newPointsList;

return pointsDict

}

Finally the Boost Python wrapper:

BOOST_PYTHON_MODULE( myWrapper )

{

// necessary only if array (cv::Mat) is returned

import_array();

boost::python::converter::registry::insert( &extract_pyarray, type_id());

def toPython("toPython", &toPython);

}

I haven't tested this specific solution but it should work in principle.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值