Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fast conversion of IplImage to Numpy array

Tags:

opencv

numpy

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.

like image 441
jab Avatar asked Oct 27 '12 21:10

jab


People also ask

Does OpenCV work with NumPy array?

OpenCV is the most popular computer vision library and has a wide range of features. It doesn't have its own internal storage format for images, instead, it uses NumPy arrays.

Why do we convert image to array?

Images are an easier way to represent the working model. In Machine Learning, Python uses the image data in the format of Height, Width, Channel format. i.e. Images are converted into Numpy Array in Height, Width, Channel format.


1 Answers

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.

like image 164
chris r. Avatar answered Oct 07 '22 11:10

chris r.