0

I already have an array with shape (1, 224, 224), a single channel image. I want to change that to (1, 1, 224, 224). I have been trying

newarr.shape
#(1,224,224)
arr = np.array([])
np.append(arr, newarr, 1)

I always get this IndexError: axis 1 out of bounds [0, 1). If i remove the axis as 0 , then the array gets flattened . What am I doing wrong ?

1
  • Just do : newarr[np.newaxis]? Commented Jan 1, 2017 at 21:59

2 Answers 2

1

A dimension of 1 is arbitrary, so it sounds like you want to simply reshape the array. This can accomplished by:

newarr.shape = (1, 1, 244, 244)

or

newarr = newarr[None]
Sign up to request clarification or add additional context in comments.

3 Comments

Explicit assignment to .shape is very nice, I wasn't aware of this feature. This can apparently be used as general reshaping, e.g. newarr.shape = (2, 2, 56, 224), and it will raise a ValueError if the number of elements is not preserved.
The newarr = newarr[:, ...] trick does not seem to have any effect on newarr at all.
@jmd_dk Whoops, I ment None instead of :. The question is now fixed. Yes, this can not be used to modify the overall size of the array.
1

The only way to do an insert into a higher dimensional array is

bigger_arr = np.zeros((1, 1, 224, 224))
bigger_arr[0,...] = arr

In other words, make a target array of the right size, and assign values.

np.append is a booby trap. Avoid it.

Occasionally that's a useful way of thinking of this. But it's simpler, and quicker, to think of this as a reshape problem.

bigger_arr = arr.reshape(1,1,224,224)
bigger_arr = arr[np.newaxis,...]
arr.shape = (1,1,224,224)   # a picky inplace change
bigger_arr = np.expand_dims(arr, 0)

This last one does

a.reshape(shape[:axis] + (1,) + a.shape[axis:])

which gives an idea of how to deal with dimensions programmatically.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.