How can I fill a multi-valued structured array from a function?
I have created a structured array using numpy. Each structure represents the rgb value of a pixel.
I'm trying to figure out how to populate an array from a function, but I keep getting an "expected readable buffered object" error.
I can set individual values ββfrom my function, but when I try to use the "fromfunction" function, it fails.
I copied the dtype from the console.
Can anyone point out my mistake?
Do I need to use 3-dimensional array and not 2d 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')])
source to share
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 list of 3 array elements (4,2)
. I assign each in turn 3 fields pixel_output
. I'll leave you a generalization.
Another way (assign a tuple to an element)
for i in range(4):
for j in range(2):
pixel_output[i,j]=testfunc(i,j)
And with the magic function 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 code fromarrays
(with Ipython?) I see that it does what I did first - assign the field by field.
for i in range(len(arrayList)):
_array[_names[i]] = arrayList[i]
source to share