New style python buffer protocol and numpy arrays

1.6k views Asked by At

I'm trying to write a fast non copy interface for my python binding of a commercial image processing library. I implemented the new-style buffer api protocol which looks ok according to memoryview():

import hirsch as H
import numpy as np

w,h = 7,5
img = H.HImage.GenImageConst('byte',w,h)
m = memoryview(img)
print 'ndim shape=',m.ndim,m.shape
# -> 2 (5L, 7L)

What I don't understand is why numpy doesn't catch this interface?

a = np.array(img)
print 'ndim size shape=',a.ndim,a.size,a.shape
# -> 0 1 ()

Am I doing something wrong, or should I just resort to using the numpy array interface, which works, though it copies the data?

Note that I'm using python 2.7

2

There are 2 answers

3
Bakuriu On

The np.array function expects an array-like object, not a buffer:

array(object, dtype=None, copy=True, order=None, subok=False, ndmin=0)

Create an array.

object : array_like
An array, any object exposing the array interface, an object whose __array__ method returns an array, or any (nested) sequence.

If you want to create an array from a buffer you should use np.frombuffer:

frombuffer(buffer, dtype=float, count=-1, offset=0)

Interpret a buffer as a 1-dimensional array.

buffer : buffer_like
An object that exposes the buffer interface.

Currently your object, as far as numpy is concerned, is a scalar:

In [7]: a=np.array(1)

In [8]: a.ndim,a.size,a.shape
Out[8]: (0, 1, ())
0
Pierre de Buyl On

You may also try np.asarray. I had success with it but I don't have access to hirsch so I can't test it.

BTW, Bakuriu has it right: you are creating a scalar array (ndim 0, size 1) of type np.object.