gpt4 book ai didi

python - 将1D字节对象 reshape 为3D numpy数组

转载 作者:行者123 更新时间:2023-12-02 16:21:24 25 4
gpt4 key购买 nike

我正在使用FFmpeg解码视频,并将RGB24原始数据传递到python中。

因此,二进制数据的格式为:

RGBRGBRGBRGB...

我需要将其转换为 (640, 360, 3) numpy数组,并且想知道是否可以为此使用 reshape,尤其是如何使用。

最佳答案

如果rgb是一个带有3 * 360 * 640字节的字节数组,那么您所需要做的就是:

np.array(rgb).reshape(640, 360, 3)

举个例子:
>>> import random
>>> import numpy as np
>>> bytearray(random.getrandbits(8) for _ in range(3 * 4 * 4))
bytearray(b'{)jg\xba\xbe&\xd1\xb9\xdd\xf9@\xadL?GV\xca\x19\xfb\xbd\xad\xc2C\xa8,+\x8aEGpo\x04\x89=e\xc3\xef\x17H@\x90]\xd5^\x94~/')
>>> rgb = bytearray(random.getrandbits(8) for _ in range(3 * 4 * 4))
>>> np.array(rgb)
array([112, 68, 7, 41, 175, 109, 124, 111, 116, 6, 124, 168, 146,
60, 125, 133, 1, 74, 251, 194, 79, 14, 72, 236, 188, 56,
52, 145, 125, 236, 86, 108, 235, 9, 215, 49, 190, 16, 90,
9, 114, 43, 214, 65, 132, 128, 145, 214], dtype=uint8)
>>> np.array(rgb).reshape(4,4,3)
array([[[112, 68, 7],
[ 41, 175, 109],
[124, 111, 116],
[ 6, 124, 168]],

[[146, 60, 125],
[133, 1, 74],
[251, 194, 79],
[ 14, 72, 236]],

[[188, 56, 52],
[145, 125, 236],
[ 86, 108, 235],
[ 9, 215, 49]],

[[190, 16, 90],
[ 9, 114, 43],
[214, 65, 132],
[128, 145, 214]]], dtype=uint8)

您可能需要查看现有的 numpy and scipy methods for image processing misc.imread 可能很有趣。

关于python - 将1D字节对象 reshape 为3D numpy数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46611019/

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