将 numpy 元组类型转换为简单类型

Convert numpy tuple type into simple type

我有一个表示 RGBA 的元组数组。我想将元组数据移动到第 5 维。例如。

b=np.array([[[(50, 50, 50, 255), (55, 55, 55, 255), (57, 57, 57, 255),(52, 52, 52, 255)],
    [(46, 46, 46, 255), (51, 51, 51, 255), (53, 53, 53, 255),(55, 55, 55, 255)]],
   [[(50, 50, 50, 255), (51, 51, 51, 255), (52, 52, 52, 255),(50, 50, 50, 255)],
    [(55, 55, 55, 255), (59, 59, 59, 255), (59, 59, 59, 255),(55, 55, 55, 255)]],
   [[(50, 50, 50, 255), (46, 46, 46, 255), (46, 46, 46, 255),(46, 46, 46, 255)],
    [(58, 58, 58, 255), (59, 59, 59, 255), (55, 55, 55, 255),(49, 49, 49, 255)]],
   [[(48, 48, 48, 255), (40, 40, 40, 255), (39, 39, 39, 255),(40, 40, 40, 255)],
    [(56, 56, 56, 255), (52, 52, 52, 255), (48, 48, 48, 255),(46, 46, 46, 255)]]], 
    dtype=[('R', 'u1'), ('G', 'u1'), ('B', 'u1'), ('A', 'u1')])
print(b.shape)

并打印 (4,2,4)。如您所见,元组不是形状的一部分。我希望形状为 (4,2,4,1,4),其中最后的 4 是 RGBA 数据。

我试过了:

c = np.apply_along_axis(lambda x: np.array(x), axis=0, arr=b)
d = c.reshape(b.shape + (1,4)) 

失败(元素数量错误)。所以我试过了。

c = np.array([list(x) for x in b.ravel()])
d = c.reshape(b.shape + (1,4)) 

而且有效!但不知道有没有更好的办法?

recfunctions 有一个函数可以做到这一点:

In [367]: b.shape
Out[367]: (4, 2, 4)
In [368]: b.dtype
Out[368]: dtype([('R', 'u1'), ('G', 'u1'), ('B', 'u1'), ('A', 'u1')])
In [369]: import numpy.lib.recfunctions as rf
In [370]: arr = rf.structured_to_unstructured(b)
In [371]: arr.shape
Out[371]: (4, 2, 4, 4)
In [372]: arr.dtype
Out[372]: dtype('uint8')

评论方法做同样的事情:

In [373]: barr = np.array(b.tolist(), dtype="uint8")
In [374]: barr.shape
Out[374]: (4, 2, 4, 4)
In [375]: barr.dtype
Out[375]: dtype('uint8')