Search code examples
pythonc++python-2.7numpypython-embedding

Passing a c++ vector to python and back


I am using a c++ code to do some simulations on an image. At some point, I need to label the image clusters, for which I want to use python ndimage.label (because it is almost 10 times faster than my labelling code). However, I am very new to python and have no idea how to pass the arguments (image) to python from C++. The search so far has given no results

  1. in the C++ code, the image is stored as vector<vector<int>>
  2. The python code needs the image as ndarray
  3. I would like to convert the output labelled array (ndarray) from python to a vector<vector<int>> again

Can anyone please suggest how can this be achieved. To begin with, any suggestions will do, although computational time is a big concern for me


Solution

  • You can use my library https://github.com/jzwinck/pccl/blob/master/NumPyArray.hpp to create a NumPy array from C++ using existing data e.g. from a vector. And any changes made in Python will be reflected in C++. It depends on Boost.Python, but the core code is simple and uses the NumPy C API directly so you could also extract just that part (the key is PyArray_NewFromDescr).