从三维NumPy阵列中正交获取每个维度的随机二维切片

2024-03-29 05:12:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试随机抽样形状(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]

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


Tags: 图像目的numpy信息imglen方式切片
1条回答
网友
1楼 · 发布于 2024-03-29 05:12:23

首先是一些评论,你说你想保留30%的原始信息。 如果保留每个轴的30%,那么最终只会得到0.3*0.3*0.3 = 0.027(2.7%)的信息。考虑使用{{CD2}}作为约化因子。 下一件事是,您可能希望保留随机抽样索引的空间顺序,因此可以在链接的问题中包含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)

相关问题 更多 >