看了网上好多说这个注意力图可视化的代码,但是我都没整出来我想要的结果。然后参考着自己整了一个。

下面简单附代码,根据个人情况去修改:

def resize(img):
    img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
    cur_ratio = img.shape[1] / float(img.shape[0])
    target_ratio = 128 / float(32)
    mask_h = 32
    mask_w = 128
    img = np.array(img)
    if cur_ratio > target_ratio:
        cur_h = 32
        cur_w = 128
    else:
        cur_h = 32
        cur_w = int(32 * cur_ratio)
    img = cv2.resize(img, (cur_w, cur_h))
    start_y = (mask_h - img.shape[0]) // 2
    start_x = (mask_w - img.shape[1]) // 2
    mask = np.zeros([mask_h, mask_w, 3]).astype(np.uint8)
    mask[start_y: start_y + img.shape[0], start_x: start_x + img.shape[1], :] = img
    return mask

img = skimage.io.imread(os.path.join(img_path, img_name))
img_new = resize(img)
amap = cv2.cvtColor(skimage.io.imread(os.path.join(path, att_map)), cv2.COLOR_RGB2BGR)
new_map = cv2.resize(amap, (img_new.shape[1], img_new.shape[0]))
normed_mask = new_map / np.max(new_map)
normed_mask = np.uint8(255 * normed_mask)
normed_mask = cv2.applyColorMap(normed_mask, cv2.COLORMAP_JET)
normed_mask = cv2.addWeighted(img_new, 0.6, normed_mask, 1.0, 0)
skimage.io.imsave(os.path.join(res_dir, m), cv2.cvtColor(normed_mask, cv2.COLOR_BGR2RGB))

    这个att_map就是你的算法模型得到的注意力图,这个图中每个值在0,1之间,可能和图像的h,w不一样,所以代码里进行了cv2.resize。如果你得到的注意力图为[h,w,c]就在c维度取个均值,变成[h,w,1]然后再把1这个维度用numpy中squeeze()给去掉。

下面是我得到的结果:
在这里插入图片描述

对大家有帮助的,欢迎点赞收藏!

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐