export an array of floats to python

sturlamolden sturlamolden at yahoo.no
Thu Feb 22 13:36:05 EST 2007


On Feb 22, 5:40 pm, Peter Wuertz <pwue... at students.uni-mainz.de>
wrote:

> I'm writing a C module for python, that accesses a special usb camera.
> This module is supposed to provide python with data (alot of data). Then
> SciPy is used to fit the data.
>
> My question is, how to make python read from a C array? By reading the
> documentation, one could get the impression that PyBufferObjects do that
> job.

Never mind the buffer object.

Since you use SciPY I assume you want to wrap your C array with a
NumPy array. This can be accomplished using the API call:

PyObject *PyArray_SimpleNewFromData(int nd, npy_intp* dims, int
typenum, void* data);

nd is the number of dimensions.
dims is an array of length nd containing the size in each dimension.
typenum can e.g. be NPY_FLOAT, NPY_DOUBLE, NPY_BYTE, NPY_UBYTE,
NPY_INT, NPY_UINT, NPY_SHORT, NPY_USHORT, etc.

Don't deallocate the data buffer until the NuPy array is deleted.

Otherwise, you could create a new array from scratch using:

PyObject *PyArray_SimpleNew(int nd, npy_intp* dims, int typenum);

Then, use

void *PyArray_DATA(PyObject* obj);

to get a pointer to the data buffer. Then fill in (e.g. memcpy)
whatever you have from your camera.

If you e.g. have unsigned integers from the camera and want to cast
them into Python floats:

unsigned int *camera_buffer = ... /* whatever */
npy_int dim = {480, 640}; /* whatever the size of your data, in C-
order */
PyObject *myarray;
double *array_buffer;
int i;
myarray = PyArray_SimpleNew(2, &dim, NPY_DOUBLE);
Py_INCREF(myarray);
array_buffer = (double *)PyArray_DATA(myarray);
for (i=0; i<640*480; i++) *array_buffer++ = (double) *camera_buffer++;

Now return myarray and be happy.















More information about the Python-list mailing list