【问题标题】:Squashing a 3D matrix into an array of vectors with indices in vector将 3D 矩阵压缩成向量数组,其中索引为向量
【发布时间】:2020-03-15 16:31:23
【问题描述】:

所以我有一个大小为 (w, h, d) 的 numpy 数组,其中 w 是图像宽度,h 是图像高度,d 是它的尺寸。

我的目标是将其转换为所有像素的向量列表(因此是 w*h 大小的列表),并使其索引与像素一起打包。

所以本质上是 [[i,j,r,g,b],[i,j,r,g,b],...] 其中 ij 是像素的坐标。我已经使用循环完成了此操作,但我试图以一种高效的方式在没有循环的情况下执行此操作。

【问题讨论】:

  • 我很好奇,为什么格式会发生变化?

标签: python numpy


【解决方案1】:

您可以执行以下操作: 给定一些示例输入:a=np.random.randint(4,size=(5,4,3)),

您可以先将其重塑为大小为(wh,d) 的二维数组:

b=a.reshape((a.shape[0]*a.shape[1],a.shape[2])) 

接下来,您可以使用列表推导,遍历数组b

 [np.concatenate(([i%a.shape[0],int(i/a.shape[0])],c)) for i,c in enumerate(b)]

【讨论】:

  • 你确定它不应该是 a.shape[1] 吗?
  • @J.Doe,也许,这是一个草图。
【解决方案2】:

这是一种只使用 numpy 函数而不使用循环的方法。

a = np.random.randint(4,size=(5,4,3))

# be careful with a.shape[1] coming first
x, y = np.meshgrid(range(a.shape[1]), range(a.shape[0]))
res = np.concatenate((x[:,:,None], y[:,:,None], a), axis = 2)
res = res.reshape(-1, a.shape[2]+2)

print(res)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-14
    • 2016-06-22
    • 1970-01-01
    • 2018-06-01
    相关资源
    最近更新 更多