例如,我有一个形状为a
的numpy数组1000*3*256*256
。
换句话说,a
是一个包含1000个图像的数组,每个图像的大小为3*256*256
。
我想随意翻转每一张图片,所以我的问题是如何有效地做到这一点?谢谢!
答案 0 :(得分:1)
基础:array[slice(a,b,c)]
相当于array[a:b:c]
,反转(“翻转”)数组使用slice(None, None, -1)
,这与array[::-1]
相同。
因此,让我们为每张图片构建随机翻转:
>>> import random
>> flips = [(slice(None, None, None),
... slice(None, None, random.choice([-1, None])),
... slice(None, None, random.choice([-1, None])))
... for _ in xrange(a.shape[0])]
第一个切片用于通道,第二个切片用于Y轴,第三个切片用于X轴。让我们构建一些测试数据:
>>> import numpy as np
>>> a = np.array(range(3*2*5*5)).reshape(3,2,5,5)
我们可以将每个随机翻转单独应用于每个图像:
>>> flips[0]
(slice(None, None, None), slice(None, None, -1), slice(None, None, None))
>>> a[0]
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, 48, 49]]])
>>> a[0][flips[0]]
array([[[20, 21, 22, 23, 24],
[15, 16, 17, 18, 19],
[10, 11, 12, 13, 14],
[ 5, 6, 7, 8, 9],
[ 0, 1, 2, 3, 4]],
[[45, 46, 47, 48, 49],
[40, 41, 42, 43, 44],
[35, 36, 37, 38, 39],
[30, 31, 32, 33, 34],
[25, 26, 27, 28, 29]]])
如您所见,flips[0]
垂直翻转图像。现在对每张图片都很简单:
>>> random_flipped = np.array([img[flip] for img, flip in zip(a, flips)])