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

时间:2018-01-10 09:21:17

标签: keras

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

model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

如何将convolution2D的输出保存为图像?

1 个答案:

答案 0 :(得分:1)

获取模型的输出

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

predictions = model.predict(inputData)

输入数据必须是形状为(any, img.shape[0], img.shape[1], img.shape[2])的numpy数组。

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

获取您已创建的模型,并在model.layers[i]model.get_layer('someName')中找到所需的图层。例如,您可以使用名称model.add(Convolution2D(1,3, input_shape=img.shape, name='target_conv'))

声明图层
from keras.models import Model

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

predictions = subModel.predict(inputData)

保存图片

这仅在卷积具有3个或更少通道时才有意义。既然你的有1,那就是灰度图像。

使用像PIL这样的库:

from PIL import Image

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

保存个别频道

如果你的转换层有超过3个通道,那么结果图像对我们的大脑并没有多大意义......所以我们应该独立保存每个通道。

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')
相关问题