Kevin Kevin - 1 year ago 118
Python Question

Numpy remove a dimension from np array

I have some images I want to work with, the problem is that there are two kinds of images both are 106 x 106 pixels, some are in color and some are black and white.

one with only two (2) dimensions:


and one with three (3)


Is there a way I can strip this last dimension?

I tried np.delete, but it did not seem to work.

np.shape(np.delete(Xtrain[0], [2] , 2))
Out[67]: (106, 106, 2)

Answer Source

You could use slice notation:

x = np.zeros( (106, 106, 3) )
result = x[:, :, 0]
print result.shape


(106, 106)

A shape of (106, 106, 3) means you have 3 sets of things that have shape (106, 106). So in order to "strip" the last dimension, you just have to pick one of these (that's what the slice notation does).

You can keep any slice you want. I arbitrarily choose to keep the 0th, since you didn't specify what you wanted. So, result = x[:, :, 1] and result = x[:, :, 2] would give the desired shape as well: it all just depends on which slice you need to keep.