Torch7学习(七)——Neural-Style代码解析

AI权益加码!Claude Code、Cursor等20+工具免费用! 购周边限时加赠Coding Plan Lite,畅享主流AI工具!学习进阶更高效! 阅读详情

torch7学习(一)——Tensor
Torch7学习(二) —— Torch与Matlab的语法对比
Torch7学习(三)——学习神经网络包的用法(1)
Torch7学习(四)——学习神经网络包的用法(2)
Torch7学习(五)——学习神经网路包的用法(3)
Torch7学习(六)——学习神经网络包的用法(4)——利用optim进行训练
Torch7学习(七)——Neural-Style代码解析

Neural-style用的可能是最容易入门的代码之一吧。比较简单,写的很清晰。只涉及到最简单的网络构建方式,同时也是最基本最重要的写法。直接看neural-style的代码吧。代码附有大量的注释,而在最后也有一定的分析。
值得注意的是,最新的该论文的代码已经是多GPU版本的了。可以指定不同层放入不同的GPU进行训练。,主要是加入了 Controlling Perceptual Factors in Neural Style Transfer代码的支持。个人觉得下面的版本比较简单,看懂了再看最新的版本的吧。https://github.com/jcjohnson/neural-style

代码

require 'torch'
require 'nn'
require 'image'
require 'optim'

require 'loadcaffe'

--------------------------------------------------------------------------------

local cmd = torch.CmdLine()

-- Basic options
cmd:option('-style_image', 'examples/inputs/starry_night.jpg',
           'Style target image')
cmd:option('-style_blend_weights', 'nil')
cmd:option('-content_image', 'examples/inputs/5.jpg',
           'Content target image')
cmd:option('-image_size', 512, 'Maximum height / width of generated image')
cmd:option('-gpu', 0, 'Zero-indexed ID of the GPU to use; for CPU mode set -gpu = -1')

-- Optimization options
cmd:option('-content_weight', 5e0)
cmd:option('-style_weight', 1e2)
cmd:option('-tv_weight', 1e-3)
cmd:option('-num_iterations', 1000)
cmd:option('-normalize_gradients', false)
cmd:option('-init', 'random', 'random|image')
cmd:option('-optimizer', 'lbfgs', 'lbfgs|adam')
cmd:option('-learning_rate', 1e1)

-- Output options
cmd:option('-print_iter', 50)
cmd:option('-save_iter', 100)
cmd:option('-output_image', 'out.png')

-- Other options
cmd:option('-style_scale', 1.0)
cmd:option('-pooling', 'max', 'max|avg')
cmd:option('-proto_file', 'models/VGG_ILSVRC_19_layers_deploy.prototxt')
cmd:option('-model_file', 'models/VGG_ILSVRC_19_layers.caffemodel')
cmd:option('-backend', 'nn', 'nn|cudnn|clnn')
cmd:option('-cudnn_autotune', false)
cmd:option('-seed', -1)

cmd:option('-content_layers', 'relu4_2', 'layers for content')
cmd:option('-style_layers', 'relu1_1,relu2_1,relu3_1,relu4_1,relu5_1', 'layers for style')

local function main(params)
  if params.gpu >= 0 then
    if params.backend ~= 'clnn' then
      require 'cutorch'
      require 'cunn'
      cutorch.setDevice(params.gpu + 1)
    else
      require 'clnn'
      require 'cltorch'
      cltorch.setDevice(params.gpu + 1)
    end
  else
    params.backend = 'nn'
  end

  if params.backend == 'cudnn' then
    require 'cudnn'
    if params.cudnn_autotune then
      cudnn.benchmark = true
    end
    cudnn.SpatialConvolution.accGradParameters = nn.SpatialConvolutionMM.accGradParameters -- ie: nop
  end

  local loadcaffe_backend = params.backend
  if params.backend == 'clnn' then loadcaffe_backend = 'nn' end
  local cnn = loadcaffe.load(params.proto_file, params.model_file, loadcaffe_backend):float()
  if params.gpu >= 0 then
    if params.backend ~= 'clnn' then
      cnn:cuda()
    else
      cnn:cl()
    end
  end

  local content_image = image.load(params.content_image, 3)
  content_image = image.scale(content_image, params.image_size, 'bilinear')
  local content_image_caffe = preprocess(content_image):float()

  local style_size = math.ceil(params.style_scale * params.image_size)
  local style_image_list = params.style_image:split(',')
  local style_images_caffe = {}
  for _, img_path in ipairs(style_image_list) do
    local img = image.load(img_path, 3)
    img = image.scale(img, style_size, 'bilinear')
    local img_caffe = preprocess(img):float()
    table.insert(style_images_caffe, img_caffe)
  end

  -- Handle style blending weights for multiple style inputs
  local style_blend_weights = nil
  if params.style_blend_weights == 'nil' then
    -- Style blending not specified, so use equal weighting
    style_blend_weights = {}
    -- #表示长度
    for i = 1, #style_image_list do
      table.insert(style_blend_weights, 1.0)
    end
  else
    style_blend_weights = params.style_blend_weights:split(',')
    assert(#style_blend_weights == #style_image_list,
      '-style_blend_weights and -style_images must have the same number of elements')
  end
  -- Normalize the style blending weights so they sum to 1
  local style_blend_sum = 0
  for i = 1, #style_blend_weights do
    style_blend_weights[i] = tonumber(style_blend_weights[i])
    style_blend_sum = style_blend_sum + style_blend_weights[i]
  end
  for i = 1, #style_blend_weights do
    style_blend_weights[i] = style_blend_weights[i] / style_blend_sum
  end


  if params.gpu >= 0 then
    if params.backend ~= 'clnn' then
      content_image_caffe = content_image_caffe:cuda()
      for i = 1, #style_images_caffe do
        style_images_caffe[i] = style_images_caffe[i]:cuda()
      end
    else
      content_image_caffe = content_image_caffe:cl()
      for i = 1, #style_images_caffe do
        style_images_caffe[i] = style_images_caffe[i]:cl()
      end
    end
  end

  local content_layers = params.content_layers:split(",")
  local style_layers = params.style_layers:split(",")

  -- Set up the network, inserting style and content loss modules
  local content_losses, style_losses = {}, {}
  local next_content_idx, next_style_idx = 1, 1
  local net = nn.Sequential()
  if params.tv_weight > 0 then
    local tv_mod = nn.TVLoss(params.tv_weight):float()
    if params.gpu >= 0 then
      if params.backend ~= 'clnn' then
        tv_mod:cuda()
      else
        tv_mod:cl()
      end
    end
    net:add(tv_mod)
  end
  for i = 1, #cnn do
    if next_content_idx <= #content_layers or next_style_idx <= #style_layers then
      local layer = cnn:get(i)
      local name = layer.name
      local layer_type = torch.type(layer)
      local is_pooling = (layer_type == 'cudnn.SpatialMaxPooling' or layer_type == 'nn.SpatialMaxPooling')
      if is_pooling and params.pooling == 'avg' then
        assert(layer.padW == 0 and layer.padH == 0)
        local kW, kH = layer.kW, layer.kH
        local dW, dH = layer.dW, layer.dH
        local avg_pool_layer = nn.SpatialAveragePooling(kW, kH, dW, dH):float()
        if params.gpu >= 0 then
          if params.backend ~= 'clnn' then
            avg_pool_layer:cuda()
          else
            avg_pool_layer:cl()
          end
        end
        local msg = 'Replacing max pooling at layer %d with average pooling'
        print(string.format(msg, i))
        net:add(avg_pool_layer)
      else
        -- 如果不是pooling层,直接add这一层
        net:add(layer)
      end
      if name == content_layers[next_content_idx] then
        print("Setting up content layer", i, ":", layer.name)
        -- 如果这一层是content的话,那么就要加入loss_module,而loss_module则需要:content_weight, target, norm来进行初始化类。
        -- target就是“输入”经过前面网络所有层得到的输出。因此target = net:forward(content_image_caffe):clone.
        local target = net:forward(content_image_caffe):clone()
        local norm = params.normalize_gradients
        local loss_module = nn.ContentLoss(params.content_weight, target, norm):float()
        if params.gpu >= 0 then
          if params.backend ~= 'clnn' then
            loss_module:cuda()
          else
            loss_module:cl()
          end
        end
        net:add(loss_module)
        table.insert(content_losses, loss_module)
        next_content_idx = next_content_idx + 1
      end

      if name == style_layers[next_style_idx] then
        print("Setting up style layer  ", i, ":", layer.name)
        local gram = GramMatrix():float()
        if params.gpu >= 0 then
          if params.backend ~= 'clnn' then
            gram = gram:cuda()
          else
            gram = gram:cl()
          end
        end
        local target = nil
        -- style_images_caffe是众多style_images的Tensor组成的table。
        -- 因此要将每个style_images_caffe[i]送入net中得到相应的输出。每个输出要经过gram处理,
        -- 得到相应的grams值,每张style图片所附的权值得到target
        for i = 1, #style_images_caffe do
          local target_features = net:forward(style_images_caffe[i]):clone()
          local target_i = gram:forward(target_features):clone()
          target_i:div(target_features:nElement())
          target_i:mul(style_blend_weights[i])
          if i == 1 then
            target = target_i
          else
            target:add(target_i)
          end
        end

        local norm = params.normalize_gradients
        local loss_module = nn.StyleLoss(params.style_weight, target, norm):float()
        if params.gpu >= 0 then
          if params.backend ~= 'clnn' then
            loss_module:cuda()
          else
            loss_module:cl()
          end
        end
        net:add(loss_module)
        table.i
Neural Style论文笔记+源码解析 引言前面在Ubuntu16.04+GTX1080配置TensorFlow并实现图像风格转换中介绍了TensorFlow的配置过程,以及运用TensorFlow实现图像风格转换,主要是使用了文章A Neural Algorithm of Artistic Style中的方法,今天,我将主要对这篇文章进行解读,并对基于TensorFlow版本的Neural Style开源代码进行解析 阅读详情

相关推荐

Neural Style Transfer实战指南:用Python零训练实现艺术风格迁移

神经风格迁移(Neural Style Transfer)是一种将内容图像与风格图像融合生成新视觉作品的技术,其核心在于利用预训练卷积神经网络(如VGG-19)分层提取语义内容与纹理统计特征,并通过Gram矩阵量化风格。该技术无需训练模型、不依赖配对数据,具备原理透明、结果可控、部署轻量等工程优势,广泛应用于设计提案生成、数字内容统一调性、美术教育可视化及创意编程教学等场景。结合Python生态工具(如neural-style-pt),开发者可在CPU环境快速完成端到端迁移,真正实现‘所见即所得’的艺术语法

weixin_34321753的博客 337

使用Neural-Style做图片神经风格迁移

一、缘起 这两天在设计一个网页,需要使用同一风格的图片来渲染氛围,当然作为一只懒狗是懒得动手一张一张画的,于是就想到了风格迁移,找了下GitHub,发现了Neural-Style这个项目,就决定是它了! 这张是官方的例子,更多请移步原项目 二、安装 该项目是基于Leon A. Gatys, Alexander S. Ecker, 和 Matthias Bethge撰写的论文《A Neural Algorithm of Artistic Style》论文,使用lua语言基于torch实现的,所以在安装之前首

N0us的博客 929

neural-style风格迁移模型实战

有没有想过,利用机器学习来画画,今天,我将手把手带大家进入深度学习模型neural style代码实战当中。 neural-style模型是一个风格迁移的模型,是GitHub上一个超棒的项目,那么什么是风格迁移,我们来举一个简单的例子: 这里,我选择了将梵高的画风和我们的东北大学的工学馆相结合,让工学馆融入了梵高的星空效果图,在经过100次的迭代后得到了带有星空效果的图片。 另外我们...

Exploer_TRY的博客 7055

9.11_neural-style

如果你是一位摄影爱好者,也许接触过滤镜。它能改变照片的颜色样式,从而使风景照更加锐利或者令人像更加美白。但一个滤镜通常只能改变照片的某个方面。如果要照片达到理想中的样式,经常需要尝试大量不同的组合,其复杂程度不亚于模型调参。在本节中,我们将介绍如何使用卷积神经网络自动将某图像中的样式应用在另一图像之上,即样式迁移(style transfer)[1]。这里我们需要两张输入图像,一张是内容图像,另一张是样式图像,我们将使用神经网络修改内容图像使其在样式上接近样式图像。图9.12中的内容图像为本书作者在西雅图郊

taifyang的博客 464

PyTorch—之Neural-Style

实现由 Leon A. Gatys,Alexander S. Ecker和Matthias Bethge提出的Neural-Style 算法。Neural-Style 或者叫 Neural-Transfer,可以让你使用一种新的风格将指定的图片进行重构。 这个算法使用三张图片,一张输入图片,一张内容图片和一张风格图片,并将输入的图片变得与内容图片相似,且拥有风格图片的优美风格。 定义两个间距,一个...

红叶谷 wsp_1138886114的博客 935

在Docker中运行torch版的neural style

相关的代码都在Github上,请参见我的Github,https://github.com/lijingpeng/deep-learning-notes 敬请多多关注哈~~~在Docker中运行torch版的neural styleTensorFlow neural-style, TensorFlow版本的实现比Torch版本的实现要慢很多,因此本文介绍如何运行torch版本的neural sty

lijingpeng的专栏 1631

如何快速安装neural-style:Ubuntu环境配置详细步骤

想要体验AI艺术风格迁移的神奇魅力吗?neural-style是一个基于Torch7实现的深度学习项目,能够将一幅图片的内容与另一幅图片的艺术风格完美融合。本文将为你提供在Ubuntu系统上快速安装和配置neural-style的完整指南,让你轻松开启AI艺术创作之旅! ## 🚀 前置环境准备 在开始安装neural-style之前,确保你的Ubuntu系统已经更新到最新状态: ```ba

gitblog_00555的博客 773

探索neural-style:基于Torch的艺术风格迁移算法实现

探索neural-style:基于Torch的艺术风格迁移算法实现 【免费下载链接】neural-style Torch implementation of neural style algorithm 项目地址: https:/...

gitblog_00054的博客 557

CNNMRF与Neural Style对比:为什么马尔可夫随机场是图像合成的更好选择?

CNNMRF(Combining Markov Random Fields and Convolutional Neural Networks for Image Synthesis)是一个创新的图像合成项目,它巧妙融合马尔可夫随机场(MRF)与卷积神经网络(CNN)的优势,为图像合成领域带来了更卓越的解决方案。相比传统的Neural Style方法,CNNMRF在保持内容结构、提升风格迁移质量以

gitblog_00674的博客 710

风格迁移-fast-neural-style-tensorflow 代码阅读及注释

风格迁移-fast-neural-style-tensorflow 代码阅读及注释 标签: Tensorflow 这篇文章主要是记录在使用及阅读fast-neural-style-tensorflow代码时候的一些疑虑的解决,也可以看做是把fast-neural-style-tensorflow做一个精简化,因为虽然fast-neural-style-tensorflow给出了源代码,但是对于初...

CoderWangSon 3452

Neural Style学习2——环境安装

neural-style Installation This guide will walk you through the setup for neural-style on Ubuntu. Step 1: Install torch7 First we need to install torch, following the installation instructions here: # ...

weixin_34337381的博客 206

neural-style社区贡献指南:如何参与开源项目开发与改进

欢迎来到neural-style社区贡献指南!neural-style是一个基于Torch实现的神经风格迁移算法项目,它能够将一张图片的艺术风格应用到另一张图片的内容上,创造出令人惊艳的艺术效果。🎨 作为开源社区的一员,你的参与将对项目的发展起到重要作用。 ## 📋 如何开始贡献代码 首先克隆项目仓库到本地: ```bash git clone https://gitcode.com/gh

gitblog_00311的博客 951

opencv dnn模块 示例(12) 图像风格化 style transfer

opencv dnn模块图像风格化转换,使用fast-neural-style.

热爱生活,忠于自己 1906

神经网络风格画 Neural Style Art

前言 Neural Style 项目 项目部署前准备 Windws下载VM中安装Ubuntu VM中Ubuntu的网络配置 项目部署安装说明 确认部署的Linux机器拥有git和cmake 步骤一Install torch7 步骤二安装loadcaffe 步骤三安装neural-style 克隆项目 下载模型 CPU模式下运行测试 测试输出解释 GPU模式下运行前言博主看到了一篇知乎上有关于代码实现

dj741的博客 2714

**神经风格迁移:jcjohnson/neural-style深度解析与实践**

神经风格迁移:jcjohnson/neural-style深度解析与实践 【免费下载链接】neural-style Torch implementation of neural style algorithm 项目地址: http...

gitblog_00872的博客 358

PyTorch 进行神经风格迁移neural style tutorial

要查看带有配图的文章内容,请前往 http://studyai.com/pytorch-1.4/advanced/neural_style_tutorial.html 本教程介绍了如何实现由Leon A.Gatys开发的 Neural-Style algorithm 。 Neural-Style, 或 Neural-Transfer, 允许你对一幅图像采取一种新的艺术风格的形象和再现。 该算法接受...

海尔兄弟的博客 539

创意无限的艺术转换神器:neural-style 开源项目探秘

创意无限的艺术转换神器:neural-style 开源项目探秘 【免费下载链接】neural-style Torch implementation of neural style algorithm 项目地址: https://g...

gitblog_00229的博客 535

neural-style高级技巧:多重风格混合与插值创作指南

想要将梵高的星夜与蒙克的呐喊风格完美融合?neural-style项目为您提供了强大的多重风格混合与插值功能!这款基于Torch实现的神经风格迁移工具,让您能够轻松创作出独一无二的艺术作品。 ## 🎨 多重风格混合的基本原理 neural-style通过深度卷积神经网络分析图像的风格特征,使用Gram矩阵捕捉纹理信息,并将多个风格图像的纹理特征进行加权融合。在[neural_style.lu

gitblog_00903的博客 513
上一篇: Torch7学习(六)——学习神经网络包的用法(4)——利用optim进行训练
下一篇: Tensorflow学习初探
Hungryof
博客等级 码龄12年 776粉丝 130原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值