1

我使用 numpy 创建了一个结构化数组。每个结构代表一个像素的 rgb 值。

我正在尝试弄清楚如何从函数中填充数组,但我不断收到“预期的可读缓冲区对象”错误。

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

我从控制台复制了 dtype。

谁能指出我的错误?

我是否必须使用 3 维数组而不是 2d 结构

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')])
4

1 回答 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

生产

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返回一个 3 元素的(4,2)数组列表。我依次将每个分配给pixel_output. 我将把概括留给你。

另一种方式(将元组分配给元素)

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

并具有神奇的功能 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]
于 2013-10-19T05:58:56.217 回答