繁体   English   中英

从每个维度正交的 3D NumPy 数组中获取随机 2D 切片

[英]Get random 2D slices from a 3D NumPy array orthogonally across each dimension

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

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

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

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

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

首先是一些评论,您说要保留原始信息的 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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM