从图像numpy生成一批克隆 [英] generating batch of clones from image numpy

查看:108
本文介绍了从图像numpy生成一批克隆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 a numpy 数组(图像),其大小为:

I have a numpy array (an image) called a with this size:

[3,128,192]

现在我想创建一个包含 a 个副本的numpy数组,该副本具有以下维度:

now i want create a numpy array that contains n copies of a which will have this dimension:

[n,3,128,192]

存在一个numpy函数,可以在不使用循环指令的情况下帮助我解决此问题?

exist a numpy function that can help me with this problem without using loop instructions?

推荐答案

只需使用np.stack

# say you need 10 copies of a 3D array `a`
In [267]: n = 10

In [266]: np.stack([a]*n)

或者,如果您确实担心性能,则应该使用np.concatenate.

Alternatively, you should use np.concatenate if you're really concerned about the performance.

In [285]: np.concatenate([a[np.newaxis, :, :]]*n)

示例:

In [268]: a
Out[268]: 
array([[[ 0,  1,  2,  3],
        [ 4,  5,  6,  7],
        [ 8,  9, 10, 11],
        [12, 13, 14, 15]],

       [[16, 17, 18, 19],
        [20, 21, 22, 23],
        [24, 25, 26, 27],
        [28, 29, 30, 31]],

       [[32, 33, 34, 35],
        [36, 37, 38, 39],
        [40, 41, 42, 43],
        [44, 45, 46, 47]]])

In [271]: a.shape
Out[271]: (3, 4, 4)

In [269]: n = 10

In [270]: np.stack([a]*n).shape
Out[270]: (10, 3, 4, 4)

In [285]: np.concatenate([a[np.newaxis, :, :]]*n).shape
Out[285]: (10, 3, 4, 4)


性能:


Performance:

# ~ 4x faster than using `np.stack`
In [292]: %timeit np.concatenate([a[np.newaxis, :, :]]*n)
100000 loops, best of 3: 10.7 µs per loop

In [293]: %timeit np.stack([a]*n)
10000 loops, best of 3: 41.1 µs per loop

这篇关于从图像numpy生成一批克隆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆