我遇到了以下Python脚本:
import numpy
image = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
image_padded = numpy.zeros((image.shape[0] + 2, image.shape[1] + 2))
image_padded[1:-1, 1:-1] = image
据我所知,最后一个语句等于3x3图像数组。我无法理解的部分是如何编制索引:[1:-1, 1:-1]
。我们如何解释这个索引的作用?
答案 0 :(得分:1)
In [45]:
...: image = numpy.array([[1,2,3],[4,5,6],[7,8,9]])
...: image_padded = numpy.zeros((image.shape[0] + 2, image.shape[1] + 2))
...:
1:-1
是一个不包括外部2项的切片。它以1
开头,在最后-1
之前结束:
In [46]: image[1:,:]
Out[46]:
array([[4, 5, 6],
[7, 8, 9]])
In [47]: image[:-1,:]
Out[47]:
array([[1, 2, 3],
[4, 5, 6]])
In [48]: image[1:-1,:]
Out[48]: array([[4, 5, 6]])
同样适用于2d索引。
In [49]: image_padded[1:-1, 1:-1]
Out[49]:
array([[0., 0., 0.],
[0., 0., 0.],
[0., 0., 0.]])
In [50]: image_padded[1:-1, 1:-1] = image
In [51]: image_padded[1:-1, 1:-1]
Out[51]:
array([[1., 2., 3.],
[4., 5., 6.],
[7., 8., 9.]])
In [52]: image_padded
Out[52]:
array([[0., 0., 0., 0., 0.],
[0., 1., 2., 3., 0.],
[0., 4., 5., 6., 0.],
[0., 7., 8., 9., 0.],
[0., 0., 0., 0., 0.]])
使用image[1:] - image[:-1]
等表达式进行相邻差异。
答案 1 :(得分:0)
从此thread
a[start:end] # items start through end-1
a[start:] # items start through the rest of the array
a[:end] # items from the beginning through end-1
a[:] # a copy of the whole array
和-1表示最后一个元素,因此:从1到最后一个元素。