我们如何解释这个索引?

2024-04-19 10:00:56 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 图像imageimportnumpy脚本zeros数组语句
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到二维的最后一个元素。你知道吗

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]这样的表达式表示。你知道吗

相关问题 更多 >