Understanding how numpy arrays are allocated in memory

I am trying to use OpenGL textures in python using numpy, but I have problems because I cannot predict how numpy arrays will be organized in memory. The following is an example of a program (which should work as is) illustrating my confusion:

from pylab import *

array_by_hand = array(
    [[[1, 2, 3, 4], [1, 2, 3, 4]], 
    [[1, 2, 3, 4], [1, 2, 3, 4]]], dtype='uint8')

layers = 1 * ones((2, 2)), 2 * ones((2, 2)), 3 * ones((2, 2)), 4 * ones((2, 2))
array_from_layers = dstack(layers)
array_from_layers = array_from_layers.astype('uint8')

print array_by_hand; print
print array_from_layers; print

print ' '.join(x.encode('hex') for x in array_by_hand.data)
print ' '.join(x.encode('hex') for x in array_from_layers.data)
print
print all(array_by_hand == array_from_layers)                 # True
print str(array_by_hand.data) == str(array_from_layers.data)  # False

Although both arrays are equivalent with respect to python, they differ differently in memory and therefore are displayed differently by OpenGL. Can someone explain why this is happening, and how can I force both arrays to the same format?

+5
source share
1 answer

If you instead call the tostring method, it converts the array to a C-contiguous layout:

>>> array_by_hand.tostring() == array_from_layers.tostring()
True

, , dstack. , , numpy. , C- .

+4

All Articles