generating batch of clones from image numpy

前端 未结 3 463
旧巷少年郎
旧巷少年郎 2021-01-13 08:05

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

[3,128,192]

now i want create a numpy array tha

3条回答
  •  北荒
    北荒 (楼主)
    2021-01-13 08:18

    Simply use np.stack

    # say you need 10 copies of a 3D array `a`
    In [267]: n = 10
    
    In [266]: np.stack([a]*n)
    

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

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

    Example:

    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
    

提交回复
热议问题