gpt4 book ai didi

python - 颜色图的非线性缩放以增强对比度

转载 作者:太空狗 更新时间:2023-10-29 21:07:46 25 4
gpt4 key购买 nike

以下 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()

这是这段代码的输出

example 1

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

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()

这是输出。

example 2

我对结果很满意,除了这个版本中的原始版本值已换成缩放值。

有没有一种方法可以将值非线性映射到颜色图?

最佳答案

颜色图包含在区间 [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)并通过调用 matplotlib.colors.LinearSegmentedColormap你的新 cdictMatplotlib Cookbook 中有几个很好的例子.

关于python - 颜色图的非线性缩放以增强对比度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6492514/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com