概述
本文通过 函数式api 的 多个输出结果, 将 卷积结果 和 池化结果 显示成 图片
注意
卷积结果、池化结果 可能是 负数、浮点数,而图片是 0-255 之间的 整数,所以 将 卷积结果、池化结果 显示成图片,肯定会有 偏差
准备图片
代码
导入模块
import tensorflow as tf
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D, MaxPool2D
from tensorflow.keras.layers import Activation
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
读取图片
path=r"C:\Users\mym\Desktop\文件接收柜\aodaili.jpg"
im = Image.open(path)
img=np.array(im)
print('输入图shape:',img.shape)
print('输入图:',img)
转换图片矩阵维度
在执行predict操作时,要求图片矩阵是4维:
- 0维表示图片数量
- 1维表示图片高度
- 2维表示图片宽度
- 3维表示图片通道数
所以要做转换
img_batch = img.reshape(1,img.shape[0],img.shape[1],1)
print('输入图shape:',img_batch.shape)
建模
注意:两个输出结果
inp=tf.keras.Input(shape=img_batch.shape[1:])
conv1=Conv2D(4, (3, 3))(inp)
mp=MaxPool2D(pool_size=(4, 4))(conv1)
model=tf.keras.Model(inputs=inp,outputs=[conv1,mp])
model.summary()
查看卷积层权重
第一层是input层,第二层才是Conv2D层
w,b=model.layers[1].get_weights()
print(w)
print(w.shape)
print(b)
predict操作
# 输出特征图
prds = model.predict(img_batch)
# 由于指定2个输出结果,所以结果类型是list
print ("结果类型:",type(prds))
# print ("结果shape:",out_imgs.shape)
print ("预测结果长度:",len(prds))
print ("卷积结果 shape:",prds[0].shape)
print ("池化结果 shape:",prds[1].shape)
执行结果如下:
结果类型: <class 'list'>
预测结果长度: 2
卷积结果 shape: (1, 298, 298, 4)
池化结果 shape: (1, 74, 74, 4)
由于定义模型时,指定2个输出结果,所以执行predict操作后,结果是list类型
实现函数:将结果显示成图片
注意:
卷积结果、池化结果 可能是 负数、浮点数,而图片是 0-255 之间的 整数,所以 将 卷积结果、池化结果 显示成图片,肯定会有 偏差
matplotlib显示的图片大小 与 真实图片 大小不一致
def show_img(out_img,name):
num_pic = out_img.shape[-1]
print('out_img.shape:',out_img.shape)
#显示将特征图
for _ in range(num_pic):
show_img = out_img[:, :, _]
plt.imshow(show_img, cmap='gray')
plt.axis('off')
plt.show()
# 根据图片的numpy数组转成图片对象,由于numpy数组是浮点型,且可能有负数,所以要转换成8位像素模式,然后保存图片
Image.fromarray(show_img).convert('L').save("%s-%s.jpeg"%(name,_))
将卷积结果显示成图片
show_img(prds[0][0],"卷积结果")
注意:
- 图片仅供参考,与真实结果不一致
- matplotlib显示的图片大小 与 真实图片 大小不一致
将池化结果显示成图片
show_img(prds[1][0],"池化结果")
注意:
- 图片仅供参考,与真实结果不一致
- matplotlib显示的图片大小 与 真实图片 大小不一致
感谢:
https://blog.csdn.net/u010420283/article/details/80303231
https://blog.csdn.net/dcrmg/article/details/81255498
https://www.cnblogs.com/tectal/p/9426971.html
