批量生成图像克隆

2024-05-03 02:09:23 发布

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

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

[3,128,192]

现在我要创建一个numpy数组,它包含na副本,它将具有以下维度:

^{pr2}$

有一个numpy函数可以帮助我解决这个问题而不使用循环指令吗?在


Tags: 函数图像numpy指令副本数组pr2
3条回答

可以将^{}方法与^{}一起使用:

import numpy as np

test = np.random.randn(3,128,192)
result = np.repeat(test[np.newaxis,...], 10, axis=0)
print(result.shape)
>> (10, 3, 128, 192)

方法1:一种方法是使用np.repeat在将输入数组扩展到多个维度之后沿着第一个轴重复,一个带有^{}-

np.repeat(a[None],n,axis=0)

样本运行-

1)二维盒:

^{pr2}$

2)3D案例:

In [214]: a
Out[214]: 
array([[[7, 2, 4, 2],
        [6, 7, 7, 6],
        [6, 8, 2, 1]],

       [[1, 5, 8, 5],
        [8, 0, 6, 4],
        [1, 2, 8, 8]]])

In [215]: np.repeat(a[None],2,axis=0)
Out[215]: 
array([[[[7, 2, 4, 2],
         [6, 7, 7, 6],
         [6, 8, 2, 1]],

        [[1, 5, 8, 5],
         [8, 0, 6, 4],
         [1, 2, 8, 8]]],


       [[[7, 2, 4, 2],
         [6, 7, 7, 6],
         [6, 8, 2, 1]],

        [[1, 5, 8, 5],
         [8, 0, 6, 4],
         [1, 2, 8, 8]]]])

方法2:如果您不介意输入数组的只读版本,我们可以使用np.broadcast_to-

np.broadcast_to(a, (n,) + a.shape)

方法3:如果您不介意输入数组的视图,这里有一个有着惊人进展的视图-

def strided_repeat_newaxis0(a, n):
    s0,s1,s2 = a.strides
    shp = (n,) + a.shape
    return np.lib.index_tricks.as_strided(a, shape=shp, strides=(0,s0,s1,s2))

运行时测试

In [290]: a = np.random.randint(0,9,(3,128,192))

In [291]: %timeit np.repeat(a[None],100,axis=0)
100 loops, best of 3: 6.15 ms per loop

In [292]: %timeit strided_repeat_newaxis0(a, 100)
100000 loops, best of 3: 4.69 µs per loop

In [293]: %timeit np.broadcast_to(a, (n,) + a.shape)
100000 loops, best of 3: 3.03 µs per loop

只需使用np.stack

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

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

或者,如果您真正关心性能,您应该使用np.concatenate。在

^{pr2}$

示例:

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)

性能:

# ~ 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

相关问题 更多 >