-1

I came across the following Python script:

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

I understand that the last statement would equal to the 3x3 image array. The part I couldn't understand is how the indexing was made: [1:-1, 1:-1]. How can we interpret what this indexing is doing?

Jongware
  • 22,200
  • 8
  • 54
  • 100
Simplicity
  • 47,404
  • 98
  • 256
  • 385

2 Answers2

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 is a slice excluding the outer 2 items. It starts with 1, and ends before the last -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]])

Same applies to the 2d indexing.

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.]])

Adjacent differences are taken with expressions like image[1:] - image[:-1].

hpaulj
  • 221,503
  • 14
  • 230
  • 353
0

From this 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

and -1 means the last element, so: from 1 to the last element of the two dimension.

GhzNcl
  • 149
  • 1
  • 4
  • 13