Read image to an already allocated Mat
modules/imgcodecs/src/loadsave.cpp defines a function imread_
that allows the caller to read image directly to some already existing Mat, potentially having an already allocated memory. However, neither the cv::imread
in the C++ API, nor cv2.imread
in Python API seem to allow reading images this way, forcing the user to allocate a new buffer every time. I'm using OpenCV version 4.1.0.
If I am wrong and this is indeed possible, please let me know what should I read up on to get it to work. If not, how complex would it be to implement this functionality? I'm particularly interested in exposing it as a Python binding.
What I'm trying to do is to have a master process doing IO and several worker processes to do some heavy work on the images. To cut on the inter-process communication time, I'd like to allocate some amount of shared memory, where the master would put images it reads, allowing workers to access it. I reckon it would be faster if master could store images directly into this shared memory, instead of allocating a new buffer, reading to it, and copying data from this buffer to shared mem.
I've asked a similar question on StackOverflow.
Interesting question. It doesn't look like there is a way to do this in the current code. It looks like imread_ calls mat.create on the mat parameter, and mat.create seems to check the current size/dimensions and returns if no new allocation is needed. So could you make a custom build with this imread_ exposed?
imread_ alocates a new image
If you want to make a PR, I think it's easier to work on imdecode and read file using python function
@LBerger Notice that
mat.create
does not allocate if it finds that the existing mat already has memory of the right shape. @Chris I might be able to rig together something like this, but I don't think I know enough about how Python bindings to C++ code work in OpenCV. Would you recommend something I could read to get started on this?@Przemek D img is always empty in imread
@LBerger My point exactly: in
imread
a new image is created, but withimread_
one can pass an existing one to act as a preallocated buffer. What I want is to have access to this function from Python API, so that I can put my newly read image in a specific memory region.