every blog every motto: Just live your life cause we don’t live twice.
0. 前言
本節主要利用skimage.util.shape 講解對有關數組的裁剪,以及後續恢復。
1. 正文
1.1 生成數組以及查看
import numpy as np
from skimage.util.shape import view_as_windows
a = np.arange(6 * 4).reshape((6, 4))
print(a)
這裏我們生成一個形狀(shape)爲4*4的數組,具體如下圖。
1.2 切割,並查看shape和內容
切割窗口大小
window_shape = (2, 2)
語句:
input_array : 要切割的數據;window_shape:切割窗口大小;step:窗口移動的步幅
output_array = view_as_windows(input_array, window_shape, step)
window_clip = view_as_windows(a, window_shape, 2)
print(window_clip.shape)
切割以後的shape,第一個shape是行切割數;第二個shape列切割數;最後兩個是切割的窗口大小。如下圖二所示。
print(window_clip)
1.3 恢復(錯誤示範)
arr = window_clip.reshape((-1, 2 * 2))
print(arr)
生成如下圖所示,可以發現和原數組不同
1. 4 正確操作
先交換第1軸和第2軸,
temp_arry = window_clip.transpose(0, 2, 1, 3)
print(temp_arry)
再reshape
arr = temp_arry.reshape((-1, 2 * 2))
print(arr)
如下圖所示,還原成功。
1.5 (附)reshape
numpy.reshape(input_arry,newshape,order=‘C’)
默認參數C,會使reshape從多維數組內向外重新改變形狀,這也是上述示範的主要問題所在。
‘C’ means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest.
參考文獻
[1] https://numpy.org/doc/1.18/reference/generated/numpy.reshape.html