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.
-
What's your platform? Since shared memory might be platform specific.Louis Go– Louis Go2021-11-01 09:59:20 +00:00Commented Nov 1, 2021 at 9:59
-
This might helpLouis Go– Louis Go2021-11-01 10:08:51 +00:00Commented Nov 1, 2021 at 10:08
-
@LouisGo I am working in Windows 10.KRG– KRG2021-11-02 01:56:51 +00:00Commented Nov 2, 2021 at 1:56
-
Multiprocessing.shared_memory seems good for you.Louis Go– Louis Go2021-11-02 06:27:23 +00:00Commented Nov 2, 2021 at 6:27
-
@LouisGo Thank you for the comments. I will check multiprocessing.shared_memory. Currently I was able to solve it using mapped memory.KRG– KRG2021-11-02 06:29:18 +00:00Commented Nov 2, 2021 at 6:29
Add a comment
|
1 Answer
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()
2 Comments
kevinlinxc
Would docs.python.org/3/library/multiprocessing.shared_memory.html be better for this, or is mmap better?
poukill
@kevinlinxc : It did not work for me for a cross platform solution. I tried and explained that here : stackoverflow.com/questions/69091769/…