提取 2d numpy 数组的随机 2d windows

Extract random 2d windows of a 2d numpy array

import numpy as np
arr = np.array(range(60)).reshape(6,10)

arr

> array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
>        [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
>        [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
>        [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
>        [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
>        [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]])

我需要的:

select_random_windows(arr, number_of windows= 3, window_size=3)



>  array([[[ 1,  2,  3],
>            [11, 12, 13],
>            [21, 22, 23]],
>            
>            [37, 38, 39],
>            [47, 48, 49],
>            [57, 58, 59]],
>           
>            [31, 32, 33],
>            [41, 42, 43],
>            [51, 52, 53]]])

在这个假设的情况下,我在主数组 (arr) 中选择 3 个 windows of 3x3。

我的实际阵列是一个栅格,我基本上需要一堆(数千个)小 3x3 windows。

我们将不胜感激任何帮助甚至提示。

实际上我还没有找到任何实用的解决方案...因为很多很多小时

谢谢!

我们可以利用 np.lib.stride_tricks.as_strided based scikit-image's view_as_windows to get sliding windows. .

from skimage.util.shape import view_as_windows

def select_random_windows(arr, number_of_windows, window_size):
    # Get sliding windows
    w = view_as_windows(arr,window_size)

    # Store shape info
    m,n =  w.shape[:2]

    # Get random row, col indices for indexing into windows array
    lidx = np.random.choice(m*n,number_of_windows,replace=False)
    r,c = np.unravel_index(lidx,(m,n))
    # If duplicate windows are allowed, use replace=True or np.random.randint

    # Finally index into windows and return output
    return w[r,c]

样本运行-

In [209]: arr
Out[209]: 
array([[ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
       [20, 21, 22, 23, 24, 25, 26, 27, 28, 29],
       [30, 31, 32, 33, 34, 35, 36, 37, 38, 39],
       [40, 41, 42, 43, 44, 45, 46, 47, 48, 49],
       [50, 51, 52, 53, 54, 55, 56, 57, 58, 59]])

In [210]: np.random.seed(0)

In [211]: select_random_windows(arr, number_of_windows=3, window_size=(2,4))
Out[211]: 
array([[[41, 42, 43, 44],
        [51, 52, 53, 54]],

       [[26, 27, 28, 29],
        [36, 37, 38, 39]],

       [[22, 23, 24, 25],
        [32, 33, 34, 35]]])

你可以试试[numpy.random.choice()][1]。它采用一维或 ndarray,并通过从给定的 ndarray 中采样元素来创建单个元素或 ndarray。您还可以选择提供您想要的数组大小作为输出。