查看原文
其他

PyTorch 教程-用于风格转移的特征提取

点击关注👉 Python架构师 2024-02-11
整理:python架构师

在将图像加载到内存后,我们将实现风格转移。为了实现风格转移,有必要将图像的样式与其内容分离。之后,还可以将一张图像的风格元素转移到第二张图像的内容元素中。这个过程主要使用标准卷积神经网络的特征提取。

然后,这些特征被操纵以提取内容信息或风格信息。这个过程涉及三张图像,即风格图像、内容图像和最终的目标图像。将风格图像的风格与内容图像中的内容相结合,以创建最终的目标图像。

这个过程开始时,选择模型中的一些层来提取特征。通过选择一些层来提取特征,我们可以很好地了解图像在整个神经网络中的处理过程。我们还从风格图像和内容图像中提取模型特征。之后,我们从目标图像中提取特征,并将其与风格图像特征和内容图像特征进行比较。

资源分享

👉点击领取:最全Python资料合集

从图像中获取特征

# Defining simple method with two arguments, i.e. our image and our model def get_features(image,model): #choosing specific layer within our VGG-19 model that we are going to extract features from # Defining layers dictionary object which contains the specific layers layers={'0':'conv1_1', #Mapping 0 to conv1_1 '5':'conv2_1', #Mapping 5 to conv2_1 '10':'conv3_1', #Mapping 10 to conv3_1 '19':'conv4_1', #Mapping 19 to conv4_1 '21':'conv4_2', #Mapping 21 to conv4_2 '28':'conv5_1',} #Mapping 28 to conv5_1

现在我们有六个特征提取层。在这六个特征提取层中,我们将使用其中的五个进行风格提取,只使用其中一个进行内容提取。我们将使用conv4_2进行内容提取。对于提取内容来说,仅使用这个单一层就足够了。这一层更深入我们的神经网络,提供了高深度的图像特征。这就是为什么预训练的目标检测卷积神经网络在表示内容元素方面非常有效的原因。

从网络中各个特征提取层获取风格特征,允许进行最佳风格的创建。从多个层提取风格特征将允许进行最有效的风格提取和重建。
#Defining an empty dictionary called features to store all the extracted features features={} #Running a loop which iterates over all of the layers in our model for name, layer in model._modules.items(): #Running our image through the specific layer and store into the new image image=layer(image) #checking the name of the current layer which we are iterating through is inside layers if name in layers: #If true then store the output from that specific layer features[layers[name]]=image #returning feature dictionary return features
一旦我们初始化了get_feature方法,我们必须用我们的内容图像和我们的VGG模型调用它。
content_features=get_features(content,vgg)
以相同的方式,我们将为我们的风格图像执行以下操作:
style_features=get_features(style, vgg)

 
热门推荐
继续滑动看下一个

PyTorch 教程-用于风格转移的特征提取

点击关注👉 Python架构师
向上滑动看下一个

您可能也对以下帖子感兴趣

文章有问题?点此查看未经处理的缓存