from keras import backend as K
import cv2
from keras.utils.vis_utils import plot_model
from DeepFace import functions,analyze
import numpy as np
from sklearn import metrics
import matplotlib.pyplot as plt
import tensorflow as tf
tf_version = int(tf.__version__.split(".")[0])
print('tf_version:',tf_version)
if tf_version == 1:
import keras
from keras.models import Model, Sequential
from keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, Flatten, Dense, Dropout
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
elif tf_version == 2:
from tensorflow import keras
from tensorflow.keras.models import Model, Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, AveragePooling2D, Flatten, Dense, Dropout
from tensorflow.keras.optimizers import SGD
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.applications.resnet import ResNet50
# num_classes = 7
model = ResNet50(weights=None,classes=7)
model.load_weights('emotion50.h5')
layer_1 = K.function([model.layers[0].input], [model.layers[6].output])#第一个 model.layers[0],不修改,表示输入数据;第二个model.layers[you wanted],修改为你需要输出的层数的编号
image = cv2.imread('1.jpg')
input_image = cv2.resize(image, (224, 224), interpolation=cv2.INTER_LINEAR)
input_image = input_image[None,:,:,:]
f1 = layer_1([input_image])[0]#只修改inpu_image
plot_model(model, to_file='model.png', show_shapes=True, show_layer_names=True)
#第一层卷积后的特征图展示,输出是(1,224,224,3),(样本个数,特征图尺寸长,特征图尺寸宽,特征图个数)
for _ in range(32):
show_img = f1[:, :, :, _]
show_img.shape = [56, 56]
plt.subplot(4, 8, _ + 1)
plt.imshow(show_img, cmap='gray')
plt.axis('off')
plt.show()