Slicing after convolution , -1 index does not work
<p>After going through the N-Dimensional array convolution in Python found here on <a href="http://stackoverflow.com/questions/39220929/python-convolution-with-different-dimension"> SO</a>
I now face a problem around which I cannot wrap my head.
The convolution provided by from <code>scipy.ndimage</code> does not allow to select the 'valid' part of the convolution like Matlab's <code>convn</code> so we need to slice out the valid part. </p>

<pre><code>"valid = [slice(kernel.shape[0]//2, -kernel.shape[0]//2), slice(kernel.shape[1]//2, -kernel.shape[1]//2)]"
</code></pre>

<p>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. </p>

<pre><code>z =  convolve(image,kernel)[valid]
</code></pre>

<p>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.</p>

<p>Doing a manual slice</p>

<pre><code>convolve(image,kernel)[1:-1,1:-1] ---&gt; Gives 22x22
convolve(image,kernel)[1:,1:] ---&gt; Gives 23x23
</code></pre>

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

<pre><code>a= np.array([100,101,102])
a[-1]
102
</code></pre>

<p>In Python the upper bound of a slice is open</p>

<pre><code>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])
</code></pre>

<p>In all Python cases, list and arrays, <code>slice(1,-1)</code> removes both the first and the last item.  <code>slice(1,None)</code> (same as <code>x[1:]</code>) removes just the first.</p>

<p>By itself the <code>-1</code> means the last; in a slice it means <code>up to, but including, the last</code>.</p>

<pre><code>In [703]: np.arange(5)[-1]
Out[703]: 4
</code></pre>

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

python numpy scipy