python - 将 vgg19 层的输出显示为图像
问题描述
我正在阅读这篇论文:神经风格迁移。在本文中,作者从 vgg19 层的输出重建图像。我正在使用 Keras。block1_conv1
层的输出大小为(1, 400, 533, 64)
。这里 1 是作为输入的图像数,400 是行数,533 列数和 64 个通道数。当我尝试将其重建为图像时,由于图像大小为 13644800 不是 3 的倍数,因此出现错误,因此我无法在三个通道中显示图像。我怎样才能重建这个图像?
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)
解决方案
你写了:
“
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)的更多信息,我可以在需要时为您提供更多帮助。
推荐阅读
- c# - 执行 SSIS 包结果失败 DTSError is the executable is not specified
- python - 我在使用 python-bs4 抓取请求时不断收到不同的错误消息
- sql - 在 SQL 中计算转化率
- typescript - TypeScript:接口取决于(递归)属性的类型
- sql - Postgresql group by 显示所有元素甚至为空
- angular - 如何允许用户在另一个选项卡中打开页面而不必再次登录
- xcode - Xcode 12 更新中断 Pod 和产品
- c# - Log all handles exception
- css - 有条件地将文本列表分成两列
- sql - 使用 MAX 查找给定其他属性的最新时间