如何扩展和填充黑白图像的第三维度

2024-06-16 10:08:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个(224224224)形状的黑白图像,但我想要(224224224,3),所以我需要扩展dim,但不能使用空值,所以np.expand_dimsnp.atleast_3d帮不了我。如何正确地执行此操作?谢谢。你知道吗

我使用的是:

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

Tags: from图像imageimportimgpilnpopen
1条回答
网友
1楼 · 发布于 2024-06-16 10:08:37

当我们使用^{}时,我们不必手动扩展维度,它将处理该工作,并沿着第三个轴(这是我们想要的)堆叠它。你知道吗

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图像,则可以使用^{},如中所示:

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)

相关问题 更多 >