【问题标题】:Transform 1-D numpy array into 3D RGB array将 1-D numpy 数组转换为 3D RGB 数组
【发布时间】:2018-04-19 02:38:14
【问题描述】:

将包含 rgb 数据的 1D 数组转换为 3D RGB 数组的最佳方法是什么?

如果数组是这个顺序,那就很容易了,(一次重塑)

RGB RGB RGB RGB...

但是我的数组是这样的,

RRRR...GGGG....BBBB

有时甚至,

GGGG....RRRR..BBBB(结果仍然应该是 RGB 而不是 GRB)

我当然可以派生一些 Python 方法来实现这一点,我什至尝试了一个 numpy 解决方案,它可以工作,但它显然是一个糟糕的解决方案,我想知道什么是最好的方法,也许是一个内置的 numpy功能?

我的解决方案:

for i in range(len(video_string) // 921600 - 1):        # Consecutive frames iterated over.
    frame = video_string[921600 * i: 921600 * (i + 1)]  # One frame
    array = numpy.fromstring(frame, dtype=numpy.uint8)  # Numpy array from one frame.
    r = array[:307200].reshape(480, 640)
    g = array[307200:614400].reshape(480, 640)
    b = array[614400:].reshape(480, 640)
    rgb = numpy.dstack((b, r, g))                       # Bring them together as 3rd dimention

不要让 for 循环让您感到困惑,我只是将帧彼此连接成一个字符串,就像视频一样,这不是问题的一部分。

What did not help me: 在这个问题中,r、g、b 值已经是二维数组,所以对我的情况没有帮助。

Edit1:所需的数组形状为640 x 480 x 3

【问题讨论】:

  • 如何在不知道高度或宽度的情况下重塑为3D 数组?
  • @Divakar 抱歉我忘了说,我会编辑,但是可以看到一帧是 921600 字节,除以三,我们有 307200,它是 640x480 的乘积。跨度>

标签: python arrays numpy rgb


【解决方案1】:

重新整形为2D,转置然后重新整形为3D 以形成RRRR...GGGG....BBBB 形式-

a1D.reshape(3,-1).T.reshape(height,-1,3) # assuming height is given

或者使用Fortran order 的 reshape 然后交换轴 -

a1D.reshape(-1,height,3,order='F').swapaxes(0,1)

示例运行 -

In [146]: np.random.seed(0)

In [147]: a = np.random.randint(11,99,(4,2,3)) # original rgb image

In [148]: a1D = np.ravel([a[...,0].ravel(), a[...,1].ravel(), a[...,2].ravel()])

In [149]: height = 4

In [150]: np.allclose(a, a1D.reshape(3,-1).T.reshape(height,-1,3))
Out[150]: True

In [151]: np.allclose(a, a1D.reshape(-1,height,3,order='F').swapaxes(0,1))
Out[151]: True

对于GGGG....RRRR....BBBB 表单,只需附加:[...,[1,0,2]]

【讨论】:

  • 感谢您的回答,我的代码依赖于性能,因此我将测试结果并将其发布在问题中,也接受任何有关性能的建议。
  • @Rockybilly 随时通知我。
  • 我目前正在处理一些其他问题,等我回到这个问题时,我一定会和你分享结果:)
猜你喜欢
  • 2021-12-29
  • 2016-11-24
  • 2019-10-31
  • 2017-07-26
  • 2019-01-15
  • 2018-08-22
  • 1970-01-01
  • 2017-03-10
  • 1970-01-01
相关资源
最近更新 更多