我试图以下列方式改造一个numpy ndarray。
这是我目前由rot_F提供的数组:
# F is laid out to be human readable here
F = np.array(
[
[# Filter 0
[ # Depth 0
[1, -1],
[2, 0]
],
[ # Depth 1
[ 0, 0],
[-1, -1]
]
],
[# Filter 1
[ # Depth 0
[0, -1],
[3, 0]
],
[ # Depth 1
[ 1, 2],
[-1, -1]
]
]
]
)
F = np.moveaxis(F,1,3)
# rotate F by 180 degrees along axes (1,2)
rot_F = np.rot90(F,2,(1,2))
print(rot_F)
OUTPUT FROM print(rot_F):
[[[[ 0 -1]
[ 2 -1]]
[[-1 0]
[ 1 0]]]
[[[ 0 -1]
[ 3 -1]]
[[-1 2]
[ 0 1]]]]
现在我想将rot_F变成以下内容:
desired_filters = np.zeros_like(rot_F)
desired_filters[0,:,:,0] = np.array([[0,2],[-1,1]])
desired_filters[0,:,:,1] = np.array([[0,3],[-1,0]])
desired_filters[1,:,:,0] = np.array([[-1,-1],[0,0]])
desired_filters[1,:,:,1] = np.array([[-1,-1],[2,1]])
print(desired_filters)
OUTPUT FROM print(desired_filters):
[[[[ 0 0]
[ 2 3]]
[[-1 -1]
[ 1 0]]]
[[[-1 -1]
[-1 -1]]
[[ 0 2]
[ 0 1]]]]
基本上我正在尝试将rot_F中第0个深度维度上的所有数组沿着它们自己的深度维度堆叠,并将第1个深度维度上的所有数据堆叠在rot_F中自己的深度维度上,同时保留原始形状。
答案 0 :(得分:1)
经过transpose
的大量试错:
In [157]: rotF = np.rot90(np.moveaxis(F,1,3),2,(1,2))
In [158]: rotF
Out[158]:
array([[[[ 0, -1],
[ 2, -1]],
[[-1, 0],
[ 1, 0]]],
[[[ 0, -1],
[ 3, -1]],
[[-1, 2],
[ 0, 1]]]])
In [159]: F1 = rotF.transpose(3,0,1,2)
In [160]: F1
Out[160]:
array([[[[ 0, 2],
[-1, 1]],
[[ 0, 3],
[-1, 0]]],
[[[-1, -1],
[ 0, 0]],
[[-1, -1],
[ 2, 1]]]])
In [161]: F1.transpose(0,2,3,1)
Out[161]:
array([[[[ 0, 0],
[ 2, 3]],
[[-1, -1],
[ 1, 0]]],
[[[-1, -1],
[-1, -1]],
[[ 0, 2],
[ 0, 1]]]])
那个F1
中间阶段是
In [110]: G =np.array([np.array([[0,2],[-1,1]]),
...: np.array([[0,3],[-1,0]]),
...: np.array([[-1,-1],[0,0]]),
...: np.array([[-1,-1],[2,1]])]).reshape(2,2,2,2)
In [111]: G
Out[111]:
array([[[[ 0, 2],
[-1, 1]],
[[ 0, 3],
[-1, 0]]],
[[[-1, -1],
[ 0, 0]],
[[-1, -1],
[ 2, 1]]]])
或简而言之:
In [163]: rotF.transpose(3,1,2,0)
Out[163]:
array([[[[ 0, 0],
[ 2, 3]],
[[-1, -1],
[ 1, 0]]],
[[[-1, -1],
[-1, -1]],
[[ 0, 2],
[ 0, 1]]]])
很难想象,但显然你只是想换掉第一个和最后一个轴。
看起来rot_F
也是
np.rot90(F,2,(2,3)).transpose(0,2,3,1)
F[:,:,::-1,::-1].transpose(0,2,3,1)
F.transpose(0,2,3,1)[:,::-1,::-1,:]