You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何创建LinearSegmentedColormap并将其应用于图像

自定义LinearSegmentedColormap并应用到图像的实现方案

原代码问题说明

  • colorMapPlasma函数无需传入red/green/blue参数,颜色映射的cdict是固定的渐变规则定义,和图像数据无关
  • 调用函数时传入的lum_img[1],lum_img[2],lum_img[3]是图像行数据,属于错误传参,完全没必要

修正后的完整实现代码

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from matplotlib.colors import LinearSegmentedColormap

# 读取灰度图像
mars_gray = mpimg.imread('img.png')
# 提取单通道灰度数据(适配RGB/RGBA格式图像)
lum_img = mars_gray[:, :, 0]
# 将灰度值归一化到0-1范围(颜色映射要求输入值在此区间)
normalized_lum_img = lum_img / 255.0 if lum_img.max() > 1 else lum_img

# 定义自定义颜色映射规则
def get_custom_cdict():
    cdict = {
        'red': [
            (0.0,  0.0, 0.0),
            (0.2,  0.0, 0.14),
            (0.75, 1.0, 1.0),
            (1.0,  0.7, 0.7)
        ],
        'green': [
            (0.0,  0.0, 0.14),
            (0.24, 0.14, 0.24),
            (0.3,  0.7, 0.7),
            (0.4,  0.3, 0.0),
            (1.0,  0.0, 0.0)
        ],
        'blue': [
            (0.0,  1.0, 1.0),
            (0.28, 0.0, 0.0),
            (1.0,  0.0, 0.0)
        ]
    }
    return cdict

# 创建自定义LinearSegmentedColormap对象
cdict = get_custom_cdict()
custom_cmap = LinearSegmentedColormap('my_custom_cmap', cdict)

# 应用颜色映射,生成带颜色的numpy数组
colored_img = custom_cmap(normalized_lum_img)
# 若不需要alpha通道,保留前3个RGB通道
colored_img_rgb = colored_img[:, :, :3]

# 可视化对比结果
plt.figure(figsize=(10, 5))
plt.subplot(121)
plt.imshow(lum_img, cmap='gray')
plt.title('原始灰度图像')
plt.subplot(122)
plt.imshow(colored_img_rgb)
plt.title('应用自定义颜色映射后的图像')
plt.show()

# 输出颜色数组信息
print("带颜色的图像数组形状:", colored_img_rgb.shape)
print("左上角像素的RGB值:", colored_img_rgb[0, 0])

关键步骤解释

  1. 图像归一化:颜色映射要求输入值在0-1区间,若原始灰度图是0-255的整数格式,需除以255.0转换为浮点数
  2. 自定义颜色映射创建:通过LinearSegmentedColormap类,传入自定义的渐变规则cdict和映射名称,生成可复用的颜色映射对象
  3. 映射应用与数组生成:调用颜色映射对象并传入归一化灰度数组,会返回RGBA格式的三维数组;如需纯RGB格式,截取前3个通道即可
  4. 结果输出:colored_img_rgb就是最终的带颜色numpy数组,可直接用于后续数据处理

内容的提问来源于stack exchange,提问作者PythonNewbie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 04:07:16