【问题标题】:Get random 2D slices from a 3D NumPy array orthogonally across each dimension从每个维度正交的 3D NumPy 数组中获取随机 2D 切片
【发布时间】:2020-10-13 05:45:58
【问题描述】:

我正在尝试随机抽取形状为(790, 64, 64, 1) 的 NumPy 数组的 30%。最后一个维度是图像的通道信息,因此本质上它是 3D 图像。目的是在每个维度上以随机的方式正交生成二维切片,以获得原始总信息的 30%。

我查看了 this question 以了解如何随机生成切片,但我无法将其扩展到我的用例。

到目前为止,我只能生成我需要的数据大小。

dim1_len = 0.3 * img.shape[0]
dim2_len = 0.3 * img.shape[1]
dim3_len = 0.3 * img.shape[2]

对不起,如果问题有点宽泛。

【问题讨论】:

  • 您能否详细说明“正交生成二维切片”?如果您包含示例输入和预期输出,将会很有帮助。
  • 这是回答你的问题还是你在寻找别的东西?
  • @scleronomic - meshgrid 解决了它 - 非常感谢! +1 为关于减少系数的说明!

标签: python numpy numpy-ndarray orthogonal


【解决方案1】:

前几个cmets,你说要保留30%的原始信息。 如果您保留每个轴的 30%,那么您最终只会得到 0.3*0.3*0.3 = 0.027 (2.7%) 的信息。考虑使用0.3 ^(1/3)作为缩减因子。 接下来是您可能想要保留随机采样索引的空间顺序,因此可能在您链接的问题中包含np.sort(...)

现在回到主要问题,您可以使用np.meshgrid(*arrays, sparse=True, indexing='ij') 来获取 可用于广播的数组列表。这对于将必要的 newaxis 添加到随机索引非常方便。

import numpy as np

img = np.random.random((790, 64, 64, 1))
alpha = 0.3 ** (1/3)

shape_new = (np.array(img.shape[:-1]) * alpha).astype(int)
idx = [np.sort(np.random.choice(img.shape[i], shape_new[i], replace=False))
       for i in range(3)]
# shapes: [(528,)  (42,)  (42,)]

idx_o = np.meshgrid(*idx, sparse=True, indexing='ij')
# shapes: [(528, 1, 1)
#          (1,  42, 1)
#          (1,  1, 42)]

img_new = img[tuple(idx_o)]
# shape: (528, 42, 42, 1)

【讨论】:

    猜你喜欢
    • 2020-05-07
    • 1970-01-01
    • 1970-01-01
    • 2012-10-26
    • 2021-10-28
    • 1970-01-01
    • 2013-08-23
    • 2018-02-10
    • 1970-01-01
    相关资源
    最近更新 更多