1.YOLOv5 特征图可视化

可视化代码:

def feature_visualization(x, module_type, stage, n=2, save_dir=Path('runs/detect/exp')):"""x:              Features to be visualizedmodule_type:    Module typestage:          Module stage within modeln:              Maximum number of feature maps to plotsave_dir:       Directory to save results"""if 'Detect' not in module_type:batch, channels, height, width = x.shape  # batch, channels, height, widthif height > 1 and width > 1:f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png"  # filenameblocks = torch.chunk(x[0].cpu(), channels, dim=0)  # select batch index 0, block by channelsn = min(n, channels)  # number of plotsfig, ax = plt.subplots(math.ceil(n / 2), 2, tight_layout=True)  # 8 rows x n/8 colsax = ax.ravel()plt.subplots_adjust(wspace=0.05, hspace=0.05)for i in range(n):ax[i].imshow(blocks[i].squeeze())  # cmap='gray'ax[i].axis('off')LOGGER.info(f'Saving {f}... ({n}/{channels})')plt.savefig(f, dpi=300, bbox_inches='tight')plt.close()np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy())  # npy save

使用:

feature_visualization(features, name, stage_id, save_dir=ROOT / "visual")

结果示例:

2.优化的特征图可视化

可视化代码:

def feature_visualization(x, module_type, stage, n=2, save_dir=Path('runs/detect/exp')):"""x:              Features to be visualizedmodule_type:    Module typestage:          Module stage within modeln:              Maximum number of feature maps to plotsave_dir:       Directory to save results"""if 'Detect' not in module_type:batch, channels, height, width = x.shape  # batch, channels, height, widthif height > 1 and width > 1:f = save_dir / f"stage{stage}_{module_type.split('.')[-1]}_features.png"  # filenameblocks = torch.chunk(x[0].cpu(), channels, dim=0)  # select batch index 0, block by channelsn = min(n, channels)  # number of plotsfig, ax = plt.subplots(math.ceil(n / 2), 2, tight_layout=True)  # 8 rows x n/8 colsax = ax.ravel()plt.subplots_adjust(wspace=0.05, hspace=0.05)for i in range(n):block = blocks[i].squeeze().detach().numpy()block = (block - np.min(block)) / (np.max(block) - np.min(block))temp = np.array(block * 255.0, dtype=np.uint8)temp = cv2.applyColorMap(temp, cv2.COLORMAP_JET)ax[i].imshow(temp, cmap=plt.cm.jet)  # cmap='gray'ax[i].axis('off')LOGGER.info(f'Saving {f}... ({n}/{channels})')plt.savefig(f, dpi=300, bbox_inches='tight')plt.close()np.save(str(f.with_suffix('.npy')), x[0].cpu().numpy())  # npy save

使用:

feature_visualization(features, name, stage_id, save_dir=ROOT / "visual")

结果示例:

优化的可视化代码可视化结果更加清晰

参考:GitHub - z1069614715/objectdetection_script: 一些关于目标检测的脚本的改进思路代码,详细请看readme.md

3.注意力图可视化(YOLO)

可视化代码:

def show_CAM(save_img_path, image, feature_maps, class_id, all_ids=97, image_size=(640, 640), normalization=True):"""save_img_path: save heatmap images pathfeature_maps: this is a list [tensor,tensor,tensor], tensor shape is [1, 3, N, N, all_ids]normalization: Normalize score and class to 0 to 1image_size: w, h"""SHOW_NAME = ["score", "class", "class*score"]img_ori = imagelayers0 = feature_maps[0].reshape([-1, all_ids])layers1 = feature_maps[1].reshape([-1, all_ids])layers2 = feature_maps[2].reshape([-1, all_ids])layers = torch.cat([layers0, layers1, layers2], 0)if normalization:score_max_v = 1.score_min_v = 0.class_max_v = 1.class_min_v = 0.else:score_max_v = layers[:, 4].max()  # compute max of score from all anchorscore_min_v = layers[:, 4].min()  # compute min of score from all anchorclass_max_v = layers[:, 5 + class_id].max()  # compute max of class from all anchorclass_min_v = layers[:, 5 + class_id].min()  # compute min of class from all anchorfor j in range(3):  # layerslayer_one = feature_maps[j]# compute max of score from three anchor of the layerif normalization:anchors_score_max = layer_one[0, :, :, :, 4].max(0)[0].sigmoid()# compute max of class from three anchor of the layeranchors_class_max = layer_one[0, :, :, :, 5 + class_id].max(0)[0].sigmoid()else:anchors_score_max = layer_one[0, :, :, :, 4].max(0)[0]# compute max of class from three anchor of the layeranchors_class_max = layer_one[0, :, :, :, 5 + class_id].max(0)[0]scores = ((anchors_score_max - score_min_v) / (score_max_v - score_min_v))classes = ((anchors_class_max - class_min_v) / (class_max_v - class_min_v))layer_one_list = []layer_one_list.append(scores)layer_one_list.append(classes)layer_one_list.append(scores * classes)for idx, one in enumerate(layer_one_list):layer_one = one.cpu().numpy()if normalization:ret = ((layer_one - layer_one.min()) / (layer_one.max() - layer_one.min())) * 255else:ret = ((layer_one - 0.) / (1. - 0.)) * 255ret = ret.astype(np.uint8)gray = ret[:, :, None]ret = cv2.applyColorMap(gray, cv2.COLORMAP_JET)ret = cv2.resize(ret, image_size)img_ori = cv2.resize(img_ori, image_size)show = ret * 0.50 + img_ori * 0.50show = show.astype(np.uint8)cv2.imwrite(os.path.join(save_img_path, f"{j}_{SHOW_NAME[idx]}.jpg"), show)

使用:

show_CAM(ROOT/"visual",cv2.imread(path),ret[1],0,  # 指的是你想查看的类别 这个代码中我们看的是bear 所有在coco数据集中是2180+ 5,  # 80+5指的是coco数据集的80个类别+ x y w h score 5个数值image_size=(640, 640),  # 模型输入尺寸# 如果为True将置信度和class归一化到0~1,方便按置信度进行区分热力图,# 如果为False会按本身数据分布归一化,这样方便查看相对置信度。normalization=True)

结果示例:

参考:GitHub - z1069614715/objectdetection_script: 一些关于目标检测的脚本的改进思路代码,详细请看readme.md

计算机视觉特征图可视化与注意力图可视化(持续更新)相关推荐

  1. 【全年汇总】2023年CCF计算机图形学与多媒体会议截稿时间汇总(持续更新)

    本博文是根据2022年CCF会议推荐的计算机图形学与多媒体领域相关会议目录撰写,更多信息详见公众号CS Conference内容.(完整PDF大家搜集好了,公众号后台回复"CCF" ...

  2. 【GIS数据网盘免费分享】含77个城市建筑轮廓矢量图、POI数据,OSM数据~持续更新,长期有效

    本文数据均是GIS相关的数据.文档.课程等 戳下方链接进Q群,即可群文件下载,长期有效,持续更新 GISer开发学习交流+资料共享​www.wjx.cn/vj/h4QOnjk.aspx正在上传-重新上 ...

  3. 图新地球(LSV)常见问题汇总(图源、全景、倾斜摄影、点云应用、图新地球模糊等等)------持续更新

    0序: 不同业务模式下使用图新地球的逻辑完全不一样,这里对于遇到的问题以及解决方案进行汇总,仅供参考. 00高频,如何下载数据,下载的数据有黑块 00.1原理说明: 所谓地图数据下载,就是把应做成切片 ...

  4. 雷达 距离-方位(RA)图目标检测 一些笔记(持续更新)

    目录 距离方位角大致测量过程 射频数据的特性(对于目标检测而言) 一些要素 最近在看RODNet,顺便记录一下上面提到的有关雷达的玩意儿. 距离方位角大致测量过程 Chirp信号 -> 目标 - ...

  5. halcon Bit图位像素处理算子,持续更新

    目录 bit_and bit_lshift bit_mask bit_not bit_or bit_rshift bit_slice bit_xor bit_and 功能:输入图像的所有像素的逐位与. ...

  6. 两万文字多图详解常用软件工具使用(持续更新)

    文章目录 1. 写在前面的话 2. 实用工具 2.1 Chrome 2.1.1 屏蔽百度的个性推荐页 2.1.2 Chrome双开 2.1.3 视频加速 2.1.4 设置代理模式 2.1.5 将UA设 ...

  7. Python使用matplotlib可视化多个不同颜色的折线图、通过FontProperties为可视化图像配置中文字体可视化、并指定字体大小

    Python使用matplotlib可视化多个不同颜色的折线图.通过FontProperties为可视化图像配置中文字体可视化.并指定字体大小 目录

  8. R语言使用DALEX包的model_performance函数对caret包生成的多个算法模型进行残差分布分析并使用箱图进行残差分布的可视化

    R语言使用DALEX包的model_performance函数对caret包生成的多个算法模型进行残差分布分析并使用箱图进行残差分布的可视化 目录

  9. R语言plotly可视化:plotly可视化箱图、基于预先计算好的分位数、均值、中位数等统计指标可视化箱图、箱图中添加缺口、可视化均值和标准差(With Precomputed Quartiles)

    R语言plotly可视化:plotly可视化箱图.基于预先计算好的分位数.均值.中位数等统计指标可视化箱图.箱图中添加缺口.可视化均值和标准差(Box Plot With Precomputed Qu ...

最新文章

  1. 【Codeforces】1093C Mishka and the Last Exam
  2. AI:一个20年程序猿的学习资料大全—结构分析软件/办公软件/电气制造控制/高级语言编程/平面三维设计/视频编辑/FQ格式转换软件——只有你不想要的,没有你找不到的
  3. 移动端阻止body左右偏移
  4. 经典算法详解 之 递归算法
  5. 习题4-6 水仙花数(20 分)
  6. stochastic noise and deterministic noise
  7. 用calibre自制图文并茂且支持kindle的mobi电子书
  8. 2023CS保研经验分享(清深、上交、港科大、南大LAMDA、同济、东南Palm等)
  9. 求两个数的最小公倍数及多个数的最小公倍数的求法
  10. 梦殇 chapter three
  11. Simulink步长选择
  12. 你好,法语!A2知识点总结(1)
  13. Hololens学习(三)打包编译安装HoloLens2应用
  14. ch341a编程和ttl刷机区别_USB转TTL(CH341A)的注意事项及说明
  15. ffmpeg statis vs dev技术选型?
  16. 韩国顶级舞台剧《爱上街舞少年的芭蕾少女》掀起街舞狂潮
  17. 数据结构中的L=(List)malloc(sizeof(PtrToNode));是什么意思
  18. c语言别踩白块小游戏代码,自学easeljs 根据别踩白块游戏规则自己写的代码
  19. 年轻的时候应该去远方漂泊(转)
  20. 初识蓝牙JDY-08(修订2)

热门文章

  1. 决策规划算法四:Piecewise Jerk Path Optimizer
  2. 【mysql】mysql获取两个集合的交集/差集/并集
  3. 玲珑杯round#11 ----A
  4. 第一篇博文——我的第一枚脚印
  5. Converting Phase Noise to Random Jitter(Period)
  6. 全志R329如何设置蓝牙自动重连时间或关闭自动重连?
  7. 掌握这3点你也可以,我每天涨粉300个,做自媒体如何快速吸粉?
  8. SAP ABAP 业务对象 BUS2072 ControllingDocument 统驭凭证 BAPI 清单和相关 TCODE
  9. Yoink 3.5.11 文件临时存放站
  10. SecureCRT乱码和超时设置