首页 > 解决方案 > 将 vgg19 层的输出显示为图像

问题描述

我正在阅读这篇论文:神经风格迁移。在本文中,作者从 vgg19 层的输出重建图像。我正在使用 Keras。block1_conv1层的输出大小为(1, 400, 533, 64)。这里 1 是作为输入的图像数,400 是行数,533 列数和 64 个通道数。当我尝试将其重建为图像时,由于图像大小为 13644800 不是 3 的倍数,因此出现错误,因此我无法在三个通道中显示图像。我怎样才能重建这个图像?

我想从图层重建图像,如下所示: 从 vgg 层重建图像 下面是相同的代码:

from keras.preprocessing.image import load_img, img_to_array
from scipy.misc import imsave
import numpy as np
from keras.applications import vgg19
from keras import backend as K

CONTENT_IMAGE_FN = store image as input here

def preprocess_image(image_path):
    img = load_img(image_path, target_size=(img_nrows, img_ncols))
    img = img_to_array(img)
    img = np.expand_dims(img, axis=0)
    img = vgg19.preprocess_input(img)
    return img

width, height = load_img(CONTENT_IMAGE_FN).size
img_nrows = 400
img_ncols = int(width * img_nrows / height)
base_image = K.variable(preprocess_image(CONTENT_IMAGE_FN))

RESULT_DIR = "generated/"
RESULT_PREFIX = RESULT_DIR + "gen"
if not os.path.exists(RESULT_DIR):
  os.makedirs(RESULT_DIR)
result_prefix = RESULT_PREFIX

# this will contain our generated image
if K.image_data_format() == 'channels_first':
    combination_image = K.placeholder((1, 3, img_nrows, img_ncols))
else:
    combination_image = K.placeholder((1, img_nrows, img_ncols, 3))

x = preprocess_image(CONTENT_IMAGE_FN)

outputs_dict = dict([(layer.name, layer.output) for layer in model.layers])
feature_layers = ['block1_conv1', 'block2_conv1',
                  'block3_conv1', 'block4_conv1',
                  'block5_conv1']
outputs = []
for layer_name in feature_layers:
  outputs.append(outputs_dict[layer_name])
functor = K.function([combination_image], outputs )   # evaluation function

# Testing
test = x
layer_outs = functor([test])
print(layer_outs)

layer_outs[0].reshape(400, -1 , 3) //getting error here

我收到以下错误:

ValueError: cannot reshape array of size 13644800 into shape (400,newaxis,3)

标签: pythontensorflowkerasconv-neural-networkvgg-net

解决方案


你写了:

block1_conv1层的输出大小是(1, 400, 533, 64)。这里 1 是作为输入的图像数,400 是行数,533 列和 64 通道数”但这不正确。输出对应 1个block1_conv1通道维度(通道优先)、400 * 533 图像维度和 64 个过滤器

当您尝试将具有 1 通道(400 * 533 * 64 = 13644800)VGG19的图像输入的输出向量重塑为对应于 3 通道输出的向量时,会发生错误。

此外,您必须通过3 通道输入:

来自VGG19代码:

input_shape:可选的形状元组,只有在include_top为False时才指定(否则输入形状必须是(224, 224, 3) (带channels_last数据格式)或(3, 224, 224)(带channels_first数据格式)。它应该正好有3个输入通道,并且宽度和高度应该不小于32. eg(200, 200, 3)将是一个有效值。

因此,您的输入图像必须是 3 个通道。如果您甚至想向您提供 1 个通道(灰度)图像,VGG19则应执行以下操作,如果channels first

X = np.repeat(X, 3 , axis=0) 

或者

X = np.repeat(X, 3 , axis=2) 

如果channels last 没有批次维度

X = np.repeat(X, 3 , axis=3) 

与批次维度

如果您提供有关图像输入矩阵的实际尺寸及其类型(灰度、RGB)的更多信息,我可以在需要时为您提供更多帮助。


推荐阅读