简体   繁体   中英

How to split a 2D array into a list of smaller 2D arrays with overlapping? Python

I want to split a 2D array x * y into some smaller 2D arrays which are N * N with overlapping and store these smaller arrays as values in a dictionary, the key will be the index of the top-left item in the larger array.

From

[[1,2,3,4],
 [5,6,7,8],
 [9,10,11,12]]

To

{(0,0):[[1,2],[5,6]], (0,1):[[2,3],[6,7]], (0,2):[[3,4],[7,8]], (1,0):[[5,6],[9,10]], (1,1):[[6,7],[10,11]], (1,2):[[7,8],[11,12]]}

I have idea of splitting it into smaller arrays without overlapping using numpy, but I have no idea of this case.

How can this be done? Full of thanks!

The operation you want to do is a sliding window .

import numpy as np

A = np.array([
    [1,  2,  3,  4],
    [5,  6,  7,  8],
    [9,  10, 11, 12]
])

result = dict(zip(
    [(i, j) for i in range(2) for j in range(3)],
    np.lib.stride_tricks.sliding_window_view(A, (2, 2)).reshape(-1, 2, 2).tolist()
))

# {(0, 0): [[1, 2], [5, 6]], (0, 1): [[2, 3], [6, 7]], (0, 2): [[3, 4], [7, 8]], (1, 0): [[5, 6], [9, 10]], (1, 1): [[6, 7], [10, 11]], (1, 2): [[7, 8], [11, 12]]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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