我写了一个C++方法,我需要从中将结构返回给Python。我已经能够按照此链接中描述的方法使用 BOOST 将 OpenCV mat
从 Python 发送到C++。
现在我需要走另一条路;从C++返回到Python,然后在Python中访问该结构。能做到吗?
任何样本或参考链接都会很好。在发布这个问题之前,我尝试过谷歌搜索,但我无法获得任何样本或解释链接。
你可以使用 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);
}
然后 Boost Python 包装器将如下所示:
boost::python::object toPython( const cv::Mat &frame )
{
PyObject* pyObjFrame = pyopencv_from( frame );
boost::python::object boostPyObjFrame(boost::python::handle<>((PyObject*)pyObjFrame));
return boostPyObjFrame;
}
请查看此链接:https://wiki.python.org/moin/boost.python/handle 以确保您使用适当的 boost::p ython::handle<> 函数。
如果你不需要返回一个cv::Mat,但你可以考虑使用boost::p ython::list或boost::p ython::d ict。例如,如果你想将2D点的向量返回给Python,你可以做如下的事情:
boost::python::dict toPython( std::vector<cv::Point> newPoints, std::vector<cv::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
}
最后是 Boost Python 包装器:
BOOST_PYTHON_MODULE( myWrapper )
{
// necessary only if array (cv::Mat) is returned
import_array();
boost::python::converter::registry::insert( &extract_pyarray, type_id<PyArrayObject>());
def toPython("toPython", &toPython);
}
我还没有测试过这个特定的解决方案,但它原则上应该可以工作。
太晚了,但看看 https://github.com/spillai/numpy-opencv-converter