title: How to convert a numpy array view to opencv matrix?
body: <p>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 <code>cv.fromarray()</code>.  Rather than plug the memory leaks I avoided the <code>fromarray()</code> function and used <code>cv.SetData</code> directly, like this:  </p>
  
  <pre><code>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])
  </code></pre>
  
  <p>This seems to solve the memory leaks and <code>foo_cv</code> seems to be deallocated properly when it goes out of scope.  However, now I have the issue where if <code>foo_numpy</code> is just a slice/view on a bigger array, I'm not permitted <code>foo_numpy.data</code> (cannot get single-segment buffer for discontiguous array).  At the moment I'm working around this by making <code>foo_numpy.copy()</code> if <code>foo_numpy.base != None</code>, which permits getting the buffer on the new copy.   But I have the feeling this is unnecessary, the slice has the <code>__array_struct__</code> and <code>__array_interface__</code> 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.</p>