提取2d numpy数组的随机2d窗口

时间:2018-10-04 08:13:23

标签: python-3.x numpy stride

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个3x3的窗口。

我的实际数组是一个栅格,基本上我需要一堆(成千上万个)3x3小窗口。

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

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

THX!

2 个答案:

答案 0 :(得分:1)

我们可以利用基于np.lib.stride_tricks.as_stridedscikit-image's view_as_windows来获取滑动窗口。 More info on use of as_strided based view_as_windows

for dirpath, dirnames, filenames in os.walk(file_dir):
    if all('01.jpg' not in file for file in filenames):
        for file in filenames :
            if os.path.splitext(file)[1] == '.jpg':
                L.append(os.path.join(dirpath, file))

样品运行-

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]

答案 1 :(得分:0)

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