gpt4 book ai didi

python - 将 width x height x 3 numpy uint8 数组合并为 width x height x 1 uint32 数组

转载 作者:太空宇宙 更新时间:2023-11-03 16:28:39 25 4
gpt4 key购买 nike

我有一个宽 x 高 x 3 channel 数组,例如

import numpy as np
aa = np.array(np.random.randint(0, 255, 300), dtype=np.uint8).reshape((10, 10, 3))

现在,我想将这些数字放入 np.uint32 数组中。我可以通过创建一个新数组并进行按位移位和或操作来做到这一点。不过我想了解是否有更干净的方法通过创建 numpy View 。

最佳答案

您可以使用 .view method :

In [94]: X = numpy.array([10, 2, 4, 8], "uint8")

In [95]: X.view("uint32")
Out[95]: array([134480394], dtype=uint32)

在你的情况下,你首先需要添加一个零平面,或者任何你想要的最后 8 位:

In [110]: aa = np.array(np.random.randint(0, 255, 300),  dtype=np.uint8).reshape((10, 10, 3))

In [111]: concatenate((aa, zeros(shape=(10, 10, 1), dtype=aa.dtype)), 2).view("uint32")

在某些情况下,您可能需要通过 numpy.ascontiguousarray 传递数据首先,特别是在以下任何情况适用的情况下:

Views that change the dtype size (bytes per entry) should normally be avoided on arrays defined by slices, transposes, fortran-ordering, etc.

请参阅view documentation .

您可能还需要注意 uint32 的字节顺序。 ( <u4>u4 )。

关于python - 将 width x height x 3 numpy uint8 数组合并为 width x height x 1 uint32 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37791134/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com