content_outputs = [vgg.get_layer(x).output for x in content_layers]
model = Model(vgg.input, content_outputs)
预训练的 `Keras CNN` 模型分为两部分。底部由卷积层组成,通常称为特征提取器,而顶部是由全连接层组成的分类器头。因为我们只想提取特征而不关心分类器,所以在实例化VGG模型时将设置 `include_top = False` 。
#### 图像加载
首先需要加载内容图像和风格图像:
def scale_image(image):
MAX_DIM = 512
scale = np.max(image.shape)/MAX_DIM
print(image.shape)
new_shape = tf.cast(image.shape[:2]/scale, tf.int32)
image = tf.image.resize(image, new_shape)
return image
content_image = scale_image(np.asarray(Image.open(‘7.jpg’)))
style_image = scale_image(np.asarray(Image.open(‘starry-night.jpg’)))
#### VGG预处理
`Keras` 预训练模型期望输入图像的BGR范围为 `[0, 255]` 。因此,第一步是反转颜色通道,以将 `RGB` 转换为`BGR` 。 `VGG` 对不同的颜色通道使用不同的平均值,可以使用 `tf.keras.applications.vgg19.preprocess_input()` 进行预处理,在 `preprocess_input()` 内部,分别为B,G和R通道的像素值减去 `103.939` 、`116.779` 和 `123.68` 。
以下是前向计算代码,在对图像进行前向计算之前先对其进行预处理,然后再将其输入模型以返回内容特征。然后,我们提取内容特征并将其用作我们的目标:
def extract_features(image):
image = tf.keras.applications.vgg19。preprocess_input(image *255.)
content_ref = model(image)
return content_ref
content_image = tf.reverse(content_image, axis=[-1])
content_ref = extract_features(content_image)
在代码中,由于图像已标准化为 `[0., 1.]`,因此我们需要通过将其乘以255将其恢复为 `[0.,255.]`。然后创建一个随机初始化的输入,该输入也将成为风格化的图像&#x