【问题标题】:Efficient way of building an uint32 numpy matrix from uint8从 uint8 构建 uint32 numpy 矩阵的有效方法
【发布时间】:2019-04-01 15:02:28
【问题描述】:

我正在存储一个矩阵(一个 python 列表列表,而不是一个 numpy 矩阵),其中包含 [0;255] 范围内的数字 - 可以像 uint8s 一样表示。但是,我想构建一个矩阵,将这些数字打包成 32 位的。

在 numpy 中是否有一种高效/好的方式来执行此操作?目前我正在使用numpy.frombuffer() 逐行重建矩阵,但感觉应该有更方便的方法来实现这一点。

当前代码:

def convert_8to32bit_matrix(mat):
    ret_mat = np.zeros(shape=(mat.shape[0], int(mat.shape[1]/4)))
    for i, row in enumerate(mat):
        ret_mat[i] = np.frombuffer(row, dtype=np.uint32)

    return ret_mat

【问题讨论】:

  • 我很困惑。您的代码与第一段无关。没有列表列表。

标签: python arrays list numpy matrix


【解决方案1】:

使用numpy.ndarray.astype方法:

mat8 = np.array([[1, 2], [3, 4]]).astype(np.uint8)
mat32 = mat8.astype(np.uint32)

print(mat32.dtype) #uint32

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-12-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-04
    • 2019-05-25
    • 2021-07-17
    • 2017-06-18
    相关资源
    最近更新 更多