在图像处理,尤其是医学图像处理的过程中,我们经常会遇到将灰度图映射成彩色图的情形,如将灰度图根据灰度的高低映射成彩虹色图。这个过程我们通常将之称为伪彩映射,伪彩映射的关键在于找到合适的彩色映射表,即colormap,也称color bar。
这里采用opencv的applyColorMap()函数生成热力图。可参考 :https://blog.csdn.net/weixin_36670529/article/details/104001820
cv2.applyColorMap(src, userColor[, dst])
热力图源码:
import cv2
import time
import os
import matplotlib.pyplot as plt
import torch
from torch import nn
import torchvision.models as models
import torchvision.transforms as transforms
import numpy as np
savepath='./vis/vis_resnet50_hot'
if not os.path.exists(savepath):
os.makedirs(savepath)
def draw_features(width, height, x, savename):
tic = time.time()
fig = plt.figure(figsize=(16, 16))
fig.subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95, wspace=0.05, hspace=0.05)
for i in range(width * height):
plt.subplot(height, width, i + 1)
plt.axis('off')
img = x[0, i, :, :]
pmin = np.min(img)
pmax = np.max(img)
img = ((img - pmin) / (pmax - pmin + 0.000001)) * 255 # float在[0,1]之间,转换成0-255
img = img.astype(np.uint8) # 转成unit8
img = cv2.applyColorMap(img, cv2.COLORMAP_JET) # 生成heat map
img = img[:, :, ::-1] # 注意cv2(BGR)和matplotlib(RGB)通道是相反的
plt.imshow(img)
print("{}/{}".format(i, width * height))
fig.savefig(savename, dpi=100)
fig.clf()
plt.close()
print("time:{}".format(time.time() - tic))
class ft_net(nn.Module):
def __init__(self):
super(ft_net, self).__init__()
model_ft = models.resnet50(pretrained=True)
self.model = model_ft
def forward(self, x):
if True: # draw features or not
x = self.model.conv1(x)
draw_features(8, 8, x.cpu().numpy(), "{}/f1_conv1.png".format(savepath))
x = self.model.bn1(x)
draw_features(8, 8, x.cpu().numpy(), "{}/f2_bn1.png".format(savepath))
x = se

该博客介绍了如何通过OpenCV的applyColorMap函数将医学图像的灰度图转换为彩色图,以进行特征可视化。具体展示了在ResNet50模型中,从卷积层到全连接层的每一层特征图的热力图,并提供了一个名为ft_net的类,用于绘制特征图。此外,还提供了将图像输入模型并进行预测的流程。
2552

被折叠的 条评论
为什么被折叠?



