python - 如何扩展和填充黑白图像的第三个暗淡
问题描述
我有一个(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)
解决方案
当我们使用 时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)
推荐阅读
- python - 扩展/附加 python 连接列表
- unit-testing - 如何在 bloc 单元测试中模拟连接性?
- ethereum - 如何正确地将 uint256 数字从前端传递给智能合约?
- android - 有没有更好的方法在 Coroutines 中设置一个 Listener n 次?
- python - 为什么django找不到网址?
- gnome-shell-extensions - 如何在 gnome 扩展中更改 PopupSwitchMenuItem 的状态
- javascript - react中点击modal的Cancel链接时如何防止onBlur触发?
- amazon-web-services - 通过 terraform 创建 API 网关域名时出错
- sql - sql中的oracle'ora-01843'日期格式错误
- bots - 欢迎 Bot 由于“无法读取未定义的属性‘查找’而无法工作”