a = np.array([[[ 1, 11],
[ 3, 13],
[ 5, 15],
[ 7, 17],
[ 9, 19]],
[[ 2, 12],
[ 4, 14],
[ 6, 16],
[ 8, 18],
[10, 20]]])
I'm trying to add the left portion to the right portion of the array in a symmetrical way along the second dimension (so 1+9
, 11+19
, 3+7
, 13+17
for the first sub array above).
I tried this
>>> middle = int(np.ceil(a.shape[1]/2))
>>> a[:,:middle-1,:] + a[:,middle:,:]
array([[[ 8, 28],
[12, 32]],
[[10, 30],
[14, 34]]], dtype=uint8)
which adds the left to the right but not symmetrically. This is what I'm hoping to get
array([[[10, 30],
[10, 30]],
[[12, 32],
[12, 32]]], dtype=uint8)
Looks like you may invert the array, add and cut to the a.shape[1]//2
middle
(a + a[:,::-1,:])[:, :a.shape[1]//2, :]
array([[[10, 30],
[10, 30]],
[[12, 32],
[12, 32]]])
A small modification to your code will work:
middle = int(np.ceil(a.shape[1]/2))
print(a[:,:middle-1,:] + a[:,:middle-1:-1,:])
The second addend is sliced differently here to reverse it. (Original was a[:,middle:,:]
)
Result:
[[[10 30]
[10 30]]
[[12 32]
[12 32]]]
You can either use backward slicing " [b:a:-1]
"
i,j,k = a.shape
a[:,:j//2] + a[:,:(j-1)//2:-1]
# array([[[10, 30],
# [10, 30]],
#
# [[12, 32],
# [12, 32]]])
Or to avoid the slightly error prone computation of the backward limits you can use np.fliplr
half = np.s_[:,:a.shape[1]//2]
a[half] + np.fliplr(a)[half]
# array([[[10, 30],
# [10, 30]],
#
# [[12, 32],
# [12, 32]]])
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.