Reputation: 131
I have created a structured array using numpy. Each structure represents the rgb value of a pixel.
I am trying to work out how to fill the array from a function but I keep getting an 'expected a readable buffer object' error.
I can set individual values from my function but when I try to use 'fromfunction' it fails.
I copied the dtype from the console.
Can anyone point out my mistake?
Do I have to use a 3 dimensional array as opposed to a 2d of structures
import numpy as np
#define structured array
pixel_output = np.zeros((4,2),dtype=('uint8,uint8,uint8'))
#print dtype
print pixel_output.dtype
#function to create structure
def testfunc(x,y):
return (x,y,x*y)
#I can fill one index of my array from the function.....
pixel_output[(0,0)]=testfunc(2,2)
#But I can't fill the whole array from the function
pixel_output = np.fromfunction(testfunc,(4,2),dtype=[('f0', '|u1'), ('f1', '|u1'), ('f2', '|u1')])
Upvotes: 1
Views: 4342
Reputation: 231475
X=np.fromfunction(testfunc,(4,2))
pixel_output['f0']=X[0]
pixel_output['f1']=X[1]
pixel_output['f2']=X[2]
print pixel_output
produces
array([[(0, 0, 0), (0, 1, 0)],
[(1, 0, 0), (1, 1, 1)],
[(2, 0, 0), (2, 1, 2)],
[(3, 0, 0), (3, 1, 3)]],
dtype=[('f0', 'u1'), ('f1', 'u1'), ('f2', 'u1')])
fromfunction
returns a 3 element list of (4,2)
arrays. I assign each one, in turn, to the 3 fields of pixel_output
. I'll leave the generalization to you.
Another way (assign a tuple to element)
for i in range(4):
for j in range(2):
pixel_output[i,j]=testfunc(i,j)
And with the magical functiion http://docs.scipy.org/doc/numpy/reference/generated/numpy.core.records.fromarrays.html#numpy.core.records.fromarrays
pixel_output[:]=np.core.records.fromarrays(X)
When I look at the fromarrays
code (with Ipython ??), I see it is doing what I did at first - assign field by field.
for i in range(len(arrayList)):
_array[_names[i]] = arrayList[i]
Upvotes: 2