引入依赖、模型定义省略
...
model = Model(inputs=inp, outputs=x)
model.load_weights('WDD_jing3_2_weights.hdf5') ***#加载自己的模型文件,可以是weights***
image=cv2.imread('6.png') ***#输入图像 ,本人输入的是一个小猫***
image_arr = cv2.resize(image, (224, 224))
image_arr = np.expand_dims(image_arr, axis=0)
preds = model.predict(image_arr)
# find the class index
index = np.argmax(preds[0])
target_output = model.output[:, index]
# last_conv_layer=model.get_layer('norm_l_1')
last_conv_layer=model.get_layer('max_pooling2d_5') # ***这里是keras定义的层的名字,想看哪一层的输出,改为哪一层的名字***
# compute the gradient of the output feature map with this target class
grads = K.gradients(target_output, last_conv_layer.output)[0]
# mean the gradient over a specific feature map channel
pooled_grads = K.mean(grads, axis=(0, 1, 2))
# this function returns the output of last_conv_layer and grads
# given the input picture
iterate = K.function([model.input], [pooled_grads, last_conv_layer.output[0]])
pooled_grads_value, conv_layer_output_value = iterate([image_arr])
# We multiply each channel in the feature map array
# by "how important this channel is" with regard to the target class
for i in range(conv_layer_output_value.shape[-1]):
conv_layer_output_value[:, :, i] *= pooled_grads_value[i]
# The channel-wise mean of the resulting feature map
# is our heatmap of class activation
heatmap = np.mean(conv_layer_output_value, axis=-1)
heatmap = np.maximum(heatmap, 0)
heatmap /= np.max(heatmap)
img=image #加载原始图像
heatma=cv2.resize(heatmap,(img.shape[1],img.shape[0]))
#将热力图调整为与原始图像一样大小
heatmap=np.uint8(255*heatma)#将热力图改为rgb格式
heatmap=cv2.applyColorMap(heatmap,cv2.COLORMAP_JET)#将热力图应用于原始图像
superimposed_img=heatmap*3+img#3是热力图的强度因子
img_write = cv2.imencode(".jpg",superimposed_img)[1].tofile('CAM6_1.jpg')# ***存图***