1

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')])
3
  • pixel_output = ... does not try to fill the array. It assigns the output of fromfunction to that variable, replacing anything that was there before. Commented Oct 19, 2013 at 18:46
  • The location of your error is relevant. It occurs several levels down in fromfunction, on a line that deals with dtype. What does the documentation for this function say about dtype? Commented Oct 19, 2013 at 18:48
  • Aha yes thanks alot. I didn't spot that Commented Oct 20, 2013 at 19:35

1 Answer 1

2
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]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.