pthom / cvnp

cvnp: pybind11 casts between numpy and OpenCV, with shared memory

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

shall the array copy when without share_memory?

tp-nan opened this issue · comments

commented

when shared memory not used , it seems that
m is out of scope, it is thus m.data freed, and the returned array directly points to the old address on the stack!`:

, m.data

pybind11::array make_array()
{
    cv::Mat m(cv::Size(10, 10), CV_8UC1);               // create a matrix on the stack
    pybind11::array a = cvnp::mat_to_nparray(m, false); 
    return a;                                                        
}  // Here be dragons, when closing the scope!
   // m is now out of scope, it is thus freed, 
   // and the returned array directly points to the old address on the stack!

Hi,

I'm not sure I understand your question.
I you call cvnp::mat_to_nparray(m, false), then m and m.data should be copied, and it should not matter that m was previously on the stack.

commented

Hi,

I'm not sure I understand your question. I you call cvnp::mat_to_nparray(m, false), then m and m.data should be copied, and it should not matter that m was previously on the stack.

Thank you for your explanation. I got it.

By the way, If I understand correctly, when shared memory is used, the py::capsule will hold a copy of the original cv::Mat( cv::Mat itself act as a smart pointer) .

return py::capsule(new cv::Mat(m)

and so will keep the stack data alive even if the function returned. Did I misunderstand something? If it is true, we can keep only shared memory version, and also non-contiguous arrays could be supported by shared memory without copying data by using this API:
https://github.com/pybind/pybind11/blob/a19daeac16685877fd0b5ffcadce4b9f60d90f7b/include/pybind11/numpy.h#L700

You might be right
I will need to study this more in details