问题描述
我有一些我想处理的图像,问题是有两种图像都是 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 数组中删除一个维度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!