Wajih - 4 months ago 17

Python Question

After going through the N-Dimensional array convolution in Python found here on SO

I now face a problem around which I cannot wrap my head.

The convolution provided by from

`scipy.ndimage`

`convn`

`"valid = [slice(kernel.shape[0]//2, -kernel.shape[0]//2), slice(kernel.shape[1]//2, -kernel.shape[1]//2)]"`

With a kernel size of [2x2], I not sure as to why I do not get a valid slice for a convolution of image [24x24] with the kernel.

`z = convolve(image,kernel)[valid]`

In return I get a [22x22] image, where I was expecting a [23x23] image.

I thus checked the values of the slice and it seems that -1 does not work here.

Doing a manual slice

`convolve(image,kernel)[1:-1,1:-1] ---> Gives 22x22`

convolve(image,kernel)[1:,1:] ---> Gives 23x23

So the question is... How come -1 gives the last item of a simple array but in my case of slicing it ignores it?

`a= np.array([100,101,102])`

a[-1]

102

Answer

In Python the upper bound of a slice is open

```
In [699]: np.arange(5)
Out[699]: array([0, 1, 2, 3, 4])
In [700]: np.arange(5)[:4]
Out[700]: array([0, 1, 2, 3])
In [701]: np.arange(5)[:-1]
Out[701]: array([0, 1, 2, 3])
In [702]: np.arange(5)[1:-1]
Out[702]: array([1, 2, 3])
```

In all Python cases, list and arrays, `slice(1,-1)`

removes both the first and the last item. `slice(1,None)`

(same as `x[1:]`

) removes just the first.

By itself the `-1`

means the last; in a slice it means `up to, but including, the last`

.

```
In [703]: np.arange(5)[-1]
Out[703]: 4
```

I assume the problem is just about slicing, and applies to any array regardless of whether it comes from a convolution or not.