【问题标题】:How to convert a greyscale image to RGB using custom color mapping?如何使用自定义颜色映射将灰度图像转换为 RGB?
【发布时间】:2021-10-08 08:50:38
【问题描述】:

我正在尝试使用自定义映射将灰度图像(表示为 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')

【问题讨论】:

    标签: python image python-imaging-library


    【解决方案1】:

    请务必在此处检查您的 dtypenp.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()
    

    【讨论】:

    猜你喜欢
    • 2014-09-17
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 2014-02-26
    • 2014-12-22
    • 2021-11-27
    • 2018-08-15
    相关资源
    最近更新 更多