【发布时间】:2018-03-18 13:43:25
【问题描述】:
我正在使用 FFmpeg 解码视频,并将 RGB24 原始数据通过管道传输到 python 中。
所以二进制数据的格式是:
RGBRGBRGBRGB...
我需要将其转换为 (640, 360, 3) numpy 数组,并且想知道是否可以为此使用 reshape,尤其是如何使用。
【问题讨论】:
标签: python opencv numpy multidimensional-array
我正在使用 FFmpeg 解码视频,并将 RGB24 原始数据通过管道传输到 python 中。
所以二进制数据的格式是:
RGBRGBRGBRGB...
我需要将其转换为 (640, 360, 3) numpy 数组,并且想知道是否可以为此使用 reshape,尤其是如何使用。
【问题讨论】:
标签: python opencv numpy multidimensional-array
如果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 可能很有趣。
【讨论】:
reshape(360, 640, 3),否则图像会旋转 90 度。我还必须以bgr24 格式输出ffmpeg,否则色调都错了。