简体   繁体   中英

Proper way to make numpy array of ndarrays

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!

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)
arr = np.array([image for x in range(count)])
return arr

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM