【问题标题】:Non-linear scaling of a colormap to enhance contrast颜色图的非线性缩放以增强对比度
【发布时间】:2011-06-27 11:59:47
【问题描述】:

以下 python 代码创建包含正态分布值的矩阵的热图

import numpy as np
from matplotlib import pylab as plt


np.random.seed(123) #make sure we all have same data
m = np.random.randn(200).reshape(10, 20)
plt.imshow(m, cmap='RdYlGn', interpolation='nearest')
plt.colorbar()

这是这段代码的输出

我想通过“淡出”接近零的值来增强此图像的对比度。 我可以通过使用原始数据的二乙型缩放轻松做到这一点,如下所示:

def disigmoidScaling(values, steepnessFactor=1, ref=None):
    ''' Sigmoid scaling in which values around a reference point are flattened
    arround a reference point

    Scaled value y is calculated as 
        y = sign(v - d)(1 - exp(-((x - d)/s)**2)))
    where v is the original value,  d is the referenc point and s is the 
    steepness factor
    '''
    if ref is None:
        mn = np.min(values)
        mx = np.max(values)
        ref = mn + (mx - mn) / 2.0

    sgn = np.sign(values - ref)
    term1 = ((values - ref)/steepnessFactor) ** 2
    term2 = np.exp(- term1) 
    term3 = 1.0 - term2 
    return sgn * term3


plt.imshow(disigmoidScaling(m, 4), cmap='RdYlGn', interpolation='nearest')
plt.colorbar()

这是输出。

我对结果很满意,除了在这个版本中原来的 值已交换为按比例缩放的值。

有没有办法将值非线性映射到颜色图?

【问题讨论】:

标签: python matplotlib color-scheme color-mapping


【解决方案1】:

颜色图包含映射在区间 [0,1] 上的红色、绿色和蓝色值的字典。 Linear Segmented Colormap 类文档给出了示例

cdict = {'red':   [(0.0,  0.0, 0.0),
               (0.5,  1.0, 1.0),
               (1.0,  1.0, 1.0)],

     'green': [(0.0,  0.0, 0.0),
               (0.25, 0.0, 0.0),
               (0.75, 1.0, 1.0),
               (1.0,  1.0, 1.0)],

     'blue':  [(0.0,  0.0, 0.0),
               (0.5,  0.0, 0.0),
               (1.0,  1.0, 1.0)]}

"表中给定颜色的每一行是一个由 x,y0,y1 元组组成的序列。在每个序列中,x 必须从 0 到 1 单调递增。对于任何介于 x[i] 和 x 之间的输入值 z [i+1],给定颜色的输出值将在 y1[i] 和 y0[i+1] 之间进行线性插值:"

RdYlGn 颜色图有 11 个 x 值,每个颜色从 0 到 1.0,步长为 0.1。您可以通过调用

获取 cdict
plt.cm.RdYlGn._segmentdata

然后,您可以将 x 值更改为您想要的任何步长(只要它们单调递增并且范围从 0 到 1),并通过在新的 cdict 上调用 matplotlib.colors.LinearSegmentedColormap 来获得新的颜色图。 Matplotlib Cookbook 中有几个很好的例子。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-22
    • 2019-10-03
    • 2011-10-19
    相关资源
    最近更新 更多