麻烦复制和反转数组的部分numpy

时间:2015-01-24 14:14:18

标签: python numpy

我正在尝试复制输入2d数组的一部分" img"并镜像该部分并将其复制到2d数组" out"

以下代码可以满足我的需求

a = numpy.zeros(shape=(pad, pad))
a[:,:]=img[0:pad,0:pad]
out[0:pad,0:pad]=a[::-1,::-1]

但只是做以下事情

out[0:pad,0:pad]=img[0:pad:-1,0:pad:-1]

而是为ValueError: could not broadcast input array from shape (0,0) into shape (2,2)返回pad=2,我不确定原因。

1 个答案:

答案 0 :(得分:1)

img[0:pad:-1,0:pad:-1] 

应该是

img[pad-1::-1, pad-1::-1]

因为您希望索引从pad-1开始并逐步降低到0.请参阅此处查看the complete rules governing NumPy basic slicing

例如,

import numpy as np

img = np.arange(24).reshape(6,4)
# array([[ 0,  1,  2,  3],
#        [ 4,  5,  6,  7],
#        [ 8,  9, 10, 11],
#        [12, 13, 14, 15],
#        [16, 17, 18, 19],
#        [20, 21, 22, 23]])

pad = 2
out = img[pad-1::-1, pad-1::-1]

print(out)

产量

[[5 4]
 [1 0]]