numpy从np数组中删除维度 [英] Numpy remove a dimension from np array
问题描述
我有一些要处理的图像,问题是有两种图像均为106 x 106像素,有些是彩色的,有些是黑白的.
I have some images I want to work with, the problem is that there are two kinds of images both are 106 x 106 pixels, some are in color and some are black and white.
只有两(2)个维度的一个:
one with only two (2) dimensions:
(106,106)
一三(3)
(106,106,3)
(106,106,3)
有没有办法去除最后一个尺寸?
Is there a way I can strip this last dimension?
我尝试了np.delete,但似乎没有用.
I tried np.delete, but it did not seem to work.
np.shape(np.delete(Xtrain[0], [2] , 2))
Out[67]: (106, 106, 2)
推荐答案
您可以使用numpy的精美索引(Python内置切片符号的扩展):
You could use numpy's fancy indexing (an extension to Python's built-in slice notation):
x = np.zeros( (106, 106, 3) )
result = x[:, :, 0]
print(result.shape)
打印
(106, 106)
(106, 106, 3)
的形状表示您有3套形状为(106, 106)
的东西.因此,为了剥离"最后一个维度,您只需选择其中一个(这就是精美索引的功能).
A shape of (106, 106, 3)
means you have 3 sets of things that have shape (106, 106)
. So in order to "strip" the last dimension, you just have to pick one of these (that's what the fancy indexing does).
您可以保留所需的任何切片.由于您未指定想要的内容,因此我任意选择保留0.因此,result = x[:, :, 1]
和result = x[:, :, 2]
也会提供所需的形状:这都取决于您需要保留哪个切片.
You can keep any slice you want. I arbitrarily choose to keep the 0th, since you didn't specify what you wanted. So, result = x[:, :, 1]
and result = x[:, :, 2]
would give the desired shape as well: it all just depends on which slice you need to keep.
这篇关于numpy从np数组中删除维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!