函数说明:np.lib.stride_tricks.sliding_window_view(arr, window_shape)
参数说明:
arr
:要创建滑动窗口视图的数组。
window_shape
:滑动窗口的形状,表示切割出的小块的大小。
作用:用于创建滑动窗口视图。对多维数组进行滑动窗口操作,从而以指定的形状和步幅切割数组。
import numpy as np
# 创建一个 3D 数组
arr = np.arange(64).reshape(4, 4, 4)
print("原始数组:", arr)
print("原始数组形状:", arr.shape)
# 定义窗口大小
window_shape = (2, 2, 2)
# 创建滑动窗口视图
window_view = np.lib.stride_tricks.sliding_window_view(arr, window_shape)
print("滑动窗口视图形状:", window_view.shape)
# 打印所有小块
# print("所有小块:")
# for block in window_view:
# print(block)
# 通过索引获取特定的小立方体
for x in range(window_view.shape[1]):
for y in range(window_view.shape[2]):
selected_block = window_view[0, x, y]
print(x, y)
print(selected_block)
输出结果如下:
原始数组: [[[ 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]
[60 61 62 63]]]
原始数组形状: (4, 4, 4)
滑动窗口视图形状: (3, 3, 3, 2, 2, 2)
0 0
[[[ 0 1]
[ 4 5]]
[[16 17]
[20 21]]]
0 1
[[[ 1 2]
[ 5 6]]
[[17 18]
[21 22]]]
0 2
[[[ 2 3]
[ 6 7]]
[[18 19]
[22 23]]]
1 0
[[[ 4 5]
[ 8 9]]
[[20 21]
[24 25]]]
1 1
[[[ 5 6]
[ 9 10]]
[[21 22]
[25 26]]]
1 2
[[[ 6 7]
[10 11]]
[[22 23]
[26 27]]]
2 0
[[[ 8 9]
[12 13]]
[[24 25]
[28 29]]]
2 1
[[[ 9 10]
[13 14]]
[[25 26]
[29 30]]]
2 2
[[[10 11]
[14 15]]
[[26 27]
[30 31]]]