I am using shared memory provided by boost/interprocess/ to share the cv::Mat between model and client (both C++). Now I need to use a model in Python. Can you please tell which is the best way to share the cv::Mat between C++ and Python without changing the present client. Thanks.
Asked
Active
Viewed 2,188 times
0
-
What's your platform? Since shared memory might be platform specific. – Louis Go Nov 01 '21 at 09:59
-
This might [help](https://stackoverflow.com/a/59257364/4123703) – Louis Go Nov 01 '21 at 10:08
-
@LouisGo I am working in Windows 10. – KRG Nov 02 '21 at 01:56
-
[Multiprocessing.shared_memory](https://docs.python.org/3/library/multiprocessing.shared_memory.html#multiprocessing.shared_memory.SharedMemory) seems good for you. – Louis Go Nov 02 '21 at 06:27
-
@LouisGo Thank you for the comments. I will check multiprocessing.shared_memory. Currently I was able to solve it using mapped memory. – KRG Nov 02 '21 at 06:29
1 Answers
3
The task was completed using mapped memory to share the cv::Mat between C++ and Python process.
- C++ - use boost to copy cv::Mat to a mapped shared memory
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/windows_shared_memory.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <opencv2/opencv.hpp>
using namespace boost::interprocess;
int main(int argc, char* argv[])
{
imgMat= cv::imread("image.jpg");
windows_shared_memory shmem(open_or_create, "shm", read_write, img_size);
mapped_region region(shmem, read_write);
unsigned char* img_ptr = static_cast<unsigned char*> (region.get_address());
std::memcpy(img_ptr , imgMat.data, img_size);
std::system("pause");
}
- Python - read the image from memory using mmap.
import mmap
import cv2 as cv
import numpy as np
if __name__ == '__main__':
shmem = mmap.mmap(-1, image_size ,"shm")
shmem.seek(0)
buf = shmem.read(image_size)
img = np.frombuffer(buf, dtype=np.uint8).reshape(shape)
cv.imwrite("img.png", img)
shmem.close()

KRG
- 655
- 7
- 18
-
Would https://docs.python.org/3/library/multiprocessing.shared_memory.html be better for this, or is mmap better? – kevinlinxc Sep 24 '22 at 22:36
-
@kevinlinxc : It did not work for me for a cross platform solution. I tried and explained that here : https://stackoverflow.com/questions/69091769/fast-communication-between-c-and-python-using-shared-memory/ – poukill Jan 03 '23 at 08:24