python - 使用字典将二维数组转换为 RGB 图像的 Pythonic 方法
问题描述
假设我有一个二维矩阵
[[80 80 80]
[ 0 50 0]
[ 0 0 50]
[ 0 50 0]
[ 30 30 30]]
我有一本字典
color_dict = {
80: (255,255,0),
50: (255,0,0),
30: (0,0,255)
}
我想得到一个 BGR 图像(在这种情况下非常小,但无论如何都是图像),它是基于字典分配给每个值的颜色的矩阵的反射。
我可以使用循环来做到这一点,这是我的第一直觉。但是有没有更蟒蛇的方式来做到这一点?
解决方案
在这种情况下,我看到两个选项:
选项 1:Numpy 索引
# First of all you need to map your random values to a continuous discrete range:
# 0 -> 0, 30 -> 1, 50 -> 2, 80 -> 3, for this you can use basic indexing.
# Now we have an array containing the position of each pixel and his corresponding value
img = np.array([[0,1,2],
[2,1,0]])
# And another array containing the colormap for each value
val = np.array([[255,255,0], # -> 0
[255,0,100], # -> 1
[100,0,0]]) # -> 2
# If we index the second array with the first one we obtain a new 3D array, the final image:
res = val.T[:,img]
看起来像这样:
array([[[250, 255, 100],
[100, 255, 250]],
[[250, 0, 0],
[ 0, 0, 250]],
[[ 0, 100, 0],
[ 0, 100, 0]]])
选项 2:索引颜色
一些图像格式支持索引颜色:
颜色图将每个值与特定颜色相关联。因此,使用其中一种格式将直接解决您的问题。
推荐阅读
- ubuntu - 将 setcap 设置为 no-root 捕获的 Wireshark dumpcap 无法在 Ubuntu 18.10 中启动
- docker - 具有确定性端口绑定的 Docker 规模
- vb.net - 当我单击一个按钮时,在运行时将新语法附加到语音识别
- django - AttributeError:“经理”对象没有属性“all_with_related_persons_and_score”
- vb.net - 文本框边框为蓝色时为空然后边框颜色为红色 vb.net
- react-native - 当我按下返回按钮(从堆栈标题)或从左向右滑动时,ios 应用程序崩溃
- vue.js - Vuetify 数据表不会在状态更新时重新加载
- css - postcss-loader 是否需要通过 webpack 将 sass 转换为 css?
- c# - 如何在 .Select 中填充一个额外的属性 - LINQ
- elasticsearch - ES 7 - 使用匹配查询和过滤器