I'm using opencv v2.2 to do some template matching on ndarrays, and I had great trouble with memory leaks when using their wrapped method cv.fromarray()
. Rather than plug the memory leaks I avoided the fromarray()
function and used cv.SetData
directly, like this:
assert foo_numpy.dtype == 'uint8'
assert foo_numpy.ndim == 3
h, w = foo_numpy.shape[:2]
foo_cv = cv.CreateMat(h, w, cv.CV_8UC3)
cv.SetData(foo_cv, foo_numpy.data, foo_numpy.strides[0])
This seems to solve the memory leaks and foo_cv
seems to be deallocated properly when it goes out of scope. However, now I have the issue where if foo_numpy
is just a slice/view on a bigger array, I'm not permitted foo_numpy.data
(cannot get single-segment buffer for discontiguous array). At the moment I'm working around this by making foo_numpy.copy()
if foo_numpy.base != None
, which permits getting the buffer on the new copy. But I have the feeling this is unnecessary, the slice has the __array_struct__
and __array_interface__
so I should be able to just stride it with the appropriate stepsizes somehow? I'm not sure how to do it in a nice way, because the base of this one can also be a view on another larger array ad infinitum.