views:

45

answers:

2

I have a label matrix with dimension (100*100), stored as a numpy array, and I would like to display the matrix with pyglet.

My original idea is to use this matrix to form a new pyglet image using function pyglet.image.ImageData(). It requres a buffer of the imagedata as an input, however I have no idea how to get a right formated buffer from the numpy array.

Any one have any idea?

ps. my current solution:

3d_label = numpy.empty([100,100,3])
3d_label[:,:,0] = label * 255            # value range of label is [0,1]
3d_label[:,:,1] = label * 255
3d_label[:,:,2] = label * 255
image_data = ctypes.string_at(id(3d_label.tostring())+20, 100*100*3)
image = pyglet.image.ImageData(100, 100, 'RGB', image_data, -100*3)

Any better way to construct a [100*100*3] matrix from 3 [100*100] matrix with numpy?

+1  A: 

I think what you are looking for is np.dstack (or more generally, np.concatenate):

label255=label*255
label3=numpy.dstack((label255,label255,label255))

This shows dstack produces the same array (label3) as your construction for label_3d:

import numpy as np

label=np.random.random((100,100))
label255=label*255
label3=np.dstack((label255,label255,label255))

label_3d = np.empty([100,100,3])
label_3d[:,:,0] = label * 255            # value range of label is [0,1]
label_3d[:,:,1] = label * 255
label_3d[:,:,2] = label * 255
print(np.all(label3==label_3d))
# True

PS. I'm not sure, but have you tried using label3.data instead of ctypes.string_at(id(label3.tostring())+20, 100*100*3) ?

unutbu
+1 for ``label3.data``, which is more efficient than building a string.
EOL
label3.data.__str__() can replace ctypes.string_at(id(label3.tostring())+20, 100*100*3), but label3.data can not
zhanwu
A: 

You can get the memory representation of your array with 3d_label.tostring().

The tostring() method allows you to change the memory ordering of the elements:

Parameters
----------
order : {'C', 'F', None}, optional
    Order of the data for multidimensional arrays:
    C, Fortran, or the same as for the original array.

PS: The 3d_label.data of ~unutbu requires less memory, since no string is constructed. However, it does not allow you to change the order in which the elements are output.

EOL