You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确绘制子图?代码输出空维度无图像问题排查

问题分析与修复方案

你的代码存在几个关键问题,导致无法正常显示图像:

1. 子图轴对象未正确索引

plt.subplots(1, 2)返回的axes是包含两个子图轴的数组,但你直接使用未定义的ax变量,既没指定子图索引,还重复调用ax.set_title覆盖内容,最终两个可视化挤在同一个错误的轴上,导致显示异常。

2. Grad-CAM可视化代码缺失

你只调用了LIME的解释函数,没有生成Grad-CAM热力图的逻辑,直接用原始图像代替,不符合需求且内容错误。

3. 图像显示的图层叠加与格式问题

如果要在原始图像上叠加热力图,需要设置透明度(比如alpha=0.5)才能看到叠加效果;另外,解释函数返回的图像可能维度、数据类型不符合matplotlib显示要求(比如是0-1的float格式而非0-255的uint8)。

修复后的代码示例

def plot_XAI2(img, model):
    # 生成Grad-CAM和LIME的解释图像(补充你的Grad-CAM生成函数)
    grad_cam_img = explain_image_gradcam(img, model)
    lime_img = explain_image_lime(img, model)
    
    fig, axes = plt.subplots(1, 2, figsize=(12, 6))
    
    # 绘制Grad-CAM子图(叠加原始图与热力图)
    axes[0].imshow(img)
    axes[0].imshow(grad_cam_img, cmap='jet', alpha=0.5)
    axes[0].set_title("Grad-CAM")
    axes[0].axis('off')
    
    # 绘制LIME子图
    axes[1].imshow(lime_img)
    axes[1].set_title("LIME")
    axes[1].axis('off')
    
    plt.tight_layout()
    plt.show()

# 确保img是matplotlib可显示的格式
img = path_to_image('Lung_cancer (1).jpg')
# 检查图像格式:应为(H, W, 3)的uint8类型
print("图像维度:", img.shape, "数据类型:", img.dtype)

plot_XAI2(img, model)
predict_image_class(img, model)

额外排查点

  • 确认explain_image_gradcam和explain_image_lime返回的图像格式正确:热力图维度为(H,W),彩色解释图维度为(H,W,3),数据范围在0-255(uint8)或0-1(float)。
  • 如果path_to_image返回的是模型输入用的张量(带batch维度的float32),需先转换为可视化格式:
    import numpy as np
    # 去除batch维度并转换为uint8
    img = np.squeeze(img.numpy())
    img = (img * 255).astype(np.uint8)
    

内容的提问来源于stack exchange,提问作者ayahahaha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 23:15:35