【问题标题】:How do we interpret this indexing?我们如何解释这个索引?
【发布时间】:2018-07-11 02:48:53
【问题描述】:

我遇到了以下 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]。我们如何解释这个索引在做什么?

【问题讨论】:

  • 你读过docs吗?
  • 错误代码,顺便说一句。他们应该使用np.pad。
  • @wim,但在内部 np.pad 做同样的事情 - 分 4 个步骤。它一次单独做 1 个维度的 pre 和 post pad。

标签: python numpy indexing


【解决方案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]])

同样适用于二维索引。

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] 之类的表达式获取相邻的差异。

【讨论】:

    【解决方案2】:

    从此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到最后一个元素的二维。

    【讨论】:

      猜你喜欢
      • 2018-04-16
      • 2014-04-22
      • 2019-11-19
      • 1970-01-01
      • 2010-10-10
      • 2015-06-11
      • 2018-12-30
      • 2018-12-31
      • 1970-01-01
      相关资源
      最近更新 更多