python - 将 numpy 数组从一个(2-D)复制到另一个(3-D)

标签 python arrays opencv numpy

我尝试将一个数组(A(2-D))复制到另一个数组(B(3-D)),其形状如下

A 是 m * n 数组,B 是 m * n * p 数组

我尝试了以下代码,但速度非常慢,比如 1 秒/帧

for r in range (0, h):
    for c in range (0, w):
        x = random.randint(0, 20)
        B[r, c, x] = A[r, c]

我还阅读了一些有关精美索引的网站,但我仍然不知道如何将其应用到我的网站中。

最佳答案

我提出了一个使用数组索引的解决方案。 MNP 分别是 (m,n) 索引数组,指定 m*n 个元素B将从A接收数据。

def indexing(A, p):
    m,n = A.shape
    B = np.zeros((m,n,p), dtype=int)
    P = np.random.randint(0, p, (m,n))
    M, N = np.indices(A.shape)
    B[M,N,P] = A
    return B

为了比较,原始循环和使用 shuffle 的解决方案

def looping(A, p):
    m, n = A.shape
    B = np.zeros((m,n,p), dtype=int)
    for r in range (m):
        for c in range (n):
            x = np.random.randint(0, p)
            B[r, c, x] = A[r, c]
    return B

def shuffling(A, p):
    m, n = A.shape
    B = np.zeros((m,n,p), dtype=int)
    B[:,:,0] = A
    map(np.random.shuffle, B.reshape(m*n,p))
    return B

对于 m,n,p = 1000,1000,20,时间为:

looping:    1.16 s
shuffling: 10 s
indexing:     271 ms

对于较小的 m,n,循环速度最快。我的索引解决方案需要更多时间来设置,但实际分配速度很快。洗牌解决方案的迭代次数与原始解决方案的迭代次数相同。


MN 数组不必是满的。它们可以分别是列数组和行数组

M = np.arange(m)[:,None]
N = np.arange(n)[None,:]

M,N = np.ogrid[:m,:n]

这可以节省一些时间,对于小型测试用例比大型测试用例更是如此。


可重复的版本:

def indexing(A, p, B=None):
    m, n = A.shape
    if B is None:
        B = np.zeros((m,n,p), dtype=int)
    for r in range (m):
        for c in range (n):
            x = np.random.randint(0, p)
            B[r, c, x] = A[r, c]
    return B
indexing(A,p,indexing(A,p))

如果A的大小与B的第1个2暗淡的大小不同,则必须更改索引范围。 A 也不必是二维数组:

B[[0,0,2],[1,1,0],[3,4,5]] = [10,11,12]

关于python - 将 numpy 数组从一个(2-D)复制到另一个(3-D),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26327137/

相关文章:

Python 可选参数对

python - 在一张图中绘制多条线,x 轴为时间(以月为单位),y 轴为出现次数

python - 从雅虎财经抓取数据

python-3.x - 如何解决类型错误: 'NoneType' object is not subscriptable in opencv (cv2 Python)

opencv - convertTo 函数中 Mat 的内存泄漏

python - 使用 Tkinter 的 'command = ' 中的 lambda 函数。

python - 循环遍历 python 数组以匹配第二个数组中的多个条件,快速方法?

c++ - 数组C++中最大和第二大数

java - JVM需要多少内存来分配一个字符数组?

python - 在 android/python 中使用 opencv 处理视频的问题