在图像处理中,伪色彩用途广泛。OpenCV的定义12种colormap(色度图),可以应用于灰度图像(即单通道),使用函数applycolormap产生伪彩色图像。
即我们画图的时候,得到的attention map一般是单通道的,这样用plt.imshow()可以画,但是用cv2就不行了, 它要求3通道的。用cv2.applyColorMap()可以合理转化成3通道
cv2.applyColorMap(src, userColor[, dst])
例如伪色彩中的
COLORMAP_JET模式
,就常被用于生成我们所常见的 热力图:
import cv2 # COLORMAP_AUTUMN = 0, # COLORMAP_BONE = 1, # COLORMAP_JET = 2, # COLORMAP_WINTER = 3, # COLORMAP_RAINBOW = 4, # COLORMAP_OCEAN = 5, # COLORMAP_SUMMER = 6, # COLORMAP_SPRING = 7, # COLORMAP_COOL = 8, # COLORMAP_HSV = 9, # COLORMAP_PINK = 10, # COLORMAP_HOT = 11 img = cv2.imread("wave.jpg") for i in range(0, 13): im_color = cv2.applyColorMap(img, i) cv2.imwrite("wave_{}.jpg".format(i), im_color)
import matplotlib.cm as mpl_color_map import cv2 import numpy as np import matplotlib.pyplot as plt import torch, copy, os from torchvision import transforms from PIL import Image #code is from https://github.com/innovation-cat/pytorch_cnn_visualization_implementations/blob/master/utils.py def apply_colormap_on_image(org_im, activation, colormap_name): """ Apply heatmap on image Args: org_img (PIL img): Original image activation_map (numpy arr): Activation map (grayscale) 0-255 colormap_name (str): Name of the colormap """ # Get colormap color_map = mpl_color_map.get_cmap(colormap_name) no_trans_heatmap = color_map(activation) # Change alpha channel in colormap to make sure original image is displayed heatmap = copy.copy(no_trans_heatmap) heatmap[:, :, 3] = 0.4 heatmap = Image.fromarray((heatmap*255).astype(np.uint8)) no_trans_heatmap = Image.fromarray((no_trans_heatmap*255).astype(np.uint8)) # Apply heatmap on iamge heatmap_on_image = Image.new("RGBA", org_im.size) heatmap_on_image = Image.alpha_composite(heatmap_on_image, org_im.convert('RGBA')) #heatmap = heatmap.transpose(method=Image.TRANSVERSE) print(heatmap_on_image) print(heatmap) heatmap_on_image = Image.alpha_composite(heatmap_on_image, heatmap) return no_trans_heatmap, heatmap_on_image
Python opencv cv2.applyColorMap 伪色彩函数
于 2022-01-12 15:48:15 首次发布