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

GradCAM热图叠加原图触发TypeError,求助解决方法

解决GradCAM热图叠加时的TypeError问题

错误原因

报错TypeError: 'module' object is not callable出现在display(Image(cam_path))行,核心问题是**Image被当作模块导入,而非可实例化的类**。比如若导入语句为import Image,会导入整个PIL的Image模块,而非其中的Image类,导致调用Image(cam_path)时触发错误。

修复方案

方案1:修正导入语句

在代码开头添加正确的导入,确保Image是可实例化的类,display是IPython的显示函数:

from PIL import Image
from IPython.display import display

方案2:改用matplotlib显示(兼容性更强)

若不想依赖IPython的display,可以用matplotlib替代显示逻辑,修改代码中的显示部分:

# 替换原有的display(Image(cam_path))
import matplotlib.pyplot as plt
plt.imshow(plt.imread(cam_path))
plt.axis('off')
plt.show()

完整修正后的代码

import numpy as np
from keras import preprocessing
import matplotlib.cm as cm
from PIL import Image
from IPython.display import display

img_path = '/content/drive/MyDrive/4.png'

def save_and_display_gradcam(img_path, heatmap, cam_path="cam.jpg", alpha=0.4):
    # 加载原图
    img = preprocessing.image.load_img(img_path)
    img = preprocessing.image.img_to_array(img)

    # 将热图缩放至0-255范围
    heatmap = np.uint8(255 * heatmap)

    # 使用jet色卡着色热图
    jet = cm.get_cmap("jet")

    # 提取色卡的RGB值
    jet_colors = jet(np.arange(256))[:, :3]
    jet_heatmap = jet_colors[heatmap]

    # 创建着色后的热图
    jet_heatmap = preprocessing.image.array_to_img(jet_heatmap)
    jet_heatmap = jet_heatmap.resize((img.shape[1], img.shape[0]))
    jet_heatmap = preprocessing.image.img_to_array(jet_heatmap)

    # 叠加热图与原图
    superimposed_img = jet_heatmap * alpha + img
    superimposed_img = preprocessing.image.array_to_img(superimposed_img)

    # 保存叠加后的图片
    superimposed_img.save(cam_path)

    # 显示结果
    display(Image(cam_path))


save_and_display_gradcam(img_path, heatmap)

额外检查项

  • 确认heatmap是形状与原图空间维度匹配的numpy数组(如原图为(224,224,3),热图需为(224,224))
  • 确保所有依赖库已安装:pip install pillow matplotlib tensorflow

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 09:24:20