0

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.

5
  • What's your platform? Since shared memory might be platform specific. Commented Nov 1, 2021 at 9:59
  • This might help Commented Nov 1, 2021 at 10:08
  • @LouisGo I am working in Windows 10. Commented Nov 2, 2021 at 1:56
  • Multiprocessing.shared_memory seems good for you. Commented 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. Commented Nov 2, 2021 at 6:29

1 Answer 1

4

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()

Sign up to request clarification or add additional context in comments.

2 Comments

Would docs.python.org/3/library/multiprocessing.shared_memory.html be better for this, or is mmap better?
@kevinlinxc : It did not work for me for a cross platform solution. I tried and explained that here : stackoverflow.com/questions/69091769/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.