图像顶部的热图

问题描述 投票:0回答:2

我有不同物体的图像(Pascal Voc),并且有概率热图。我想通过绘制图像并以某种方式在其顶部绘制热图来可视化它。最好的方法是什么?

我正在考虑像这样使用 alpha 通道:

im_heat = np.zeros((image.shape[0],image.shape[1],4))
im_heat[:,:,:3] = image
im_heat[:,:,3] = np.rint(255/heatmap)
plt.imshow(im_heat, cmap='jet')
plt.colorbar()

如何将颜色条自定义为从最小(热图)到最大(热图)? 或者有没有更好的方法来可视化概率?

python matplotlib visualization colorbar colormap
2个回答
25
投票

您可以使用 matplotlib 堆叠图像和绘图,然后选择用于颜色条的句柄。使用

contourf
颜色条最小值和最大值将基于您的热图(或者您可以将
vmin=min(heatmap)
vmax=max(heatmap)
传递给轮廓f 以明确此范围)。这样做的问题是热图将覆盖您的图像(设置透明度将使整个图像透明)。最好的选择是制作一个在接近零时透明的颜色图,如下所示,

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
import Image

#2D Gaussian function
def twoD_Gaussian((x, y), xo, yo, sigma_x, sigma_y):
    a = 1./(2*sigma_x**2) + 1./(2*sigma_y**2)
    c = 1./(2*sigma_x**2) + 1./(2*sigma_y**2)
    g = np.exp( - (a*((x-xo)**2) + c*((y-yo)**2)))
    return g.ravel()


def transparent_cmap(cmap, N=255):
    "Copy colormap and set alpha values"

    mycmap = cmap
    mycmap._init()
    mycmap._lut[:,-1] = np.linspace(0, 0.8, N+4)
    return mycmap


#Use base cmap to create transparent
mycmap = transparent_cmap(plt.cm.Reds)


# Import image and get x and y extents
I = Image.open('./deerback.jpg')
p = np.asarray(I).astype('float')
w, h = I.size
y, x = np.mgrid[0:h, 0:w]

#Plot image and overlay colormap
fig, ax = plt.subplots(1, 1)
ax.imshow(I)
Gauss = twoD_Gaussian((x, y), .5*x.max(), .4*y.max(), .1*x.max(), .1*y.max())
cb = ax.contourf(x, y, Gauss.reshape(x.shape[0], y.shape[1]), 15, cmap=mycmap)
plt.colorbar(cb)
plt.show()

这给出了,

enter image description here


0
投票

如果您正在寻找 Ed Smith 代码的 Python3 版本

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from PIL import Image

#2D Gaussian function
def twoD_Gaussian(x,y, xo, yo, sigma_x, sigma_y):
    a = 1./(2*sigma_x**2) + 1./(2*sigma_y**2)
    c = 1./(2*sigma_x**2) + 1./(2*sigma_y**2)
    g = np.exp( - (a*((x-xo)**2) + c*((y-yo)**2)))
    return g.ravel()


def transparent_cmap(cmap, N=255):
    "Copy colormap and set alpha values"

    mycmap = cmap
    mycmap._init()
    mycmap._lut[:,-1] = np.linspace(0, 0.8, N+4)
    return mycmap


#Use base cmap to create transparent
mycmap = transparent_cmap(plt.cm.Reds)


# Import image and get x and y extents
I = Image.open('./deerback.jpg')
p = np.asarray(I).astype('float')
w, h = I.size
y, x = np.mgrid[0:h, 0:w]

#Plot image and overlay colormap
fig, ax = plt.subplots(1, 1)
ax.imshow(I)
Gauss = twoD_Gaussian(x, y, .5*x.max(), .4*y.max(), .1*x.max(), .1*y.max())
cb = ax.contourf(x, y, Gauss.reshape(x.shape[0], y.shape[1]), 15, cmap=mycmap)
plt.colorbar(cb)
plt.show()
© www.soinside.com 2019 - 2024. All rights reserved.