fast conversion of IplImage to Numpy array
numpy, opencv
Solution
Fun Fact: Say you call:
import cv2.cv as cv #Just a formality!
Capture = cv.CaptureFromCAM(0)
Img = cv.QueryFrame(Capture)
The object `Img` is an `ipimage`, and `numpy.asarray(Img)` is erratic at best. However! `Img[:,:]` is a `cvmat` type, and `numpy.asarray(Img[:,:])` works fantastically, and more important: quickly!
This is by far the fastest way I've found to grab a frame and make it an `ndarray` for numpy processing.
Problem
The newer OpenCV documentation here says you can convert an IplImage to a Numpy array just like this: ``` arr = numpy.asarray( im ) ``` but that doesn't work for my needs, because it apparently doesn't support math: ``` x = arr/0.01 TypeError: unsupported operand type(s) for /: 'cv2.cv.iplimage' and 'float' ``` If I try to specify data type, I can't even get that far: ``` arr = numpy.asarray( im, dtype=num.float32 ) TypeError: float() argument must be a string or a number ``` So I'm using the code provided in the older documentation here. Basically, it does this: ``` arr = numpy.fromstring( im.tostring(), dtype=numpy.float32 ) ``` But the `tostring` call is really slow, perhaps because it's copying the data? I need this conversion to be really fast and not copy any buffers it doesn't need to. I don't think the data are inherently incompatible; I'm creating my IplImage with `cv.fromarray` in the first place, which is extremely fast and accepted by the OpenCV functions. Is there a way I can make the newer `asarray` method work for me, or else can I get direct access to the data pointer in the IplImage in a way that `numpy.fromstring` will accept it? I'm using OpenCV 2.3.1 prepackaged for Ubuntu Precise.