Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an opposite / inverse to numpy.pad() function?

Is there a function doing the opposite of what numpy.pad() does?

What I am looking for is a function to (uniformly) reduce the dimensions of a numpy array (matrix) in each direction. I tried like to call the numpy.pad() with negative values, but it gave an error:

import numpy as np

A_flat = np.array([0,1,2,3,4,5,6,7,8,9,10,11])
A = np.reshape(A_flat, (3,2,-1))

#this WORKS:
B = np.pad(A, ((1,1),(1,1),(1,1)), mode='constant')

# this DOES NOT WORK:
C = np.pad(B, ((-1,1),(1,1),(1,1)), mode='constant')

Error: ValueError: ((-1, 1), (1, 1), (1, 1)) cannot contain negative values.

I understand this function numpy.pad() does not take negative values, but is there a numpy.unpad() or something similar?

like image 638
Chris Avatar asked Jul 17 '14 14:07

Chris


People also ask

How do you negate a NumPy array?

negative() in Python. numpy. negative() function is used when we want to compute the negative of array elements. It returns element-wise negative value of an array or negative value of a scalar.

What does pad do in NumPy?

pad() function is used to pad the Numpy arrays. Sometimes there is a need to perform padding in Numpy arrays, then numPy. pad() function is used. The function returns the padded array of rank equal to the given array and the shape will increase according to pad_width.

How do I reverse the order of a NumPy array?

NumPy: flip() function The flip() function is used to reverse the order of elements in an array along the given axis. The shape of the array is preserved, but the elements are reordered.

How do you horizontally flip a NumPy array?

You can flip the image vertically and horizontally by using numpy. flip() , numpy. flipud() , numpy. fliplr() .


1 Answers

As mdurant suggests, simply use slice indexing:

In [59]: B[1:-1, 1:-1, 1:-1]
Out[59]: 
array([[[ 0,  1],
        [ 2,  3]],

       [[ 4,  5],
        [ 6,  7]],

       [[ 8,  9],
        [10, 11]]])
like image 178
unutbu Avatar answered Sep 20 '22 16:09

unutbu