Tensorflow 特征图可视化

使用Tensorflow对特征图进行可视化输出
training_transform和process_image这两个函数目的是resize时,保证原图比例不变的情况下,使用黑边填充

# -*- coding: utf-8 -*-


import cv2
import numpy as np
from tensorflow.keras.applications.vgg16 import VGG16
from tensorflow.keras.models import Model

def training_transform(height, width, output_height, output_width):
    height_scale, width_scale = output_height / height, output_width / width
    scale = min(height_scale, width_scale)
    resize_height, resize_width = round(height * scale), round(width * scale)
    pad_top = (output_height - resize_height) // 2
    pad_left = (output_width - resize_width) // 2
    A = np.float32([[scale, 0.0], [0.0, scale]])
    B = np.float32([[pad_left], [pad_top]])
    M = np.hstack([A, B])
    return M, output_height, output_width

def process_image(img,input_shape):
    h, w = img.shape[:2]
    M, h_out, w_out = training_transform(h, w, input_shape[0], input_shape[1])
    # 填充黑边缩放
    letterbox = cv2.warpAffine(img, M, (w_out, h_out))
    pimage = np.float32(letterbox) / 255.
    pimage = np.expand_dims(pimage, axis=0)
    return pimage

# 下面的第一个model是vgg16,第二个model是使用vgg16的前半部分作为主干网络
model= VGG16(include_top=False,weights='imagenet',input_shape=(224,224,3))
model = Model(inputs=vgg16.input,outputs=model.get_layer('block1_conv2').output)

print(model.summary())

img = cv2.imread('shan.jpg')
img = process_image(img,input_shape=(224,224))

out = model.predict(img)

import matplotlib.pyplot as plt
for i in range(64):
    plt.matshow(out[0,:,:,i],cmap='viridis')
    plt.axis('off')
    plt.savefig('features//feature-{}.png'.format(i),bbox_inches='tight')
    plt.show()

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值