0

the following code achieves what I want to accomplish, but uses python lists and is probably very inefficient. Please let me know if there is a way to do the following purely with Numpy:

def makeImageArray(count):
    l = []
    for i in range (count):
        l.append(image)
    res = np.array(l)
    return res

Where image is a numpy array of shape (1200,1200,3).

Thank you so much!

2
  • Look into np.stack or np.concatenate Commented Mar 6, 2021 at 18:20
  • You are doing the right thing - start with a list of images you want to join. Commented Mar 6, 2021 at 18:32

1 Answer 1

1

It is possible using numpy.stack() (reference)

If you have multiple images you want to add to the new array you can use this

import numpy as np

image_0 = np.random.rand(1200,1200,3)
image_1 = np.random.rand(1200,1200,3)

stack = np.stack((image_0, image_1))
stack.shape

>>> (2, 1200, 1200, 3)

If you just want to stack one array multiple times

Edit

If you want to stack the same image:

image = np.random.rand(1200,1200,3)
count = 10
stack = np.stack([image for _ in range(count)])
stack.shape
>>> (10, 1200, 1200, 3)
Sign up to request clarification or add additional context in comments.

4 Comments

For this stack and array are the same.
You are correct, but I think using stack makes the code more clear.
stack provides a different error/warning if the arrays don't match in size.
Thats true, however it is deprecated/not good to append/store ndarrays with different shapes or lengths in an ndarray. And here it was onbly asked for images of the same size.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.