如何将每层卷积神经网络的输出保存为keras中的图像?

如何将每层卷积神经网络的输出保存为keras中的图像?,keras,Keras,如何将卷积2D的输出保存为图像?获取模型的输出 对输入数据使用predict方法获得输出: model=Sequential() model.add(Convolution2D(1,3,3, input_shape=img.shape)) model.add(Activation('relu')) model.add(MaxPooling2D(pool_size=(2,2))) 输入数据必须是具有shape的numpy数组(任意,img.shape[0]、img.shape[1]、img.s

如何将卷积2D的输出保存为图像?

获取模型的输出

对输入数据使用
predict
方法获得输出:

model=Sequential()
model.add(Convolution2D(1,3,3, input_shape=img.shape))

model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))
输入数据必须是具有shape
的numpy数组(任意,img.shape[0]、img.shape[1]、img.shape[2])

创建子模型以获得中间输出

获取已创建的模型,并在
model.layers[i]
model.Get\u layer('someName')
中找到所需的层。例如,您可以用一个名称声明层:
model.add(卷积2D(1,3,input\u shape=img.shape,name='target\u conv'))

保存图像

这只有在卷积有3个或更少通道时才有意义。因为你的有1个,所以它是一个灰度图像

使用一些库,如PIL:

from keras.models import Model

subModel = Model(model.input, model.get_layer('target_conv').output)

predictions = subModel.predict(inputData)
保存单个频道

如果您的conv层有3个以上的通道,那么生成的图像对我们的大脑来说并没有真正意义。。。因此,我们应该独立保存每个通道

from PIL import Image

for i in range(predictions.shape[0]):
    Image.fromarray(predictions[i]).save('filename'+str(i),'.bmp')
看见
from PIL import Image

for i in range(predictions.shape[0]):
    Image.fromarray(predictions[i]).save('filename'+str(i),'.bmp')
for i in range(predictions.shape[0]):
    im = predictions[i]

    for channel in range(im.shape[-1]):
        Image.fromarray(im[:,:,channel]).save('img_'+str(i)+'_ch_' + str(channel),'.bmp')