Repeat/duplicate a given numpy array ten times

2020-04-11 04:15发布

问题:

I have a numpy array of shape, (320, 320, 3). I want to repeat/duplicate this data 10 times, and want to get new array of shape (10, 320, 320, 3).

How to do it?

array = np.ones((320, 320, 3))
print (array.shape)
(320, 320, 3)

I tried as:

res = np.tile(array, 10)
print (res.shape)

(320, 320, 30).

But I want shape of,

(10, 320, 320, 3)

回答1:

We can use np.broadcast_to -

np.broadcast_to(a,(10,)+a.shape).copy() # a is input array

If we are okay with a view instead, skip .copy() for a virtually free runtime and zero memory overhead.

We can also use np.repeat -

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


回答2:

You can use np.resize, which will tile if the new size is larger than the old one:

array = np.ones((320, 320, 3))

new_array = np.resize(array, (10, *array.shape))
print(new_array.shape)
# (10, 320, 320, 3)

From the docs:

numpy.resize(a, new_shape): If the new array is larger than the original array, then the new array is filled with repeated copies of a.



回答3:

res = np.tile(array, (10,1,1,1))
print (res.shape)