首页 > 解决方案 > 使用字典将二维数组转换为 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 图像(在这种情况下非常小,但无论如何都是图像),它是基于字典分配给每个值的颜色的矩阵的反射。

我可以使用循环来做到这一点,这是我的第一直觉。但是有没有更蟒蛇的方式来做到这一点?

标签: pythonimagenumpy

解决方案


在这种情况下,我看到两个选项:

选项 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:索引颜色

一些图像格式支持索引颜色

在此处输入图像描述

颜色图将每个值与特定颜色相关联。因此,使用其中一种格式将直接解决您的问题。


推荐阅读