【Pytorch】Visualization of Feature Maps(3)

news2024/9/22 1:07:01

在这里插入图片描述

学习参考来自:

  • Image Style Transform–关于图像风格迁移的介绍
  • github:https://github.com/wmn7/ML_Practice/tree/master/2019_06_03

文章目录

  • 风格迁移


风格迁移

风格迁移出处:

《A Neural Algorithm of Artistic Style》(arXiv-2015)

在这里插入图片描述

在这里插入图片描述

风格迁移的实现

在这里插入图片描述

Random Image 在内容上可以接近 Content Image,在风格上可以接近 Style Image,当然, Random Image 可以初始化为 Content Image

导入基本库,数据读取

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim

from PIL import Image
import matplotlib.pyplot as plt

import torchvision.transforms as transforms
import torchvision.models as models

import numpy as np
import copy
import os

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")


def image_loader(image_name, imsize):
    loader = transforms.Compose([
        transforms.Resize(imsize),  # scale images
        transforms.ToTensor()
    ])
    image = Image.open(image_name).convert("RGB")
    image = loader(image).unsqueeze(0)
    return image.to(device, torch.float)


def image_util(img_size=512, style_img="./1.jpg", content_img="./2.jpg"):
    "the size of style_img and contend_img should be same"
    imsize = img_size if torch.cuda.is_available() else 128  # use small size if no gpu
    style_img = image_loader(style_img, imsize)
    content_img = image_loader(content_img, imsize)

    print("Style Image Size:{}".format(style_img.size()))
    print("Content Image Size:{}".format(content_img.size()))

    assert style_img.size() == content_img.size(), "we need to import style and content images of the same size"
    return style_img, content_img

定义内容损失

在这里插入图片描述

"content loss"
class ContentLoss(nn.Module):
    def __init__(self, target):
        super(ContentLoss, self).__init__()
        self.target = target.detach()
        
    def forward(self, input):
        self.loss = F.mse_loss(input, self.target)
        return input

定义风格损失

def gram_matrix(input):
    a, b, c, d = input.size()  # N, C,
    features = input.view(a * b, c * d)
    G = torch.mm(features, features.t())
    return G.div(a * b * c * d)

在这里插入图片描述

Gram Matrix 最后输出大小只和 filter 的个数有关(channels),上面的例子输出为 3x3

Gram Matrix 可以表示出特征出现的关系(特征 f1、f2、f3 之间的关系)。

我们可以通过计算 Gram Matrix 的差,来计算两张图片风格上的差距

在这里插入图片描述

class StyleLoss(nn.Module):
    def __init__(self, target_feature):
        # we "detach" the target content from the tree used to dynamically
        # compute the gradient: this is stated value, not a variable .
        # Otherwise the forward method of the criterion will throw an error
        super(StyleLoss, self).__init__()
        self.target = gram_matrix(target_feature).detach()

    def forward(self, input):
        G = gram_matrix(input)
        self.loss = F.mse_loss(G, self.target)
        return input

写好前处理减均值,除方差

"based on VGG-16"
"put the normalization to the first layer"
class  Normalization(nn.Module):
    def __init__(self, mean, std):
        super(Normalization, self).__init__()
        # view the mean and std to make them [C,1,1] so that they can directly work with image Tensor of shape [B,C,H,W]
        self.mean = mean.view(-1, 1, 1)  # [3] -> [3, 1, 1]
        self.std = std.view(-1, 1, 1)

    def forward(self, img):
        return (img - self.mean) / self.std

定义网络,引入 loss

"modify to a style network"
def get_style_model_and_losses(cnn, normalization_mean, normalization_std,
                               style_img, content_img,
                               content_layers,
                               style_layers):
    cnn = copy.deepcopy(cnn)
    # normalization module
    normalization = Normalization(normalization_mean, normalization_std).to(device)

    # just in order to have an iterable acess to or list of content / style
    # losses
    content_losses = []
    style_losses = []

    # assuming that cnn is a nn.Sequantial, so we make a new nn.Sequential to put
    # in modules that are supposed to be activated sequantially
    model = nn.Sequential(normalization)

    i = 0  # increment every time we see a conv
    for layer in cnn.children():
        if isinstance(layer, nn.Conv2d):
            i += 1
            name = "conv_{}".format(i)
        elif isinstance(layer, nn.ReLU):
            name = "relu_{}".format(i)
            layer = nn.ReLU(inplace=False)
        elif isinstance(layer, nn.MaxPool2d):
            name = "pool_{}".format(i)
        elif isinstance(layer, nn.BatchNorm2d):
            name = "bn_{}".format(i)
        else:
            raise RuntimeError("Unrecognized layer: {}".format(layer.__class__.__name__))
        model.add_module(name, layer)

        if name in content_layers:
            # add content loss
            target = model(content_img).detach()
            content_loss = ContentLoss(target)
            model.add_module("content_loss_{}".format(i), content_loss)
            content_losses.append(content_loss)

        if name in style_layers:
            # add style loss
            target_feature = model(style_img).detach()
            style_loss = StyleLoss(target_feature)
            model.add_module("style_loss_{}".format(i), style_loss)
            style_losses.append(style_loss)

    # now we trim off the layers afater the last content and style losses
    for i in range(len(model)-1, -1, -1):
        if isinstance(model[i], ContentLoss) or isinstance(model[i], StyleLoss):
            break
    model = model[:(i+1)]
    return model, style_losses, content_losses

def get_input_optimizer(input_img):
    optimizer = optim.LBFGS([input_img.requires_grad_()])
    return optimizer


def run_style_transfer(cnn, normalization_mean, normalization_std, content_img, style_img, input_img, content_layers,
                       style_layers, num_steps=50, style_weight=1000000, content_weight=1):
    print('Building the style transfer model..')
    model, style_losses, content_losses = get_style_model_and_losses(cnn, normalization_mean, normalization_std,
                                                                     style_img, content_img, content_layers,
                                                                     style_layers)
    optimizer = get_input_optimizer(input_img) # 网络不变,反向传播优化的是输入图片

    print('Optimizing..')
    run = [0]
    while run[0] <= num_steps:

        def closure():
            # correct the values of updated input image
            input_img.data.clamp_(0, 1)

            optimizer.zero_grad()
            model(input_img)  # 前向传播
            style_score = 0
            content_score = 0

            for sl in style_losses:
                style_score += sl.loss
            for cl in content_losses:
                content_score += cl.loss

            style_score *= style_weight
            content_score *= content_weight
            # loss为style loss 和 content loss的和
            loss = style_score + content_score
            loss.backward()  # 反向传播
            # 打印loss的变化情况
            run[0] += 1
            if run[0] % 50 == 0:
                print("run {}:".format(run))
                print('Style Loss : {:4f} Content Loss: {:4f}'.format(
                    style_score.item(), content_score.item()))
                print()

            return style_score + content_score

        # 进行参数优化
        optimizer.step(closure)

    # a last correction...
    # 数值范围的纠正, 使其范围在0-1之间
    input_img.data.clamp_(0, 1)

    return input_img

搭建完成,开始训练,仅优化更新 input image(get_input_optimizer),网络不更新

# 加载content image和style image
style_img,content_img = image_util(img_size=270, style_img="./style9.jpg", content_img="./content.jpg")  # [1, 3, 270, 270]
# input image使用content image
input_img = content_img.clone()
# 加载预训练好的模型
cnn = models.vgg19(pretrained=True).features.to(device).eval()
# 模型标准化的值
cnn_normalization_mean = torch.tensor([0.485, 0.456, 0.406]).to(device)
cnn_normalization_std = torch.tensor([0.229, 0.224, 0.225]).to(device)
# 定义要计算loss的层
content_layers_default = ['conv_4']
style_layers_default = ['conv_1', 'conv_2', 'conv_3', 'conv_4', 'conv_5']
# 模型进行计算
output = run_style_transfer(cnn, cnn_normalization_mean, cnn_normalization_std,
                            content_img, style_img, input_img,
                            content_layers=content_layers_default,
                            style_layers=style_layers_default,
                            num_steps=300, style_weight=100000, content_weight=1)


image = output.cpu().clone()
image = image.squeeze(0)  # ([1, 3, 270, 270] -> [3, 270, 270])
unloader = transforms.ToPILImage()
image = unloader(image)
import cv2
image = cv2.cvtColor(np.asarray(image), cv2.COLOR_RGB2BGR)
cv2.imwrite("t9.jpg", image)
torch.cuda.empty_cache()

"""VGG-19
Sequential(
  (0): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (1): ReLU(inplace=True)
  (2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (3): ReLU(inplace=True)
  (4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (5): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (6): ReLU(inplace=True)
  (7): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (8): ReLU(inplace=True)
  (9): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (10): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (11): ReLU(inplace=True)
  (12): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (13): ReLU(inplace=True)
  (14): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (15): ReLU(inplace=True)
  (16): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (17): ReLU(inplace=True)
  (18): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (19): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (20): ReLU(inplace=True)
  (21): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (22): ReLU(inplace=True)
  (23): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (24): ReLU(inplace=True)
  (25): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (26): ReLU(inplace=True)
  (27): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (28): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (29): ReLU(inplace=True)
  (30): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (31): ReLU(inplace=True)
  (32): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (33): ReLU(inplace=True)
  (34): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (35): ReLU(inplace=True)
  (36): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
"""


"""modify name, add loss layer
Sequential(
  (0): Normalization()
  (conv_1): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (style_loss_1): StyleLoss()
  (relu_1): ReLU()
  (conv_2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (style_loss_2): StyleLoss()
  (relu_2): ReLU()
  (pool_2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv_3): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (style_loss_3): StyleLoss()
  (relu_3): ReLU()
  (conv_4): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (content_loss_4): ContentLoss()
  (style_loss_4): StyleLoss()
  (relu_4): ReLU()
  (pool_4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv_5): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (style_loss_5): StyleLoss()
  (relu_5): ReLU()
  (conv_6): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (relu_6): ReLU()
  (conv_7): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (relu_7): ReLU()
  (conv_8): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (relu_8): ReLU()
  (pool_8): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv_9): Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (relu_9): ReLU()
  (conv_10): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (relu_10): ReLU()
  (conv_11): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (relu_11): ReLU()
  (conv_12): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (relu_12): ReLU()
  (pool_12): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv_13): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (relu_13): ReLU()
  (conv_14): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (relu_14): ReLU()
  (conv_15): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (relu_15): ReLU()
  (conv_16): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (relu_16): ReLU()
  (pool_16): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
)
"""


"""after trim
Sequential(
  (0): Normalization()
  (conv_1): Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (style_loss_1): StyleLoss()
  (relu_1): ReLU()
  (conv_2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (style_loss_2): StyleLoss()
  (relu_2): ReLU()
  (pool_2): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv_3): Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (style_loss_3): StyleLoss()
  (relu_3): ReLU()
  (conv_4): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (content_loss_4): ContentLoss()
  (style_loss_4): StyleLoss()
  (relu_4): ReLU()
  (pool_4): MaxPool2d(kernel_size=2, stride=2, padding=0, dilation=1, ceil_mode=False)
  (conv_5): Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
  (style_loss_5): StyleLoss()
)
"""

原图,花宝叽

在这里插入图片描述
不同风格

在这里插入图片描述
产生的结果

在这里插入图片描述

更直观的展示

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1245150.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Peter算法小课堂—前缀和数组的应用

桶 相当于计数排序&#xff0c;看一个视频 桶排序 太戈编程1620题 算法解析 #include <bits/stdc.h> using namespace std; const int R11; int cnt[R];//cnt[t]代表第t天新增几人 int s[R];//s[]数组是cnt[]数组的前缀和数组 int n,t; int main(){cin>>n;for(…

rabbitMQ发布确认-交换机不存在或者无法抵达队列的缓存处理

rabbitMQ在发送消息时&#xff0c;会出现交换机不存在&#xff08;交换机名字写错等消息&#xff09;&#xff0c;这种情况如何会退给生产者重新处理&#xff1f;【交换机层】 生产者发送消息时&#xff0c;消息未送达到指定的队列&#xff0c;如何消息回退&#xff1f; 核心&…

企业数字化转型的作用是什么?_光点科技

在当今快速变化的商业环境中&#xff0c;数字化转型已成为企业发展的重要策略。企业数字化转型指的是利用数字技术改造传统业务模式和管理方式&#xff0c;以提升效率、增强竞争力和创造新的增长机会。 提升运营效率&#xff1a;数字化转型通过引入自动化工具和智能系统&#x…

数据分析基础之《matplotlib(2)—折线图》

一、折线图绘制与保存图片 1、matplotlib.pyplot模块 matplotlib.pyplot包含了一系列类似于matlab的画图函数。它的函数作用于当前图形&#xff08;figure&#xff09;的当前坐标系&#xff08;axes&#xff09; import matplotlib.pyplot as plt 2、折线图绘制与显示 展示城…

基于springboot实现校园在线拍卖系统项目【项目源码】

基于springboot实现校园在线拍卖系统演示 Javar技术 JavaScript是一种网络脚本语言&#xff0c;广泛运用于web应用开发&#xff0c;可以用来添加网页的格式动态效果&#xff0c;该语言不用进行预编译就直接运行&#xff0c;可以直接嵌入HTML语言中&#xff0c;写成js语言&…

ubuntu22.04安装wvp-gb28181-pro 2023-11-23最新版本(一键安装)

下载程序 输入下面命令&#xff0c;输入普通用户密码&#xff0c;切换到 root用户 sudo su git clone -b ubuntu_wvp_online_install_2023_0425 https://gitcode.net/zenglg/ubuntu_wvp_online_install.git 等待下载完成 安装 进入到克隆下来的路径中 cd /home/tuners/ub…

HTTPS攻击怎么防御?

HTTPS 简介 超文本传输安全协议&#xff08; HTTPS &#xff09;是一种通过计算机网络进行安全通信的传输协议。HTTPS 经由 HTTP 进行通信&#xff0c;但利用 SSL/TLS 来加密数据包。 HTTPS 开发的主要目的&#xff0c;是提供对网站服务器的身份认证&#xff0c;保护交换数据的…

搭配:基于OpenCV的边缘检测实战

引言 计算机中的目标检测与人类识别物体的方式相似。作为人类&#xff0c;我们可以分辨出狗的形象&#xff0c;因为狗的特征是独特的。尾巴、形状、鼻子、舌头等特征综合在一起&#xff0c;帮助我们把狗和牛区分开来。 同样&#xff0c;计算机能够通过检测与估计物体的结构和性…

掌握未来技术趋势,成为领先者——深度解析2023年技术热点

掌握未来技术趋势&#xff0c;成为领先者——深度解析2023年技术热点 摘要&#xff1a;本文探讨当前最热门的技术趋势。我们将介绍人工智能、大数据、区块链、5G等前沿技术&#xff0c;并阐述它们如何改变我们的生活。最后&#xff0c;我们将总结如何利用这些技术趋势&#xf…

罗拉ROLA分析亚马逊频繁扫号下的跨境电商,跨境电商卖家应该何去何从?

相信各位同行都知道&#xff0c;自2021年起&#xff0c;亚马逊的扫号活动就从未间断&#xff0c;直到如今2023年的亚马逊&#xff0c;仍然是隔2周-几个月就有大规模的审核扫号&#xff0c;大批卖家店铺被封&#xff0c;亚马逊卖家人人自危&#xff0c;面对时间间隔短频率高的扫…

【数据结构】树如何定义 | 如何存储 | 实际应用

前言 如上图&#xff0c;A中的孩子的个数是不固定的。我们无法精确的每个不同的根结点有多少个孩子。所以并不能精确知道需要定义多少个孩子节点。 struct TreeNode {int val;struct TreeNode* child1;struct TreeNode* child2;struct TreeNode* child3;//...//这样显然是不能…

C语言数组的距离(ZZULIOJ1200:数组的距离)

题目描述 已知元素从小到大排列的两个数组x[]和y[]&#xff0c; 请写出一个程序算出两个数组彼此之间差的绝对值中最小的一个&#xff0c;这叫做数组的距离 。 输入&#xff1a;第一行为两个整数m, n(1≤m, n≤1000)&#xff0c;分别代表数组f[], g[]的长度。第二行有m个元素&a…

2023年【四川省安全员B证】找解析及四川省安全员B证作业模拟考试

题库来源&#xff1a;安全生产模拟考试一点通公众号小程序 四川省安全员B证找解析是安全生产模拟考试一点通总题库中生成的一套四川省安全员B证作业模拟考试&#xff0c;安全生产模拟考试一点通上四川省安全员B证作业手机同步练习。2023年【四川省安全员B证】找解析及四川省安…

mac电脑系统活动监控:iStat Menus 中文 for Mac

iStat Menus是一款Mac操作系统上的系统监控工具&#xff0c;它提供了实时的系统状态和性能数据&#xff0c;让用户可以方便地监控和管理自己的电脑。iStat Menus以菜单栏图标的形式显示各种系统指标&#xff0c;用户可以轻松访问和查看这些信息。 以下是iStat Menus软件的一些…

AI实景无人直播源码开发揭秘--SaaS

AI实景无人直播系统是指由技术人员基于无人直播平台开发创建的源代码&#xff0c;核心功能设计包含&#xff1a;实景无人直播&#xff0c;评论实时互动&#xff0c;视频流处理&#xff0c;话术库&#xff0c;语音库等&#xff0c; 无人直播源码模块包含 以下常见模块&#xf…

跨境电商的微商业务:个人品牌的成功之路

随着互联网的发展&#xff0c;跨境电商行业迅猛崛起&#xff0c;微商业务作为其中的一种新型销售模式也逐渐崭露头角。微商业务以低成本、高灵活性的特点&#xff0c;为个人品牌的成功之路开辟了新的可能性。 本文将深入研究跨境电商微商业务&#xff0c;探讨在这个领域中个人…

GPT、GPT-2、GPT-3论文精读笔记

视频&#xff1a;GPT&#xff0c;GPT-2&#xff0c;GPT-3 论文精读【论文精读】_哔哩哔哩_bilibili MAE论文&#xff1a;把bert用回计算机视觉领域 CLIP论文&#xff1a;打通文本和图像 GPT 论文&#xff1a;Improving Language Understanding by Generative Pre-Training …

如何开启MySQL的慢查询日志

说明&#xff1a;如果需要查看某一条SQL查询速度慢&#xff0c;并对慢的SQL进行优化&#xff0c;那么开启MySQL慢查询日志是一定要做的事情&#xff0c;本文介绍如何开启MySQL的慢查询日志&#xff1b; 查看MySQL慢查询是否开启 首先&#xff0c;输入下面的命令&#xff0c;查…

Qt/QML编程学习之心得:一个Qt工程的学习笔记(九)

1、.pro文件 加CONFIG += c++11,才可以使用Lamda表达式(一般用于connect的内嵌槽函数) 2、QWidget 这是Qt新增加的一个类,基类,窗口类,QMainWindow和QDialog都继承与它。 3、Main函数 QApplication a应用程序对象,有且仅有一个 a.exec() 进行消息循环、阻塞 MyWi…

快速入门go语言学习笔记

文章目录 1、初识go1.1、go语言1.2 第一个Go程序 2、基础类型2.1、命名2.2、变量2.2.1 变量声明2.2.2 变量初始化2.2.3 变量赋值2.2.4 匿名变量 2.3、常量2.3.1 字面常量(常量值)2.3.2 常量定义2.3.3 iota枚举 2.4、基础数据类型2.4.1 分类2.4.2 布尔类型2.4.3 整型2.4.4 浮点型…