使用Grad-CAM方法建立YOLOv5中实现三种不同的热力图可视化(普通热力图、仅标签框内的热力图、去除红色以外区域的热力图

使用Grad-CAM方法建立YOLOv5中实现三种不同的热力图可视化(普通热力图、仅标签框内的热力图、去除红色以外区域的热力图


YOLOv5热力图grad-cam
建立目标:3种热力图可视化:普通的,仅标签框内的,去除红色以外区域的
用于YOLOv5添加注意力机制、改进模型等
在这里插入图片描述
YOLOv5中实现三种不同的热力图可视化(普通热力图、仅标签框内的热力图、去除红色以外区域的热力图),我们可以使用Grad-CAM方法。

代码示例,仅供参考。

如何加载模型、处理图像、生成热力图以及展示结果。
在这里插入图片描述

步骤 1: 导入必要的库

import cv2
import numpy as np
import torch
from torchvision.transforms import functional as F
from pytorch_grad_cam import GradCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM, EigenCAM, EigenGradCAM, LayerCAM
from pytorch_grad_cam.utils.image import show_cam_on_image
from models.experimental import attempt_load  # 假设这是加载YOLOv5模型的方式

步骤 2: 加载YOLOv5模型

model = attempt_load('yolov5_weights.pt', map_location='cpu')  # 或 'cuda' 如果有GPU的话
model.eval()

步骤 3: 定义Grad-CAM类

target_layer = model.model[-1]  # 这里假设目标层是最后一个层
cam = GradCAM(model=model, target_layer=target_layer, use_cuda=True if torch.cuda.is_available() else False)

步骤 4: 处理输入图像

def preprocess_image(img_path):
    img = cv2.imread(img_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img_tensor = F.to_tensor(img).unsqueeze(0)  # 添加batch维度
    return img, img_tensor

步骤 5: 获取热力图

def get_gradcam_visualization(model, img_tensor, cam_method, target_category=None):
    grayscale_cam = cam_method(input_tensor=img_tensor, target_category=target_category)
    grayscale_cam = grayscale_cam[0, :]
    visualization = show_cam_on_image(img / 255.0, grayscale_cam, use_rgb=True)
    return visualization

# 普通热力图
img, img_tensor = preprocess_image('path_to_your_image.jpg')
visualization = get_gradcam_visualization(model, img_tensor, cam)

# 显示结果
import matplotlib.pyplot as plt
plt.imshow(visualization)
plt.show()

特定区域热力图

仅标签框内的热力图
def get_bounding_boxes(model, img_tensor):
    with torch.no_grad():
        output = model(img_tensor)
    boxes = output.xyxy[0].tolist()
    return boxes

def visualize_bounding_box_heatmap(img, boxes, visualization):
    for box in boxes:
        x1, y1, x2, y2 = int(box[0]), int(box[1]), int(box[2]), int(box[3])
        cropped_img = img[y1:y2, x1:x2]
        cropped_tensor = F.to_tensor(cropped_img).unsqueeze(0)
        cropped_visualization = get_gradcam_visualization(model, cropped_tensor, cam)
        img[y1:y2, x1:x2] = cropped_visualization
    return img

boxes = get_bounding_boxes(model, img_tensor)
heatmap_with_boxes = visualize_bounding_box_heatmap(img, boxes, visualization)
plt.imshow(heatmap_with_boxes)
plt.show()
去除红色以外区域的热力图
def remove_non_red_regions(visualization):
    lower_red = np.array([200, 0, 0], dtype="uint8")
    upper_red = np.array([255, 100, 100], dtype="uint8")
    mask = cv2.inRange(visualization, lower_red, upper_red)
    visualization[mask == 0] = [255, 255, 255]  # 将非红色区域变白或其他颜色
    return visualization

heatmap_without_non_red = remove_non_red_regions(visualization)
plt.imshow(heatmap_without_non_red)
plt.show()

完整代码

import cv2
import numpy as np
import torch
from torchvision.transforms import functional as F
from pytorch_grad_cam import GradCAM, ScoreCAM, GradCAMPlusPlus, AblationCAM, XGradCAM, EigenCAM, EigenGradCAM, LayerCAM
from pytorch_grad_cam.utils.image import show_cam_on_image
from models.experimental import attempt_load

# 加载YOLOv5模型
model = attempt_load('yolov5_weights.pt', map_location='cpu')
model.eval()

# 定义Grad-CAM类
target_layer = model.model[-1]
cam = GradCAM(model=model, target_layer=target_layer, use_cuda=True if torch.cuda.is_available() else False)

# 处理输入图像
def preprocess_image(img_path):
    img = cv2.imread(img_path)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img_tensor = F.to_tensor(img).unsqueeze(0)
    return img, img_tensor

# 获取热力图
def get_gradcam_visualization(model, img_tensor, cam_method, target_category=None):
    grayscale_cam = cam_method(input_tensor=img_tensor, target_category=target_category)
    grayscale_cam = grayscale_cam[0, :]
    visualization = show_cam_on_image(img / 255.0, grayscale_cam, use_rgb=True)
    return visualization

# 获取边界框
def get_bounding_boxes(model, img_tensor):
    with torch.no_grad():
        output = model(img_tensor)
    boxes = output.xyxy[0].tolist()
    return boxes

# 可视化边界框内的热力图
def visualize_bounding_box_heatmap(img, boxes, visualization):
    for box in boxes:
        x1, y1, x2, y2 = int(box[0]), int(box[1]), int(box[2]), int(box[3])
        cropped_img = img[y1:y2, x1:x2]
        cropped_tensor = F.to_tensor(cropped_img).unsqueeze(0)
        cropped_visualization = get_gradcam_visualization(model, cropped_tensor, cam)
        img[y1:y2, x1:x2] = cropped_visualization
    return img

# 去除非红色区域
def remove_non_red_regions(visualization):
    lower_red = np.array([200, 0, 0], dtype="uint8")
    upper_red = np.array([255, 100, 100], dtype="uint8")
    mask = cv2.inRange(visualization, lower_red, upper_red)
    visualization[mask == 0] = [255, 255, 255]
    return visualization

# 主程序
if __name__ == "__main__":
    img_path = 'path_to_your_image.jpg'
    img, img_tensor = preprocess_image(img_path)
    
    # 普通热力图
    visualization = get_gradcam_visualization(model, img_tensor, cam)
    plt.imshow(visualization)
    plt.show()
    
    # 仅标签框内的热力图
    boxes = get_bounding_boxes(model, img_tensor)
    heatmap_with_boxes = visualize_bounding_box_heatmap(img, boxes, visualization)
    plt.imshow(heatmap_with_boxes)
    plt.show()
    
    # 去除红色以外区域的热力图
    heatmap_without_non_red = remove_non_red_regions(visualization)
    plt.imshow(heatmap_without_non_red)
    plt.show()

展示了如何在YOLOv5中实现三种不同的热力图可视化,并且可以用于各种 YOLOv5模型以添加注意力机制和改进模型。

仅供参考。

### 使用 Grad-CAM 生成可视化热力 #### 安装依赖库 为了实现 Grad-CAM 的功能,需要安装一些必要的 Python 库。可以使用 pip 来完成这些操作。 ```bash pip install torch torchvision numpy matplotlib opencv-python pillow ``` #### 导入所需模块 接下来导入所需的 Python 模块来处理像并运行模型: ```python import cv2 import numpy as np from PIL import Image import torch import torchvision.transforms as transforms from pytorch_grad_cam.utils.image import show_cam_on_image from pytorch_grad_cam import GradCAM ``` #### 加载预训练模型 这里以 ResNet50 为例加载一个已经过预训练的卷积神经网络模型,并设置其评估模式以便后续推理过程中的梯度计算能够正常工作[^1]。 ```python model = torch.hub.load('pytorch/vision:v0.6.0', 'resnet50', pretrained=True) model.eval() ``` #### 准备目标层 对于大多数情况下,默认选择最后一层卷积作为目标层来进行注意力机制分析是最合适的;而对于某些特定架构,则可能需要手动指定其他位置上的卷积层作为目标对象[^2]。 ```python target_layer = model.layer4[-1] ``` #### 初始化 Grad-CAM 实例 创建一个新的 `GradCAM` 对象实例并将之前定义好的参数传递给它用于初始化配置。 ```python cam = GradCAM(model=model, target_layers=[target_layer], use_cuda=torch.cuda.is_available()) ``` #### 像前处理函数 编写一个辅助方法负责将原始片转换成适合送入深度学习框架的形式——即张量(tensor),同时保留原尺寸副本供后期叠加显示时调用[^3]。 ```python def preprocess_image(img_path): img = Image.open(img_path).convert('RGB') transform = transforms.Compose([ transforms.Resize((224, 224)), transforms.ToTensor(), transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) ]) input_tensor = transform(img).unsqueeze(0) # Add batch dimension. return input_tensor, np.array(img) / 255. input_tensor, rgb_img = preprocess_image("path_to_your_image.jpg") ``` #### 获取类别预测结果 通过调用模型对输入数据做出分类决策,并获取最高概率对应的标签索引值。 ```python output = model(input_tensor) prediction = output.argmax(dim=1).item() print(f"The predicted class index is {prediction}.") ``` #### 构建 Grad-CAM 热力 最后一步就是实际构建 Grad-CAM 映射了。这会返回一个形状与输入一致但只含单通道灰阶数值的结果矩阵表示重要性权重分布情况。 ```python grayscale_cam = cam(input_tensor=input_tensor, targets=None)[0, :] visualization = show_cam_on_image(rgb_img, grayscale_cam, use_rgb=True) cv2.imshow('Visualization', visualization[:, :, ::-1]) # Convert RGB to BGR for OpenCV display compatibility cv2.waitKey(0) cv2.destroyAllWindows() ``` 上述代码片段展示了如何利用 PyTorch 和 grad-cam 库快速搭建一套基于 Grad-CAM 技术的视觉解释工具链路,帮助理解复杂深层结构内部运作原理及其对外界刺激响应特性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值