首页 > 解决方案 > 如何从列表中随机选择一个连续样本?

问题描述

我有不同深度的输入数组,范围从 20 到 32。我无法填充它们以使它们都具有相同的大小,因此最好的选择是在每次迭代时随机选择图像的 z 深度。

我读过它numpy.random.choice()可以用于此,但我得到随机排列的索引,我想要一个连续的选择。

z_values = np.arange(img.shape[0]) # get the depth of this sample
z_rand = np.random.choice(z_values, 20) # create an index array for croping

以上给了我:

[22  4 31 19  9 24 13  6 20 17 28  8 11 27 14 15 30 16 12 25]

这对我没有用,因为它们不是连续的,我不能用它来裁剪我的音量。

有什么办法可以得到一个连续的随机样本?

谢谢

标签: pythonnumpyrandom

解决方案


如果我理解正确,您想随机选择一个 20 长度的切片。因此,只需调整您的逻辑以随机搜索有效的起点,然后切片以获得您需要的结果。

import numpy as np
import random
#pretending this is the image
img = np.array(range(100, 3200, 100))

size_to_slice = 20
if img.shape[0] >= size_to_slice: #make sure you are able to get the length you need
    start = random.randint(0, img.shape[0] - size_to_slice)    
    z_rand = img[start: start + size_to_slice]
else:
    print("selection invalid")

推荐阅读