Numpy从np数组中删除维度

时间:2022-04-20 23:50:44

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.

我有一些我想要使用的图像,问题是有两种图像都是106 x 106像素,一些是彩色的,一些是黑色和白色。

one with only two (2) dimensions:

一个只有两(2)个维度:

(106,106)

(106106)

and one with three (3)

一个有三个(3)

(106,106,3)

(106,106,3)

Is there a way I can strip this last dimension?

有没有办法可以去掉这最后一个维度?

I tried np.delete, but it did not seem to work.

我试过np.delete,但它似乎没有用。

np.shape(np.delete(Xtrain[0], [2] , 2))
Out[67]: (106, 106, 2)

1 个解决方案

#1


22  

You could use slice notation:

您可以使用切片表示法:

x = np.zeros( (106, 106, 3) )
result = x[:, :, 0]
print result.shape

prints

版画

(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 slice notation does).

形状(106,106,3)意味着你有3组具有形状的东西(106,106)。因此,为了“剥离”最后一个维度,您只需选择其中一个(这就是切片表示法所做的)。

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.

你可以保留任何你想要的切片。我随意选择保留第0个,因为你没有指定你想要的东西。因此,result = x [:,:,1]和result = x [:,:,2]也会得到所需的形状:它只取决于你需要保留的切片。

#1


22  

You could use slice notation:

您可以使用切片表示法:

x = np.zeros( (106, 106, 3) )
result = x[:, :, 0]
print result.shape

prints

版画

(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 slice notation does).

形状(106,106,3)意味着你有3组具有形状的东西(106,106)。因此,为了“剥离”最后一个维度,您只需选择其中一个(这就是切片表示法所做的)。

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.

你可以保留任何你想要的切片。我随意选择保留第0个,因为你没有指定你想要的东西。因此,result = x [:,:,1]和result = x [:,:,2]也会得到所需的形状:它只取决于你需要保留的切片。