how to return a numpy array to python from c++ (shared memory)
Is there a way to return a numpy array from c++ to python (shared memory)? This is for sharing image data between a c++ app and python. I am using SWIG currently.
I was able to shared the memory between c++ and python (for modifying image data in both end). Please see http://answers.opencv.org/question/18...
Now, instead of letting user to retrieve the shared data from memory and construct the right shape for the numpy array, I would like to package that so that it will just return the numpy array (shared memory) and let user manipulates it in python?
numpy_array = np.frombuffer(imgPtr, dtype=np.uint8) //for one byte integer image numpy_array.shape = (rows1, cols1)
So in summary, I would like to package the above two lines of code in my c++ app and provide a function call in python to retrieve the numpy array. This is more user friendly since the user that uses python app are not professional sw developer, so asking them to get the data from shared memory and reshape the numpy array before they can use the numpy array to visualize it in opencv is a little bit too much for them.
Thanks in advamce/
That's bull**. Anyone can learn to code C++, because it's natural.
Unfortunately, my users do not have interest or time to learn c++. I wish you are my target user :-). Anyway, thanks for your comment.
Is this not where you need a function like
DLLEXPORT char *alloc_img(const char *file_name, int *width, int *height, size_t *image_id)
?.. and also a function like...
DLLEXPORT int free_img(size_t *image_id)
... and also the Python code:
I think you must have misunderstood my question.
Instead of letting user retrieve the shared memory pointer, create a
numpy
array and shape it to the correct dimemsion, I would like to let the user achieve that by a single function call from C++ app to retrieve thenumpy
array (i.e. without performing the following code line 2 to 3):Original solution:
instead:
New Solution:
--> this retrieves the
numpy
array created in c++ with the correct shape (and is using shared memory with Python, so any python related updated on this array will be reflected in c++ automatically)The original solution requires user to understand the programming basics of retrieving the buffer pointer, create a numpy array from buffer pointer and then shape the numpy array accordingly. For my users, they will ask me "Why do I have to do all that? This is too complicated. Why can't you just give me the numpy array in Python for the displayed image on C++ app?"
So, you've figured it out? That's good!
Sorry, yes I do believe that I have misunderstood you.
no, I am still looking for a solution...I am still researching how to implement GetNumpyArray() on the c++ side...
I think I can use
PyArray_SimpleNewFromData()
... but I got access violation error with the following code:assuming it is a 512x512 int8 image and buf is the:
Am I not calling
PyArray_SimpleNewFromData()
properly?