首页 > 解决方案 > 如何扩展和填充黑白图像的第三个暗淡

问题描述

我有一个(224,224)形状的黑白图像,但我想要(224,224,3),所以我需要扩大暗淡,但不是空值,所以np.expand_dims还是np.atleast_3d帮不了我。我怎样才能正确地做到这一点?谢谢。

我用什么:

from PIL import Image
img = Image.open('data/'+link)
rsize = img.resize((224,224))
rsizeArr = np.asarray(rsize)

标签: pythonnumpycomputer-visionpython-imaging-libraryrgb

解决方案


当我们使用 时numpy.dstack(),我们不必手动扩展维度,它会处理这项工作并将其沿第三轴堆叠,这正是我们想要的。

In [4]: grayscale = np.random.random_sample((224,224))

# make it RGB by stacking the grayscale image along depth dimension 3 times
In [5]: rgb = np.dstack([grayscale]*3)

In [6]: rgb.shape
Out[6]: (224, 224, 3)

对于您的具体情况,它应该是:

rsize_rgb = np.dstack([rsize]*3)

无论出于何种原因,如果您仍想将灰度图像的尺寸扩大1,然后使其成为 RGB 图像,那么您可以使用numpy.concatenate()如下:

In [9]: rgb = np.concatenate([grayscale[..., np.newaxis]]*3, axis=2)
In [10]: rgb.shape
Out[10]: (224, 224, 3)

对于您的具体情况,它将是:

rsize_rgb = np.concatenate([rsize[..., np.newaxis]]*3, axis=2)

推荐阅读