如何使用自定义颜色映射将灰度图像转换为 RGB?

How to convert a greyscale image to RGB using custom color mapping?

我正在尝试使用自定义映射将灰度图像(表示为 NumPy 数组)转换为 RGB 图像。示例自定义贴图为:如果像素(数组)值为负 RGB =(0,0,0) 并且如果数组值介于 0 和 0.1 之间,则 RGB=(247, 251, 255)。请参阅下文了解我的初步尝试。该代码生成空白图像(无法对 RGB 值进行编码)。你能帮我理解我哪里出错了吗?另外,在灰度到 RGB 转换过程中,有没有更好的方法来实现自定义颜色映射?

import numpy as np
# Creating a synthentic image
arr = np.random.rand(7279, 15078)

# The range is defined by (start_value, end_value]
# key: [start_value, end_value, RGB Value]
color_map = {0: [-1e100, 0.0, 0, 0, 0],
             1: [0.0, 0.1, 247, 251, 255],
             2: [0.1, 0.2, 222, 235, 247],
             3: [0.2, 0.5, 198, 219, 239],
             4: [0.5, 1.0, 158, 202, 225],
             5: [1.0, 1.5, 107, 174, 214],
             6: [1.5, 2.0, 66, 146, 198],
             7: [2.0, 4.0, 33, 113, 181],
             8: [4.0, 1e100, 8, 69, 148]}

rgb_img = np.zeros((*arr.shape, 3))
for key in color_map.keys():
    start, end, *_rgb = color_map[key]
    boolean_array = np.logical_and(arr > start, arr <= end)
    rgb_img[boolean_array] = _rgb

from PIL import Image
Image.fromarray(rgb_img, 'RGB')

请务必在此处检查您的 dtype 是否为 np.uint8

rgb_img = np.zeros((*arr.shape, 3), dtype=np.uint8)

所以,它可能看起来像这样:

#!/usr/bin/env python3

import numpy as np
from PIL import Image

# Creating a synthetic image
arr = np.random.rand(480, 640)

# The range is defined by (start_value, end_value]
# key: [start_value, end_value, RGB Value]
color_map = {0: [-1e100, 0.0, 0, 0, 0],
             1: [0.0, 0.3, 255, 0, 0],
             2: [0.3, 0.6, 0, 255, 0],
             3: [0.6, 0.9, 0, 0, 255],
             4: [0.9, 1e100, 255, 255, 255]}

rgb_img = np.zeros((*arr.shape, 3), np.uint8)
for key in color_map.keys():
    start, end, *_rgb = color_map[key]
    boolean_array = np.logical_and(arr > start, arr <= end)
    rgb_img[boolean_array] = _rgb

res=Image.fromarray(rgb_img, 'RGB')
res.show()