2013-10-18 52 views
0

我用numpy创建了一个结构化数组。每个结构都表示一个像素的rgb值。如何从函数中填充一个numpy结构数组?

我想解决如何从一个函数中填充数组,但我不断收到'预计可读的缓冲区对象'错误。

我可以从我的函数中设置单个值,但是当我尝试使用'fromfunction'时失败。

我从控制台复制了dtype。

任何人都可以指出我的错误吗?

是否必须使用一个3维阵列,而不是结构

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')]) 
+0

'pixel_output = ...'不会尝试填充数组。它将'fromfunction'的输出分配给该变量,替换之前存在的任何内容。 – hpaulj

+0

您的错误的位置是相关的。它在'fromfunction'中出现在处理'dtype'的行上的几个级别。这个函数的文档有关'dtype'的说法是什么? – hpaulj

+0

啊哈非常感谢。我没有发现 – user1714819

回答

1
X=np.fromfunction(testfunc,(4,2)) 
pixel_output['f0']=X[0] 
pixel_output['f1']=X[1] 
pixel_output['f2']=X[2] 
print pixel_output 

的2D产生

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返回(4,2)阵列的3元素列表。我将每一个依次分配给pixel_output的3个字段。我会把这个推广留给你。

另一种方式(指定一个元组元素)

for i in range(4): 
    for j in range(2): 
     pixel_output[i,j]=testfunc(i,j) 

而且具有神奇的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) 

当我看fromarrays代码(有IPython的?),我见它正在做我最初做的事情 - 按字段分配。

for i in range(len(arrayList)): 
    _array[_names[i]] = arrayList[i] 
+0

辉煌。谢谢。 – user1714819