Share OpenCV C++ Object with Python
Scenario:
A C++ program process captures an image using OpenCV. Another process, using Python and OpenCV has a shared memory area (with mmap) with the first program.
Problem:
How do I create in a Python process, a reference to the same image that already exists in the shared memory area? This part in the Python process could be written as a C module and imported into Python.
For my specific needs, only the C++ process creates and writes data, while the Python process just reads (and processes upon) it.
Extra info:
Given the same image, the data
field of C++ cv::Mat
and numpy.array
are equal (same size and content). So there is no need to convert.
As the languages have separated memory managers, it may have to use some external sync (eg. semaphore) to avoid one process using a deallocated area from another.
My problem is creating in Python numpy.array
object that the data fields point to the specific area in the shared memory.
Solution 1:
below options can be used to create cv::Mat
or numpy.array
header for a preallocated memory buffer:
-
For cv::Mat, there is a constructor which creates a cv::Mat header over preallocated memory (destructor of Mat will not release the memory in this case):
cv::Mat(int rows, int cols, int type, void * data, size_t step = AUTO_STEP)
-
numpy array from buffer:
numpy.frombuffer(buffer, dtype=float, count=- 1, offset=0, *, like=None)