【问题标题】:How To ReShape a Numpy Array in Python如何在 Python 中重塑 Numpy 数组
【发布时间】:2019-05-05 11:40:21
【问题描述】:

我有一个numpy array 形状为(5879,) 的图像。在 numpy 数组的每个索引中,我都有形状为(640,640,3) 的图像像素。 我想重塑整个数组,使 numpy 数组的形状变为(5879,640,640,3)

【问题讨论】:

  • 试试array.ravel().reshape((5879,640,640,3))
  • 看来你需要np.stack
  • 原始数组的dtype是什么?

标签: python python-3.x numpy image-processing image-segmentation


【解决方案1】:

您希望将图像沿第一个轴堆叠成一个 4D 数组。但是,您的图像都是 3D 的。 所以,首先你需要add a leading singleton dimension 到所有图片,然后concatenate 他们沿着这个轴:

imgs = [i_[None, ...] for i_ in orig_images]  # add singleton dim to all images
x = np.concatenate(imgs, axis=0)  # stack along the first axis

编辑:
基于Mad Phyiscist's comment,似乎在这里使用np.stack 更合适:np.stack 负责为您添加前导单例维度:

x = np.stack(orig_images, axis=0)

【讨论】:

  • 看起来有点矫枉过正。堆叠而不是串联可能更好。
  • 我认为这并不过分。 stack 做同样的事情,只是将它隐藏在函数调用中。方便,但知道如何直接使用concatenate也是一个好主意。
【解决方案2】:

请检查以下代码是否适合您

import numpy as np

b = np.array([5879])
b.shape

output (1,)

a = np.array([[640],[640],[3]])
a = a.reshape((a.shape[0], 1))
a.shape

output (3, 1)

c = np.concatenate((a,b[:,None]),axis=0)
c.shape

Output:
(4, 1) 

np.concatenate((a,b[:,None]),axis=0)

output 
array([[ 640],
   [ 640],
   [   3],
   [5879]])

【讨论】:

  • 您可以使用 c = c.reshape((1,c.shape[0])) 将 c 重塑为 (1, 4)
猜你喜欢
  • 2019-08-25
  • 1970-01-01
  • 2011-10-01
  • 2013-01-06
  • 2017-07-22
  • 2020-11-26
  • 2017-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多