2

I am trying to create an empty numpy array, and save all the images that I get from my device. The images come in as numpy array of shape (240,320,3). Creating an empty array to store these images seems like the correct thing to do. When I try to append however, I get this error:

ValueError: all the input arrays must have same number of dimensions

Code as follows:

    import numpy as np

    # will be appending many images of size (240,320,3)
    images = np.empty((0,240,320,3),dtype='uint8')

    # filler image to append
    image = np.ones((240,320,3),dtype='uint8') * 255

    images = np.append(images,image,axis=0)

I need to append many images to this array, so after 100 appends, the shape of the images array should be of shape (100,240,320,3) if done correctly.

2 Answers 2

4

Better than np.append is:

images = np.empty((100,240,320,3),dtype='uint8')
for i in range(100):
    image = ....
    images[i,...] = image

or

alist = []
for i in range(100):
     image = ....
     alist.append(image)
images = np.array(alist)
# or images = np.stack(alist, axis=0) for more control

np.append is just a cover for np.concatenate. So it makes a new array each time through the loop. By the time you add the 100th image, you have copied the first one 100 times!. The other disadvantage with np.append is that you have to adjust the dimensions of image, a frequent source of error. The other frequent error is getting that initial 'empty' array shape wrong.

Sign up to request clarification or add additional context in comments.

Comments

2

Your images array has four dimensions, so you must append a four dimensional item to it. To do so, simply add a new axis to image like so:

images = np.append(images,image[np.newaxis, ...], axis=0)

In a sense, when passing an axis numpy.append is more akin to list.extend than list.append.

2 Comments

Of course, it'd make a lot more sense to stick these arrays in a list as they come and then build the combined array at the end, since repeatedly appending to an array is highly inefficient.
It is more like alist = alist + [image]

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.