制作nDarray numpy数组的正确方法

2024-04-28 05:35:30 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的代码实现了我想要实现的目标,但是使用了python列表,可能效率很低。请让我知道是否有一种方法可以完全使用Numpy执行以下操作:

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

其中图像是形状的numpy数组(12001200,3)

非常感谢你


2条回答
arr = np.array([image for x in range(count)])
return arr

可以使用numpy.stack()reference

如果要将多个图像添加到新阵列中,可以使用

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)

如果只想将一个数组堆叠多次

编辑

如果要堆叠相同的图像:

image = np.random.rand(1200,1200,3)
count = 10
stack = np.stack([image for _ in range(count)])
stack.shape
>>> (10, 1200, 1200, 3)

相关问题 更多 >