【问题标题】:Reshaping a 1D bytes object into a 3D numpy array将 1D 字节对象重塑为 3D numpy 数组
【发布时间】:2018-03-18 13:43:25
【问题描述】:

我正在使用 FFmpeg 解码视频,并将 RGB24 原始数据通过管道传输到 python 中。

所以二进制数据的格式是:

RGBRGBRGBRGB...

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

【问题讨论】:

    标签: python opencv numpy multidimensional-array


    【解决方案1】:

    如果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 processingmisc.imread 可能很有趣。

    【讨论】:

    • 哦,是的,这行得通。我必须使用reshape(360, 640, 3),否则图像会旋转 90 度。我还必须以bgr24 格式输出ffmpeg,否则色调都错了。
    • 反对者:欢迎建设性批评。否则,请停止对我的随机答案投反对票。
    猜你喜欢
    • 2020-04-22
    • 2016-02-10
    • 2021-02-25
    • 1970-01-01
    • 2018-03-17
    • 2021-10-25
    • 2017-09-18
    • 2016-06-30
    • 2021-03-21
    相关资源
    最近更新 更多