15

我在 2d 中有一个 (w,h) np 数组。我想制作一个值大于 1 的 3d 维度,并将其值沿 3rd 维度复制。我希望广播能做到,但它不能。这就是我的做法

arr = np.expand_dims(arr, axis=2)
arr = np.concatenate((arr,arr,arr), axis=2)

有更快的方法吗?

4

7 回答 7

14

您可以所有暗淡向前推,引入一个单一暗淡/新轴作为最后一个暗淡来创建一个3D数组,然后沿着那个重复三次np.repeat,就像这样 -

arr3D = np.repeat(arr[...,None],3,axis=2)

这是另一种使用方法np.tile-

arr3D = np.tile(arr[...,None],3)
于 2016-09-13T05:56:18.577 回答
8

另一种有效的方法:

x_train = np.stack((x_train,) * 3, axis=-1)

于 2017-10-18T00:44:47.537 回答
3

更有助于将灰色 a 通道​​矩阵转换为 3 通道矩阵。

img3 = np.zeros((gray.shape[0],gray.shape[1],3))
img3[:,:,0] = gray
img3[:,:,1] = gray
img3[:,:,2] = gray
fig = plt.figure(figsize = (15,15))
plt.imshow(img3)
于 2018-07-12T12:01:05.380 回答
3

另一种简单的方法是使用矩阵乘法 - 乘以一个矩阵,这实际上将在新维度上复制值:

a=np.random.randn(4,4)    #a.shape = (4,4)
a = np.expand_dims(a,-1)  #a.shape = (4,4,1)
a = a*np.ones((1,1,3))
a.shape                   #(4, 4, 3)
于 2018-08-02T19:12:41.833 回答
1

不确定我是否理解正确,但在这种情况下,广播似乎对我有用:

>>> a = numpy.array([[1,2], [3,4]])
>>> c = numpy.zeros((4, 2, 2))
>>> c[0] = a
>>> c[1:] = a+1
>>> c
array([[[ 1.,  2.],
        [ 3.,  4.]],

       [[ 2.,  3.],
        [ 4.,  5.]],

       [[ 2.,  3.],
        [ 4.,  5.]],

       [[ 2.,  3.],
        [ 4.,  5.]]])
于 2016-09-13T06:01:12.840 回答
1

这会奏效。(我认为这不是推荐的方式 :-) 但也许这是您认为最接近的方式。)

np.array([img, img, img]).transpose(1,2,0)

img只需在您想要的任何时候()堆叠目标(3),并使通道(3)转到最后一个轴。

于 2019-04-22T08:35:13.683 回答
1

我建议您使用准系统numpy.concatenate(),因为下面的代码显示它是所有其他建议答案中最快的:

# sample 2D array to work with
In [51]: arr = np.random.random_sample((12, 34))

# promote the array `arr` to 3D and then concatenate along `axis 2`
In [52]: arr3D = np.concatenate([arr[..., np.newaxis]]*3, axis=2)

# verify for desired shape
In [53]: arr3D.shape
Out[53]: (12, 34, 3)

你可以看看下面的时间来说服自己。(排序:从最好到最差):

In [42]: %timeit -n 100000 np.concatenate([arr[..., np.newaxis]]*3, axis=2)
1.94 µs ± 32.9 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [43]: %timeit -n 100000 np.repeat(arr[..., np.newaxis], 3, axis=2)
4.38 µs ± 46.7 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [44]: %timeit -n 100000 np.dstack([arr]*3)
5.1 µs ± 57.6 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [49]: %timeit -n 100000 np.stack([arr]*3, -1)
5.12 µs ± 125 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

In [46]: %timeit -n 100000 np.tile(arr[..., np.newaxis], 3)
7.13 µs ± 85.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

话虽如此,如果您正在寻找最短的代码,那么您可以使用:

# wrap your 2D array in an iterable and then multiply it by the needed depth
arr3D = np.dstack([arr]*3)

# verify shape
print(arr3D.shape)
(12, 34, 3)
于 2019-04-18T22:04:07.220 回答