注意:本贴主要来自网络搜集,自己做了一些修改,原作者链接:https://blog.youkuaiyun.com/guduruyu/article/details/60868501
热力图(Heat_Map)示意图
热力图可以高亮显示所关注区域中的数据所占比重情况,红色是占比最高,蓝色是占比最低。热力图以其好看、易于理解的可视化格式在CNN网络中广泛被用来分析特征分布情况。
彩色映射
如上图所示,上图按照灰度的高低将灰度图映射成彩色图,这个过程称为伪彩色映射表,即colormap,或color bar。
- 内嵌的colormaps
python的matplotlib模块内嵌了很多常用的colormaps,将colormaps绘制的代码如下所示:
import numpy as np
import matplotlib.pyplot as plt
# Have colormaps separated into categories:
# http://matplotlib.org/examples/color/colormaps_reference.html
cmaps = [('Perceptually Uniform Sequential',
['viridis', 'inferno', 'plasma', 'magma']),
('Sequential', ['Blues', 'BuGn', 'BuPu',
'GnBu', 'Greens', 'Greys', 'Oranges', 'OrRd',
'PuBu', 'PuBuGn', 'PuRd', 'Purples', 'RdPu',
'Reds', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd']),
('Sequential (2)', ['afmhot', 'autumn', 'bone', 'cool',
'copper', 'gist_heat', 'gray', 'hot',
'pink', 'spring', 'summer', 'winter']),
('Diverging', ['BrBG', 'bwr', 'coolwarm', 'PiYG', 'PRGn', 'PuOr',
'RdBu', 'RdGy', 'RdYlBu', 'RdYlGn', 'Spectral',
'seismic']),
('Qualitative', ['Accent', 'Dark2', 'Paired', 'Pastel1',
'Pastel2', 'Set1', 'Set2', 'Set3']),
('Miscellaneous', ['gist_earth', 'terrain', 'ocean', 'gist_stern',
'brg', 'CMRmap', 'cubehelix',
'gnuplot', 'gnuplot2', 'gist_ncar',
'nipy_spectral', 'jet', 'rainbow',
'gist_rainbow', 'hsv', 'flag', 'prism'])]
nrows = max(len(cmap_list) for cmap_category, cmap_list in cmaps)
gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))
def plot_color_gradients(cmap_category, cmap_list):
fig, axes = plt.subplots(nrows=nrows)
fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99)
axes[0].set_title(cmap_category + ' colormaps', fontsize=14)
for ax, name in zip(axes, cmap_list):
ax.imshow(gradient, aspect='auto', cmap=plt.get_cmap(name))
pos = list(ax.get_position().bounds)
x_text = pos[0] - 0.01
y_text = pos[1] + pos[3]/2.
fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)
# Turn off *all* ticks & spines, not just the ones with colormaps.
for ax in axes:
ax.set_axis_off()
for cmap_category, cmap_list in cmaps:
plot_color_gradients(cmap_category, cmap_list)
plt.show()
输出结果如下所示:
2. 获取colormap
以获取最常用的jet映射表为例,我们可以使用如下代码分别获取整型和浮点型的jet map,并将其保存在txt文件中:
import numpy as np
from matplotlib import cm
# 获取cmp彩色映射图
def get_jet():
colormap_int = np.zeros((256, 3), np.uint8)
colormap_float = np.zeros((256, 3), np.float)
for i in range(0, 256, 1):
colormap_float[i, 0] = cm.jet(i)[0]
colormap_float[i, 1] = cm.jet(i)[1]
colormap_float[i, 2] = cm.jet(i)[2]
colormap_int[i, 0] = np.int_(np.round(cm.jet(i)[0] * 255.0))
colormap_int[i, 1] = np.int_(np.round(cm.jet(i)[1] * 255.0))
colormap_int[i, 2] = np.int_(np.round(cm.jet(i)[2] * 255.0))
np.savetxt("jet_float.txt", colormap_float, fmt = "%f", delimiter = ' ', newline = '\n')
np.savetxt("jet_int.txt", colormap_int, fmt = "%d", delimiter = ' ', newline = '\n')
print(colormap_int)
return
if __name__ == "__main__":
get_jet()
获取其他种类的colormap与之类似:
def get_spectral():
colormap_int = np.zeros((256, 3), np.uint8)
colormap_float = np.zeros((256, 3), np.float)
for i in range(0, 256, 1):
colormap_float[i, 0] = cm.spectral(i)[0]
colormap_float[i, 1] = cm.spectral(i)[1]
colormap_float[i, 2] = cm.spectral(i)[2]
colormap_int[i, 0] = np.int_(np.round(cm.spectral(i)[0] * 255.0))
colormap_int[i, 1] = np.int_(np.round(cm.spectral(i)[1] * 255.0))
colormap_int[i, 2] = np.int_(np.round(cm.spectral(i)[2] * 255.0))
np.savetxt("spectral_float.txt", colormap_float, fmt = "%f", delimiter = ' ', newline = '\n')
np.savetxt("spectral_int.txt", colormap_int, fmt = "%d", delimiter = ' ', newline = '\n')
print(colormap_int)
return
3. 伪彩映射示例
from matplotlib import cm
import matplotlib.pyplot as plt
import numpy as np
import cv2
# 将所绘制图映射到热力图
def gray2color(gray_array, color_map):
'''
:param gray_array: 必须为二维numpy_narray矩阵
:param color_map: 保存的cmp彩色映射图
:return: 返回映射后的热力图(heat_map)
'''
rows, cols = gray_array.shape
color_array = np.zeros((rows, cols, 3), np.uint8)
for i in range(0, rows):
for j in range(0, cols):
color_array[i, j] = color_map[gray_array[i, j]]
# color_image = Image.fromarray(color_array)
return color_array
# the path of jet_map
jet_map = np.loadtxt('/home/alfred/fromlinux/objectTracking/code/NoOfficialCode/SiamRPN-PyTorch_36_star/jet_int.txt', dtype=np.int)
# numpy narray
picture = cv2.imread('/home/alfred/fromlinux/objectTracking/code/NoOfficialCode/SiamRPN-PyTorch_36_star/0020.jpg') # cv2.imread读入的图片已经是numpy narray形式
gray_picture = cv2.cvtColor(picture, cv2.COLOR_RGB2GRAY) # 转换成灰度图
# get the heat_map
gray_to_color = gray2color(gray_picture, jet_map)
# draw picture
plt.figure()
plt.subplot(121)
plt.imshow(gray_picture, cmap='gray')
plt.subplot(122)
plt.imshow(gray_to_color)
plt.show()
示例结果: