如何绘制对数归一化的imshow图,并用颜色条表示原始数据
我正在使用matplotlib来绘制对数归一化的图像,但我希望在颜色条上显示原始的原始图像数据,而不是[0-1]的范围。我感觉有一种更符合matplotlib风格的方法,可以使用某种归一化对象,而不是提前转换数据……无论如何,原始图像中可能会有负值。
import matplotlib.pyplot as plt
import numpy as np
def log_transform(im):
'''returns log(image) scaled to the interval [0,1]'''
try:
(min, max) = (im[im > 0].min(), im.max())
if (max > min) and (max > 0):
return (np.log(im.clip(min, max)) - np.log(min)) / (np.log(max) - np.log(min))
except:
pass
return im
a = np.ones((100,100))
for i in range(100): a[i] = i
f = plt.figure()
ax = f.add_subplot(111)
res = ax.imshow(log_transform(a))
# the colorbar drawn shows [0-1], but I want to see [0-99]
cb = f.colorbar(res)
我尝试过使用cb.set_array,但似乎没有任何效果,还有cb.set_clim,但那样会完全重新调整颜色。
2 个回答
8
如果你只是想让图像进行对数归一化(这样可以增强细节),但不想改变数据本身(以保持物理值),那么你需要在颜色映射上进行这个转换。你可以使用一个叫做cmap_map()的函数,这个函数在食谱里有介绍:
https://scipy-cookbook.readthedocs.io/items/Matplotlib_ColormapTransformations.html75
当然有办法!你可以使用 LogNorm
。下面是我写的一个小工具中的代码片段,用来在对数尺度上显示混淆矩阵。
from pylab import figure, cm
from matplotlib.colors import LogNorm
# C = some matrix
f = figure(figsize=(6.2, 5.6))
ax = f.add_axes([0.17, 0.02, 0.72, 0.79])
axcolor = f.add_axes([0.90, 0.02, 0.03, 0.79])
im = ax.matshow(C, cmap=cm.gray_r, norm=LogNorm(vmin=0.01, vmax=1))
t = [0.01, 0.1, 0.2, 0.4, 0.6, 0.8, 1.0]
f.colorbar(im, cax=axcolor, ticks=t, format="$%.2f$")
f.show()