赞
踩
原图:
Keras代码:
- from keras.models import Sequential
- from keras.layers.convolutional import Convolution2D,MaxPooling2D,AveragePooling2D
- from keras.layers import Activation
- import cv2
- import os
- import shutil
- import numpy as np
- import matplotlib.pyplot as plt
-
- #网络模型
- def create_model():
- model = Sequential()
- #输入 img.shape = (28,28,3)
-
- #第一层卷积
- model.add(Convolution2D(9,(5,5),padding='same',strides=(1,1),input_shape=img.shape)) #(1, 24, 24, 9)
- model.add(Activation('relu'))
- model.add(MaxPooling2D(pool_size=(2,2)))
-
- # # 第二层卷积
- # model.add(Convolution2D(9,(5,5),padding='same',strides=(2,2)))
- # model.add(Activation('relu'))
- # model.add(MaxPooling2D(pool_size=(2,2)))
- return model
-
- #保存特征图
- def save_conv_img(conv_img):
- feature_maps = np.squeeze(conv_img,axis=0)
- img_num = feature_maps.shape[2]
- all_feature_maps = []
- for i in range(0,img_num):
- single_feature_map = feature_maps[:,:,i]
- all_feature_maps.append(single_feature_map)
- plt.imshow(single_feature_map)
- plt.savefig('./feature_map/'+'feature_{}'.format(i))
- sum_feature_map = sum(feature_map for feature_map in all_feature_maps)
- plt.imshow(sum_feature_map)
- plt.savefig("./feature_map/feature_map_sum.png")
-
- def create_dir():
- if not os.path.exists('./feature_map'):
- os.mkdir('./feature_map')
- else:
- shutil.rmtree('./feature_map')
- os.mkdir('./feature_map')
-
- if __name__ =='__main__':
- img = cv2.imread('b0.jpg')
- print(img.shape)
- create_dir()
- model = create_model()
-
- img_batch = np.expand_dims(img,axis=0)
-
- conv_img = model.predict(img_batch) #predict()的参数是需要四维的
- save_conv_img(conv_img)
经过第一层卷积后,得到的特征图为:
因为第一层卷积设置了一共有9个卷积核,所以对应就会有9张特征图
而网络的输出则是9张特征图合在一起,形成总的特征图:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。