[
  {
    "path": "Dockerfile",
    "content": "FROM nvidia/cuda:9.0-cudnn7-devel\n\n# Install system dependencies\nRUN apt-get update \\\n    && DEBIAN_FRONTEND=noninteractive apt-get install -y \\\n        build-essential \\\n        curl \\\n        git \\\n    && apt-get clean\n\n# Install python miniconda3 + requirements\nENV MINICONDA_HOME=\"/opt/miniconda\"\nENV PATH=\"${MINICONDA_HOME}/bin:${PATH}\"\nRUN curl -o Miniconda3-latest-Linux-x86_64.sh https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh \\\n    && chmod +x Miniconda3-latest-Linux-x86_64.sh \\\n    && ./Miniconda3-latest-Linux-x86_64.sh -b -p \"${MINICONDA_HOME}\" \\\n    && rm Miniconda3-latest-Linux-x86_64.sh\nCOPY environment.yml environment.yml\nRUN conda env update -n=root --file=environment.yml\nRUN conda clean -y -i -l -p -t && \\\n    rm environment.yml\n\n# Clone deep image prior repository\nRUN git clone https://github.com/DmitryUlyanov/deep-image-prior.git\nWORKDIR /deep-image-prior\n\n# Start container in notebook mode\nCMD jupyter notebook --ip=\"*\" --no-browser --allow-root\n\n"
  },
  {
    "path": "LICENSE",
    "content": "Apache License 2.0\n\nBut please contact me if you want to use this software in a commercial application. \n\nNote that Apache License 2.0 asks to include a copyright notice if you use this software. \n"
  },
  {
    "path": "README.md",
    "content": "**Warning!** The optimization may not converge on some GPUs. We've personnaly experienced issues on Tesla V100 and P40 GPUs. When running the code, make sure you get similar results to the paper first. Easiest to check using text inpainting notebook.  Try to set double precision mode or turn off cudnn. \n\n# Deep image prior\n\nIn this repository we provide *Jupyter Notebooks* to reproduce each figure from the paper:\n\n> **Deep Image Prior**\n\n> CVPR 2018\n\n> Dmitry Ulyanov, Andrea Vedaldi, Victor Lempitsky\n\n\n[[paper]](https://sites.skoltech.ru/app/data/uploads/sites/25/2018/04/deep_image_prior.pdf) [[supmat]](https://box.skoltech.ru/index.php/s/ib52BOoV58ztuPM) [[project page]](https://dmitryulyanov.github.io/deep_image_prior)\n\n![](data/teaser_compiled.jpg)\n\nHere we provide hyperparameters and architectures, that were used to generate the figures. Most of them are far from optimal. Do not hesitate to change them and see the effect.\n\nWe will expand this README with a list of hyperparameters and options shortly.\n\n# Install\n\nHere is the list of libraries you need to install to execute the code:\n- python = 3.6\n- [pytorch](http://pytorch.org/) = 0.4\n- numpy\n- scipy\n- matplotlib\n- scikit-image\n- jupyter\n\nAll of them can be installed via `conda` (`anaconda`), e.g.\n```\nconda install jupyter\n```\n\n## Docker image\n\nAlternatively, you can use a Docker image that exposes a Jupyter Notebook with all required dependencies. To build this image ensure you have both [docker](https://www.docker.com/) and  [nvidia-docker](https://github.com/NVIDIA/nvidia-docker) installed, then run\n\n```\nnvidia-docker build -t deep-image-prior .\n```\n\nAfter the build you can start the container as\n\n```\nnvidia-docker run --rm -it --ipc=host -p 8888:8888 deep-image-prior\n```\n\nyou will be provided an URL through which you can connect to the Jupyter notebook.\n\n\n# Citation\n```\n@article{UlyanovVL17,\n    author    = {Ulyanov, Dmitry and Vedaldi, Andrea and Lempitsky, Victor},\n    title     = {Deep Image Prior},\n    journal   = {arXiv:1711.10925},\n    year      = {2017}\n}\n```\n"
  },
  {
    "path": "activation_maximization.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Code for **\\\"Activation maximization\\\"** figure.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"You can select net type (`vgg_16_caffe`, `vgg19_caffe`, `alexnet`) and a layer. For your reference the layer names for each network type are shown below.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"vgg_19_names=['conv1_1','relu1_1','conv1_2','relu1_2','pool1',\\n\",\n    \"              'conv2_1','relu2_1','conv2_2','relu2_2','pool2',\\n\",\n    \"              'conv3_1','relu3_1','conv3_2','relu3_2','conv3_3','relu3_3','conv3_4','relu3_4','pool3',\\n\",\n    \"              'conv4_1','relu4_1','conv4_2','relu4_2','conv4_3','relu4_3','conv4_4','relu4_4','pool4',\\n\",\n    \"              'conv5_1','relu5_1','conv5_2','relu5_2','conv5_3','relu5_3','conv5_4','relu5_4','pool5',\\n\",\n    \"              'torch_view','fc6','relu6','drop6','fc7','relu7','drop7','fc8']\\n\",\n    \"\\n\",\n    \"vgg_16_names = ['conv1_1','relu1_1','conv1_2','relu1_2','pool1',\\n\",\n    \"                'conv2_1','relu2_1','conv2_2','relu2_2','pool2',\\n\",\n    \"                'conv3_1','relu3_1','conv3_2','relu3_2','conv3_3','relu3_3','pool3',\\n\",\n    \"                'conv4_1','relu4_1','conv4_2','relu4_2','conv4_3','relu4_3','pool4',\\n\",\n    \"                'conv5_1','relu5_1','conv5_2','relu5_2','conv5_3','relu5_3','pool5',\\n\",\n    \"                'torch_view','fc6','relu6','drop6','fc7','relu7','fc8']\\n\",\n    \"\\n\",\n    \"alexnet_names = ['conv1', 'relu1', 'norm1', 'pool1',\\n\",\n    \"                 'conv2', 'relu2', 'norm2', 'pool2',\\n\",\n    \"                 'conv3', 'relu3', 'conv4', 'relu4',\\n\",\n    \"                 'conv5', 'relu5', 'pool5', 'torch_view',\\n\",\n    \"                 'fc6', 'relu6', 'drop6',\\n\",\n    \"                 'fc7', 'relu7', 'drop7',\\n\",\n    \"                 'fc8', 'softmax']\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"The actual code starts here.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Import libs\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from __future__ import print_function\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"%matplotlib inline\\n\",\n    \"\\n\",\n    \"import argparse\\n\",\n    \"import os\\n\",\n    \"# os.environ['CUDA_VISIBLE_DEVICES'] = '3'\\n\",\n    \"\\n\",\n    \"import numpy as np\\n\",\n    \"from models import *\\n\",\n    \"\\n\",\n    \"import torch\\n\",\n    \"import torch.optim\\n\",\n    \"\\n\",\n    \"from utils.perceptual_loss.perceptual_loss import *\\n\",\n    \"from utils.common_utils import *\\n\",\n    \"\\n\",\n    \"torch.backends.cudnn.enabled = True\\n\",\n    \"torch.backends.cudnn.benchmark =True\\n\",\n    \"dtype = torch.cuda.FloatTensor\\n\",\n    \"\\n\",\n    \"PLOT = True\\n\",\n    \"fname = './data/feature_inversion/building.jpg'\\n\",\n    \"\\n\",\n    \"# Choose net type\\n\",\n    \"pretrained_net = 'alexnet_caffe' \\n\",\n    \"assert pretrained_net in ['alexnet_caffe', 'vgg19_caffe', 'vgg16_caffe']\\n\",\n    \"\\n\",\n    \"# Choose layers\\n\",\n    \"layer_to_use = 'conv4'\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"import json\\n\",\n    \"with open('data/imagenet1000_clsid_to_human.txt', 'r') as f:\\n\",\n    \"    corresp = json.load(f)\\n\",\n    \"    \\n\",\n    \"\\n\",\n    \"if layer_to_use == 'fc8':\\n\",\n    \"    # Choose class\\n\",\n    \"    name = 'black swan'\\n\",\n    \"    # name = 'cheeseburger'\\n\",\n    \"\\n\",\n    \"    map_idx = None\\n\",\n    \"    for k,v in corresp.items():\\n\",\n    \"        if name in v:\\n\",\n    \"            map_idx = int(k)\\n\",\n    \"            break\\n\",\n    \"else:\\n\",\n    \"    map_idx = 2 # Choose here\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Setup pretrained net\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Target imsize \\n\",\n    \"imsize = 227 if pretrained_net == 'alexnet_caffe' else 224\\n\",\n    \"\\n\",\n    \"# Something divisible by a power of two\\n\",\n    \"imsize_net = 256\\n\",\n    \"\\n\",\n    \"# VGG and Alexnet need input to be correctly normalized\\n\",\n    \"preprocess, deprocess = get_preprocessor(imsize), get_deprocessor()\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"img_content_pil, img_content_np  = get_image(fname, -1)\\n\",\n    \"img_content_prerocessed = preprocess(img_content_pil)[None,:].type(dtype)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"scrolled\": true\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"opt_content = {'layers': [layer_to_use], 'what':'features', 'map_idx': map_idx}\\n\",\n    \"\\n\",\n    \"cnn = get_pretrained_net(pretrained_net).type(dtype)\\n\",\n    \"cnn.add_module('softmax', nn.Softmax())\\n\",\n    \"\\n\",\n    \"# Remove the layers we don't need \\n\",\n    \"keys = [x for x in cnn._modules.keys()]\\n\",\n    \"max_idx = max(keys.index(x) for x in opt_content['layers'])\\n\",\n    \"for k in keys[max_idx+1:]:\\n\",\n    \"    cnn._modules.pop(k)\\n\",\n    \"    \\n\",\n    \"print(cnn)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"scrolled\": true\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"matcher_content = get_matcher(cnn, opt_content)\\n\",\n    \"matcher_content.mode = 'match'\\n\",\n    \"\\n\",\n    \"if layer_to_use == 'fc8':\\n\",\n    \"    matcher_content.mode = 'match'\\n\",\n    \"    LR = 0.01\\n\",\n    \"else:\\n\",\n    \"    \\n\",\n    \"    # Choose here\\n\",\n    \"    # Window size controls the width of the region where the activations are maximized\\n\",\n    \"    matcher_content.window_size = 20 # if = 1 then it is neuron maximization\\n\",\n    \"    matcher_content.method = 'maximize'\\n\",\n    \"    LR = 0.001\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Setup matcher and net\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"INPUT = 'noise'\\n\",\n    \"input_depth = 32\\n\",\n    \"OPTIMIZER = 'adam'\\n\",\n    \"net_input = get_noise(input_depth, INPUT, imsize_net).type(dtype).detach()\\n\",\n    \"OPT_OVER = 'net' #'net,input'\\n\",\n    \"pad='reflection'\\n\",\n    \"\\n\",\n    \"tv_weight=0.0\\n\",\n    \"reg_noise_std = 0.03\\n\",\n    \"param_noise = True\\n\",\n    \"num_iter = 3100\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"net = skip(input_depth, 3, num_channels_down = [16, 32, 64, 128, 128, 128],\\n\",\n    \"                           num_channels_up =   [16, 32, 64, 128, 128, 128],\\n\",\n    \"                           num_channels_skip = [0, 4, 4, 4, 4, 4],   \\n\",\n    \"                           filter_size_down = [5, 3, 5, 5, 3, 5], filter_size_up = [5, 3, 5, 3, 5, 3], \\n\",\n    \"                           upsample_mode='bilinear', downsample_mode='avg',\\n\",\n    \"                           need_sigmoid=True, pad=pad, act_fun='LeakyReLU').type(dtype)\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"# Compute number of parameters\\n\",\n    \"s  = sum(np.prod(list(p.size())) for p in net.parameters())\\n\",\n    \"print ('Number of params: %d' % s)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"net(net_input).shape\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### TV\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Uncomment this section if you do not wan to optimize over pixels with TV prior only.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# INPUT = 'noise'\\n\",\n    \"# input_depth = 3\\n\",\n    \"# net_input = (get_noise(input_depth, INPUT, imsize_net).type(dtype)+0.5).detach()\\n\",\n    \"\\n\",\n    \"# OPT_OVER = 'input' #'net,input'\\n\",\n    \"# net = nn.Sequential()\\n\",\n    \"# reg_noise_std =0.0\\n\",\n    \"# OPTIMIZER = 'adam'# 'LBFGS'\\n\",\n    \"# LR = 0.01\\n\",\n    \"# tv_weight=1e-6\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Optimize\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"mask = net_input.clone()[:,:3,:imsize,:imsize] * 0\\n\",\n    \"for i in range(imsize):\\n\",\n    \"    for j in range(imsize):\\n\",\n    \"        d = np.sqrt((i - imsize//2)**2 + (j - imsize//2)**2)\\n\",\n    \"#         if d > 75:\\n\",\n    \"        mask[:,:, i, j] = 1 - min(100./d, 1)\\n\",\n    \"            \\n\",\n    \"plot_image_grid([torch_to_np(mask)]);\\n\",\n    \"use_mask = False\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from utils.sr_utils import tv_loss\\n\",\n    \"\\n\",\n    \"net_input_saved = net_input.detach().clone()\\n\",\n    \"noise = net_input.detach().clone()\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"outs = [] \\n\",\n    \"\\n\",\n    \"def closure():\\n\",\n    \"    \\n\",\n    \"    global i, net_input\\n\",\n    \"    \\n\",\n    \"    if param_noise:\\n\",\n    \"        for n in [x for x in net.parameters() if len(x.size()) == 4]:\\n\",\n    \"            n = n + n.detach().clone().normal_() * n.std()/50\\n\",\n    \"    \\n\",\n    \"    net_input = net_input_saved\\n\",\n    \"    if reg_noise_std > 0:\\n\",\n    \"        net_input = net_input_saved + (noise.normal_() * reg_noise_std)\\n\",\n    \"\\n\",\n    \"    out = net(net_input)[:, :, :imsize, :imsize]\\n\",\n    \"    \\n\",\n    \"#     out = out* (1-mask)\\n\",\n    \"   \\n\",\n    \"        \\n\",\n    \"    cnn(vgg_preprocess_caffe(out))\\n\",\n    \"    total_loss =  sum(matcher_content.losses.values()) * 5\\n\",\n    \"    \\n\",\n    \"    if tv_weight > 0:\\n\",\n    \"        total_loss += tv_weight * tv_loss(vgg_preprocess_caffe(out), beta=2)\\n\",\n    \"        \\n\",\n    \"    \\n\",\n    \"    if use_mask:\\n\",\n    \"        total_loss += nn.functional.mse_loss(out * mask, mask * 0, size_average=False) * 1e1\\n\",\n    \"    \\n\",\n    \"    total_loss.backward()\\n\",\n    \"\\n\",\n    \"    print ('Iteration %05d    Loss %.3f' % (i, total_loss.item()), '\\\\r', end='')\\n\",\n    \"    if PLOT and  i % 100==0:\\n\",\n    \"        out_np = np.clip(torch_to_np(out), 0, 1)\\n\",\n    \"        plot_image_grid([out_np], 3, 3, interpolation='lanczos');\\n\",\n    \"        \\n\",\n    \"        outs.append(out_np)\\n\",\n    \"    i += 1\\n\",\n    \"    \\n\",\n    \"    return total_loss\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"i=0\\n\",\n    \"\\n\",\n    \"p = get_params(OPT_OVER, net, net_input)\\n\",\n    \"\\n\",\n    \"optimize(OPTIMIZER, p, closure, LR, num_iter)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Result\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"out = net(net_input)[:, :, :imsize, :imsize]\\n\",\n    \"plot_image_grid([torch_to_np(out)], 3, 3);\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.6.5\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
  },
  {
    "path": "data/imagenet1000_clsid_to_human.txt",
    "content": "{\"0\": \"tench, Tinca tinca\",\n \"1\": \"goldfish, Carassius auratus\",\n \"2\": \"great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias\",\n \"3\": \"tiger shark, Galeocerdo cuvieri\",\n \"4\": \"hammerhead, hammerhead shark\",\n \"5\": \"electric ray, crampfish, numbfish, torpedo\",\n \"6\": \"stingray\",\n \"7\": \"cock\",\n \"8\": \"hen\",\n \"9\": \"ostrich, Struthio camelus\",\n \"10\": \"brambling, Fringilla montifringilla\",\n \"11\": \"goldfinch, Carduelis carduelis\",\n \"12\": \"house finch, linnet, Carpodacus mexicanus\",\n \"13\": \"junco, snowbird\",\n \"14\": \"indigo bunting, indigo finch, indigo bird, Passerina cyanea\",\n \"15\": \"robin, American robin, Turdus migratorius\",\n \"16\": \"bulbul\",\n \"17\": \"jay\",\n \"18\": \"magpie\",\n \"19\": \"chickadee\",\n \"20\": \"water ouzel, dipper\",\n \"21\": \"kite\",\n \"22\": \"bald eagle, American eagle, Haliaeetus leucocephalus\",\n \"23\": \"vulture\",\n \"24\": \"great grey owl, great gray owl, Strix nebulosa\",\n \"25\": \"European fire salamander, Salamandra salamandra\",\n \"26\": \"common newt, Triturus vulgaris\",\n \"27\": \"eft\",\n \"28\": \"spotted salamander, Ambystoma maculatum\",\n \"29\": \"axolotl, mud puppy, Ambystoma mexicanum\",\n \"30\": \"bullfrog, Rana catesbeiana\",\n \"31\": \"tree frog, tree-frog\",\n \"32\": \"tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui\",\n \"33\": \"loggerhead, loggerhead turtle, Caretta caretta\",\n \"34\": \"leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea\",\n \"35\": \"mud turtle\",\n \"36\": \"terrapin\",\n \"37\": \"box turtle, box tortoise\",\n \"38\": \"banded gecko\",\n \"39\": \"common iguana, iguana, Iguana iguana\",\n \"40\": \"American chameleon, anole, Anolis carolinensis\",\n \"41\": \"whiptail, whiptail lizard\",\n \"42\": \"agama\",\n \"43\": \"frilled lizard, Chlamydosaurus kingi\",\n \"44\": \"alligator lizard\",\n \"45\": \"Gila monster, Heloderma suspectum\",\n \"46\": \"green lizard, Lacerta viridis\",\n \"47\": \"African chameleon, Chamaeleo chamaeleon\",\n \"48\": \"Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis\",\n \"49\": \"African crocodile, Nile crocodile, Crocodylus niloticus\",\n \"50\": \"American alligator, Alligator mississipiensis\",\n \"51\": \"triceratops\",\n \"52\": \"thunder snake, worm snake, Carphophis amoenus\",\n \"53\": \"ringneck snake, ring-necked snake, ring snake\",\n \"54\": \"hognose snake, puff adder, sand viper\",\n \"55\": \"green snake, grass snake\",\n \"56\": \"king snake, kingsnake\",\n \"57\": \"garter snake, grass snake\",\n \"58\": \"water snake\",\n \"59\": \"vine snake\",\n \"60\": \"night snake, Hypsiglena torquata\",\n \"61\": \"boa constrictor, Constrictor constrictor\",\n \"62\": \"rock python, rock snake, Python sebae\",\n \"63\": \"Indian cobra, Naja naja\",\n \"64\": \"green mamba\",\n \"65\": \"sea snake\",\n \"66\": \"horned viper, cerastes, sand viper, horned asp, Cerastes cornutus\",\n \"67\": \"diamondback, diamondback rattlesnake, Crotalus adamanteus\",\n \"68\": \"sidewinder, horned rattlesnake, Crotalus cerastes\",\n \"69\": \"trilobite\",\n \"70\": \"harvestman, daddy longlegs, Phalangium opilio\",\n \"71\": \"scorpion\",\n \"72\": \"black and gold garden spider, Argiope aurantia\",\n \"73\": \"barn spider, Araneus cavaticus\",\n \"74\": \"garden spider, Aranea diademata\",\n \"75\": \"black widow, Latrodectus mactans\",\n \"76\": \"tarantula\",\n \"77\": \"wolf spider, hunting spider\",\n \"78\": \"tick\",\n \"79\": \"centipede\",\n \"80\": \"black grouse\",\n \"81\": \"ptarmigan\",\n \"82\": \"ruffed grouse, partridge, Bonasa umbellus\",\n \"83\": \"prairie chicken, prairie grouse, prairie fowl\",\n \"84\": \"peacock\",\n \"85\": \"quail\",\n \"86\": \"partridge\",\n \"87\": \"African grey, African gray, Psittacus erithacus\",\n \"88\": \"macaw\",\n \"89\": \"sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita\",\n \"90\": \"lorikeet\",\n \"91\": \"coucal\",\n \"92\": \"bee eater\",\n \"93\": \"hornbill\",\n \"94\": \"hummingbird\",\n \"95\": \"jacamar\",\n \"96\": \"toucan\",\n \"97\": \"drake\",\n \"98\": \"red-breasted merganser, Mergus serrator\",\n \"99\": \"goose\",\n \"100\": \"black swan, Cygnus atratus\",\n \"101\": \"tusker\",\n \"102\": \"echidna, spiny anteater, anteater\",\n \"103\": \"platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus\",\n \"104\": \"wallaby, brush kangaroo\",\n \"105\": \"koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus\",\n \"106\": \"wombat\",\n \"107\": \"jellyfish\",\n \"108\": \"sea anemone, anemone\",\n \"109\": \"brain coral\",\n \"110\": \"flatworm, platyhelminth\",\n \"111\": \"nematode, nematode worm, roundworm\",\n \"112\": \"conch\",\n \"113\": \"snail\",\n \"114\": \"slug\",\n \"115\": \"sea slug, nudibranch\",\n \"116\": \"chiton, coat-of-mail shell, sea cradle, polyplacophore\",\n \"117\": \"chambered nautilus, pearly nautilus, nautilus\",\n \"118\": \"Dungeness crab, Cancer magister\",\n \"119\": \"rock crab, Cancer irroratus\",\n \"120\": \"fiddler crab\",\n \"121\": \"king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica\",\n \"122\": \"American lobster, Northern lobster, Maine lobster, Homarus americanus\",\n \"123\": \"spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish\",\n \"124\": \"crayfish, crawfish, crawdad, crawdaddy\",\n \"125\": \"hermit crab\",\n \"126\": \"isopod\",\n \"127\": \"white stork, Ciconia ciconia\",\n \"128\": \"black stork, Ciconia nigra\",\n \"129\": \"spoonbill\",\n \"130\": \"flamingo\",\n \"131\": \"little blue heron, Egretta caerulea\",\n \"132\": \"American egret, great white heron, Egretta albus\",\n \"133\": \"bittern\",\n \"134\": \"crane\",\n \"135\": \"limpkin, Aramus pictus\",\n \"136\": \"European gallinule, Porphyrio porphyrio\",\n \"137\": \"American coot, marsh hen, mud hen, water hen, Fulica americana\",\n \"138\": \"bustard\",\n \"139\": \"ruddy turnstone, Arenaria interpres\",\n \"140\": \"red-backed sandpiper, dunlin, Erolia alpina\",\n \"141\": \"redshank, Tringa totanus\",\n \"142\": \"dowitcher\",\n \"143\": \"oystercatcher, oyster catcher\",\n \"144\": \"pelican\",\n \"145\": \"king penguin, Aptenodytes patagonica\",\n \"146\": \"albatross, mollymawk\",\n \"147\": \"grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus\",\n \"148\": \"killer whale, killer, orca, grampus, sea wolf, Orcinus orca\",\n \"149\": \"dugong, Dugong dugon\",\n \"150\": \"sea lion\",\n \"151\": \"Chihuahua\",\n \"152\": \"Japanese spaniel\",\n \"153\": \"Maltese dog, Maltese terrier, Maltese\",\n \"154\": \"Pekinese, Pekingese, Peke\",\n \"155\": \"Shih-Tzu\",\n \"156\": \"Blenheim spaniel\",\n \"157\": \"papillon\",\n \"158\": \"toy terrier\",\n \"159\": \"Rhodesian ridgeback\",\n \"160\": \"Afghan hound, Afghan\",\n \"161\": \"basset, basset hound\",\n \"162\": \"beagle\",\n \"163\": \"bloodhound, sleuthhound\",\n \"164\": \"bluetick\",\n \"165\": \"black-and-tan coonhound\",\n \"166\": \"Walker hound, Walker foxhound\",\n \"167\": \"English foxhound\",\n \"168\": \"redbone\",\n \"169\": \"borzoi, Russian wolfhound\",\n \"170\": \"Irish wolfhound\",\n \"171\": \"Italian greyhound\",\n \"172\": \"whippet\",\n \"173\": \"Ibizan hound, Ibizan Podenco\",\n \"174\": \"Norwegian elkhound, elkhound\",\n \"175\": \"otterhound, otter hound\",\n \"176\": \"Saluki, gazelle hound\",\n \"177\": \"Scottish deerhound, deerhound\",\n \"178\": \"Weimaraner\",\n \"179\": \"Staffordshire bullterrier, Staffordshire bull terrier\",\n \"180\": \"American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier\",\n \"181\": \"Bedlington terrier\",\n \"182\": \"Border terrier\",\n \"183\": \"Kerry blue terrier\",\n \"184\": \"Irish terrier\",\n \"185\": \"Norfolk terrier\",\n \"186\": \"Norwich terrier\",\n \"187\": \"Yorkshire terrier\",\n \"188\": \"wire-haired fox terrier\",\n \"189\": \"Lakeland terrier\",\n \"190\": \"Sealyham terrier, Sealyham\",\n \"191\": \"Airedale, Airedale terrier\",\n \"192\": \"cairn, cairn terrier\",\n \"193\": \"Australian terrier\",\n \"194\": \"Dandie Dinmont, Dandie Dinmont terrier\",\n \"195\": \"Boston bull, Boston terrier\",\n \"196\": \"miniature schnauzer\",\n \"197\": \"giant schnauzer\",\n \"198\": \"standard schnauzer\",\n \"199\": \"Scotch terrier, Scottish terrier, Scottie\",\n \"200\": \"Tibetan terrier, chrysanthemum dog\",\n \"201\": \"silky terrier, Sydney silky\",\n \"202\": \"soft-coated wheaten terrier\",\n \"203\": \"West Highland white terrier\",\n \"204\": \"Lhasa, Lhasa apso\",\n \"205\": \"flat-coated retriever\",\n \"206\": \"curly-coated retriever\",\n \"207\": \"golden retriever\",\n \"208\": \"Labrador retriever\",\n \"209\": \"Chesapeake Bay retriever\",\n \"210\": \"German short-haired pointer\",\n \"211\": \"vizsla, Hungarian pointer\",\n \"212\": \"English setter\",\n \"213\": \"Irish setter, red setter\",\n \"214\": \"Gordon setter\",\n \"215\": \"Brittany spaniel\",\n \"216\": \"clumber, clumber spaniel\",\n \"217\": \"English springer, English springer spaniel\",\n \"218\": \"Welsh springer spaniel\",\n \"219\": \"cocker spaniel, English cocker spaniel, cocker\",\n \"220\": \"Sussex spaniel\",\n \"221\": \"Irish water spaniel\",\n \"222\": \"kuvasz\",\n \"223\": \"schipperke\",\n \"224\": \"groenendael\",\n \"225\": \"malinois\",\n \"226\": \"briard\",\n \"227\": \"kelpie\",\n \"228\": \"komondor\",\n \"229\": \"Old English sheepdog, bobtail\",\n \"230\": \"Shetland sheepdog, Shetland sheep dog, Shetland\",\n \"231\": \"collie\",\n \"232\": \"Border collie\",\n \"233\": \"Bouvier des Flandres, Bouviers des Flandres\",\n \"234\": \"Rottweiler\",\n \"235\": \"German shepherd, German shepherd dog, German police dog, alsatian\",\n \"236\": \"Doberman, Doberman pinscher\",\n \"237\": \"miniature pinscher\",\n \"238\": \"Greater Swiss Mountain dog\",\n \"239\": \"Bernese mountain dog\",\n \"240\": \"Appenzeller\",\n \"241\": \"EntleBucher\",\n \"242\": \"boxer\",\n \"243\": \"bull mastiff\",\n \"244\": \"Tibetan mastiff\",\n \"245\": \"French bulldog\",\n \"246\": \"Great Dane\",\n \"247\": \"Saint Bernard, St Bernard\",\n \"248\": \"Eskimo dog, husky\",\n \"249\": \"malamute, malemute, Alaskan malamute\",\n \"250\": \"Siberian husky\",\n \"251\": \"dalmatian, coach dog, carriage dog\",\n \"252\": \"affenpinscher, monkey pinscher, monkey dog\",\n \"253\": \"basenji\",\n \"254\": \"pug, pug-dog\",\n \"255\": \"Leonberg\",\n \"256\": \"Newfoundland, Newfoundland dog\",\n \"257\": \"Great Pyrenees\",\n \"258\": \"Samoyed, Samoyede\",\n \"259\": \"Pomeranian\",\n \"260\": \"chow, chow chow\",\n \"261\": \"keeshond\",\n \"262\": \"Brabancon griffon\",\n \"263\": \"Pembroke, Pembroke Welsh corgi\",\n \"264\": \"Cardigan, Cardigan Welsh corgi\",\n \"265\": \"toy poodle\",\n \"266\": \"miniature poodle\",\n \"267\": \"standard poodle\",\n \"268\": \"Mexican hairless\",\n \"269\": \"timber wolf, grey wolf, gray wolf, Canis lupus\",\n \"270\": \"white wolf, Arctic wolf, Canis lupus tundrarum\",\n \"271\": \"red wolf, maned wolf, Canis rufus, Canis niger\",\n \"272\": \"coyote, prairie wolf, brush wolf, Canis latrans\",\n \"273\": \"dingo, warrigal, warragal, Canis dingo\",\n \"274\": \"dhole, Cuon alpinus\",\n \"275\": \"African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus\",\n \"276\": \"hyena, hyaena\",\n \"277\": \"red fox, Vulpes vulpes\",\n \"278\": \"kit fox, Vulpes macrotis\",\n \"279\": \"Arctic fox, white fox, Alopex lagopus\",\n \"280\": \"grey fox, gray fox, Urocyon cinereoargenteus\",\n \"281\": \"tabby, tabby cat\",\n \"282\": \"tiger cat\",\n \"283\": \"Persian cat\",\n \"284\": \"Siamese cat, Siamese\",\n \"285\": \"Egyptian cat\",\n \"286\": \"cougar, puma, catamount, mountain lion, painter, panther, Felis concolor\",\n \"287\": \"lynx, catamount\",\n \"288\": \"leopard, Panthera pardus\",\n \"289\": \"snow leopard, ounce, Panthera uncia\",\n \"290\": \"jaguar, panther, Panthera onca, Felis onca\",\n \"291\": \"lion, king of beasts, Panthera leo\",\n \"292\": \"tiger, Panthera tigris\",\n \"293\": \"cheetah, chetah, Acinonyx jubatus\",\n \"294\": \"brown bear, bruin, Ursus arctos\",\n \"295\": \"American black bear, black bear, Ursus americanus, Euarctos americanus\",\n \"296\": \"ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus\",\n \"297\": \"sloth bear, Melursus ursinus, Ursus ursinus\",\n \"298\": \"mongoose\",\n \"299\": \"meerkat, mierkat\",\n \"300\": \"tiger beetle\",\n \"301\": \"ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle\",\n \"302\": \"ground beetle, carabid beetle\",\n \"303\": \"long-horned beetle, longicorn, longicorn beetle\",\n \"304\": \"leaf beetle, chrysomelid\",\n \"305\": \"dung beetle\",\n \"306\": \"rhinoceros beetle\",\n \"307\": \"weevil\",\n \"308\": \"fly\",\n \"309\": \"bee\",\n \"310\": \"ant, emmet, pismire\",\n \"311\": \"grasshopper, hopper\",\n \"312\": \"cricket\",\n \"313\": \"walking stick, walkingstick, stick insect\",\n \"314\": \"cockroach, roach\",\n \"315\": \"mantis, mantid\",\n \"316\": \"cicada, cicala\",\n \"317\": \"leafhopper\",\n \"318\": \"lacewing, lacewing fly\",\n \"319\": \"dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk\",\n \"320\": \"damselfly\",\n \"321\": \"admiral\",\n \"322\": \"ringlet, ringlet butterfly\",\n \"323\": \"monarch, monarch butterfly, milkweed butterfly, Danaus plexippus\",\n \"324\": \"cabbage butterfly\",\n \"325\": \"sulphur butterfly, sulfur butterfly\",\n \"326\": \"lycaenid, lycaenid butterfly\",\n \"327\": \"starfish, sea star\",\n \"328\": \"sea urchin\",\n \"329\": \"sea cucumber, holothurian\",\n \"330\": \"wood rabbit, cottontail, cottontail rabbit\",\n \"331\": \"hare\",\n \"332\": \"Angora, Angora rabbit\",\n \"333\": \"hamster\",\n \"334\": \"porcupine, hedgehog\",\n \"335\": \"fox squirrel, eastern fox squirrel, Sciurus niger\",\n \"336\": \"marmot\",\n \"337\": \"beaver\",\n \"338\": \"guinea pig, Cavia cobaya\",\n \"339\": \"sorrel\",\n \"340\": \"zebra\",\n \"341\": \"hog, pig, grunter, squealer, Sus scrofa\",\n \"342\": \"wild boar, boar, Sus scrofa\",\n \"343\": \"warthog\",\n \"344\": \"hippopotamus, hippo, river horse, Hippopotamus amphibius\",\n \"345\": \"ox\",\n \"346\": \"water buffalo, water ox, Asiatic buffalo, Bubalus bubalis\",\n \"347\": \"bison\",\n \"348\": \"ram, tup\",\n \"349\": \"bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis\",\n \"350\": \"ibex, Capra ibex\",\n \"351\": \"hartebeest\",\n \"352\": \"impala, Aepyceros melampus\",\n \"353\": \"gazelle\",\n \"354\": \"Arabian camel, dromedary, Camelus dromedarius\",\n \"355\": \"llama\",\n \"356\": \"weasel\",\n \"357\": \"mink\",\n \"358\": \"polecat, fitch, foulmart, foumart, Mustela putorius\",\n \"359\": \"black-footed ferret, ferret, Mustela nigripes\",\n \"360\": \"otter\",\n \"361\": \"skunk, polecat, wood pussy\",\n \"362\": \"badger\",\n \"363\": \"armadillo\",\n \"364\": \"three-toed sloth, ai, Bradypus tridactylus\",\n \"365\": \"orangutan, orang, orangutang, Pongo pygmaeus\",\n \"366\": \"gorilla, Gorilla gorilla\",\n \"367\": \"chimpanzee, chimp, Pan troglodytes\",\n \"368\": \"gibbon, Hylobates lar\",\n \"369\": \"siamang, Hylobates syndactylus, Symphalangus syndactylus\",\n \"370\": \"guenon, guenon monkey\",\n \"371\": \"patas, hussar monkey, Erythrocebus patas\",\n \"372\": \"baboon\",\n \"373\": \"macaque\",\n \"374\": \"langur\",\n \"375\": \"colobus, colobus monkey\",\n \"376\": \"proboscis monkey, Nasalis larvatus\",\n \"377\": \"marmoset\",\n \"378\": \"capuchin, ringtail, Cebus capucinus\",\n \"379\": \"howler monkey, howler\",\n \"380\": \"titi, titi monkey\",\n \"381\": \"spider monkey, Ateles geoffroyi\",\n \"382\": \"squirrel monkey, Saimiri sciureus\",\n \"383\": \"Madagascar cat, ring-tailed lemur, Lemur catta\",\n \"384\": \"indri, indris, Indri indri, Indri brevicaudatus\",\n \"385\": \"Indian elephant, Elephas maximus\",\n \"386\": \"African elephant, Loxodonta africana\",\n \"387\": \"lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens\",\n \"388\": \"giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca\",\n \"389\": \"barracouta, snoek\",\n \"390\": \"eel\",\n \"391\": \"coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch\",\n \"392\": \"rock beauty, Holocanthus tricolor\",\n \"393\": \"anemone fish\",\n \"394\": \"sturgeon\",\n \"395\": \"gar, garfish, garpike, billfish, Lepisosteus osseus\",\n \"396\": \"lionfish\",\n \"397\": \"puffer, pufferfish, blowfish, globefish\",\n \"398\": \"abacus\",\n \"399\": \"abaya\",\n \"400\": \"academic gown, academic robe, judge's robe\",\n \"401\": \"accordion, piano accordion, squeeze box\",\n \"402\": \"acoustic guitar\",\n \"403\": \"aircraft carrier, carrier, flattop, attack aircraft carrier\",\n \"404\": \"airliner\",\n \"405\": \"airship, dirigible\",\n \"406\": \"altar\",\n \"407\": \"ambulance\",\n \"408\": \"amphibian, amphibious vehicle\",\n \"409\": \"analog clock\",\n \"410\": \"apiary, bee house\",\n \"411\": \"apron\",\n \"412\": \"ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin\",\n \"413\": \"assault rifle, assault gun\",\n \"414\": \"backpack, back pack, knapsack, packsack, rucksack, haversack\",\n \"415\": \"bakery, bakeshop, bakehouse\",\n \"416\": \"balance beam, beam\",\n \"417\": \"balloon\",\n \"418\": \"ballpoint, ballpoint pen, ballpen, Biro\",\n \"419\": \"Band Aid\",\n \"420\": \"banjo\",\n \"421\": \"bannister, banister, balustrade, balusters, handrail\",\n \"422\": \"barbell\",\n \"423\": \"barber chair\",\n \"424\": \"barbershop\",\n \"425\": \"barn\",\n \"426\": \"barometer\",\n \"427\": \"barrel, cask\",\n \"428\": \"barrow, garden cart, lawn cart, wheelbarrow\",\n \"429\": \"baseball\",\n \"430\": \"basketball\",\n \"431\": \"bassinet\",\n \"432\": \"bassoon\",\n \"433\": \"bathing cap, swimming cap\",\n \"434\": \"bath towel\",\n \"435\": \"bathtub, bathing tub, bath, tub\",\n \"436\": \"beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon\",\n \"437\": \"beacon, lighthouse, beacon light, pharos\",\n \"438\": \"beaker\",\n \"439\": \"bearskin, busby, shako\",\n \"440\": \"beer bottle\",\n \"441\": \"beer glass\",\n \"442\": \"bell cote, bell cot\",\n \"443\": \"bib\",\n \"444\": \"bicycle-built-for-two, tandem bicycle, tandem\",\n \"445\": \"bikini, two-piece\",\n \"446\": \"binder, ring-binder\",\n \"447\": \"binoculars, field glasses, opera glasses\",\n \"448\": \"birdhouse\",\n \"449\": \"boathouse\",\n \"450\": \"bobsled, bobsleigh, bob\",\n \"451\": \"bolo tie, bolo, bola tie, bola\",\n \"452\": \"bonnet, poke bonnet\",\n \"453\": \"bookcase\",\n \"454\": \"bookshop, bookstore, bookstall\",\n \"455\": \"bottlecap\",\n \"456\": \"bow\",\n \"457\": \"bow tie, bow-tie, bowtie\",\n \"458\": \"brass, memorial tablet, plaque\",\n \"459\": \"brassiere, bra, bandeau\",\n \"460\": \"breakwater, groin, groyne, mole, bulwark, seawall, jetty\",\n \"461\": \"breastplate, aegis, egis\",\n \"462\": \"broom\",\n \"463\": \"bucket, pail\",\n \"464\": \"buckle\",\n \"465\": \"bulletproof vest\",\n \"466\": \"bullet train, bullet\",\n \"467\": \"butcher shop, meat market\",\n \"468\": \"cab, hack, taxi, taxicab\",\n \"469\": \"caldron, cauldron\",\n \"470\": \"candle, taper, wax light\",\n \"471\": \"cannon\",\n \"472\": \"canoe\",\n \"473\": \"can opener, tin opener\",\n \"474\": \"cardigan\",\n \"475\": \"car mirror\",\n \"476\": \"carousel, carrousel, merry-go-round, roundabout, whirligig\",\n \"477\": \"carpenter's kit, tool kit\",\n \"478\": \"carton\",\n \"479\": \"car wheel\",\n \"480\": \"cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM\",\n \"481\": \"cassette\",\n \"482\": \"cassette player\",\n \"483\": \"castle\",\n \"484\": \"catamaran\",\n \"485\": \"CD player\",\n \"486\": \"cello, violoncello\",\n \"487\": \"cellular telephone, cellular phone, cellphone, cell, mobile phone\",\n \"488\": \"chain\",\n \"489\": \"chainlink fence\",\n \"490\": \"chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour\",\n \"491\": \"chain saw, chainsaw\",\n \"492\": \"chest\",\n \"493\": \"chiffonier, commode\",\n \"494\": \"chime, bell, gong\",\n \"495\": \"china cabinet, china closet\",\n \"496\": \"Christmas stocking\",\n \"497\": \"church, church building\",\n \"498\": \"cinema, movie theater, movie theatre, movie house, picture palace\",\n \"499\": \"cleaver, meat cleaver, chopper\",\n \"500\": \"cliff dwelling\",\n \"501\": \"cloak\",\n \"502\": \"clog, geta, patten, sabot\",\n \"503\": \"cocktail shaker\",\n \"504\": \"coffee mug\",\n \"505\": \"coffeepot\",\n \"506\": \"coil, spiral, volute, whorl, helix\",\n \"507\": \"combination lock\",\n \"508\": \"computer keyboard, keypad\",\n \"509\": \"confectionery, confectionary, candy store\",\n \"510\": \"container ship, containership, container vessel\",\n \"511\": \"convertible\",\n \"512\": \"corkscrew, bottle screw\",\n \"513\": \"cornet, horn, trumpet, trump\",\n \"514\": \"cowboy boot\",\n \"515\": \"cowboy hat, ten-gallon hat\",\n \"516\": \"cradle\",\n \"517\": \"crane\",\n \"518\": \"crash helmet\",\n \"519\": \"crate\",\n \"520\": \"crib, cot\",\n \"521\": \"Crock Pot\",\n \"522\": \"croquet ball\",\n \"523\": \"crutch\",\n \"524\": \"cuirass\",\n \"525\": \"dam, dike, dyke\",\n \"526\": \"desk\",\n \"527\": \"desktop computer\",\n \"528\": \"dial telephone, dial phone\",\n \"529\": \"diaper, nappy, napkin\",\n \"530\": \"digital clock\",\n \"531\": \"digital watch\",\n \"532\": \"dining table, board\",\n \"533\": \"dishrag, dishcloth\",\n \"534\": \"dishwasher, dish washer, dishwashing machine\",\n \"535\": \"disk brake, disc brake\",\n \"536\": \"dock, dockage, docking facility\",\n \"537\": \"dogsled, dog sled, dog sleigh\",\n \"538\": \"dome\",\n \"539\": \"doormat, welcome mat\",\n \"540\": \"drilling platform, offshore rig\",\n \"541\": \"drum, membranophone, tympan\",\n \"542\": \"drumstick\",\n \"543\": \"dumbbell\",\n \"544\": \"Dutch oven\",\n \"545\": \"electric fan, blower\",\n \"546\": \"electric guitar\",\n \"547\": \"electric locomotive\",\n \"548\": \"entertainment center\",\n \"549\": \"envelope\",\n \"550\": \"espresso maker\",\n \"551\": \"face powder\",\n \"552\": \"feather boa, boa\",\n \"553\": \"file, file cabinet, filing cabinet\",\n \"554\": \"fireboat\",\n \"555\": \"fire engine, fire truck\",\n \"556\": \"fire screen, fireguard\",\n \"557\": \"flagpole, flagstaff\",\n \"558\": \"flute, transverse flute\",\n \"559\": \"folding chair\",\n \"560\": \"football helmet\",\n \"561\": \"forklift\",\n \"562\": \"fountain\",\n \"563\": \"fountain pen\",\n \"564\": \"four-poster\",\n \"565\": \"freight car\",\n \"566\": \"French horn, horn\",\n \"567\": \"frying pan, frypan, skillet\",\n \"568\": \"fur coat\",\n \"569\": \"garbage truck, dustcart\",\n \"570\": \"gasmask, respirator, gas helmet\",\n \"571\": \"gas pump, gasoline pump, petrol pump, island dispenser\",\n \"572\": \"goblet\",\n \"573\": \"go-kart\",\n \"574\": \"golf ball\",\n \"575\": \"golfcart, golf cart\",\n \"576\": \"gondola\",\n \"577\": \"gong, tam-tam\",\n \"578\": \"gown\",\n \"579\": \"grand piano, grand\",\n \"580\": \"greenhouse, nursery, glasshouse\",\n \"581\": \"grille, radiator grille\",\n \"582\": \"grocery store, grocery, food market, market\",\n \"583\": \"guillotine\",\n \"584\": \"hair slide\",\n \"585\": \"hair spray\",\n \"586\": \"half track\",\n \"587\": \"hammer\",\n \"588\": \"hamper\",\n \"589\": \"hand blower, blow dryer, blow drier, hair dryer, hair drier\",\n \"590\": \"hand-held computer, hand-held microcomputer\",\n \"591\": \"handkerchief, hankie, hanky, hankey\",\n \"592\": \"hard disc, hard disk, fixed disk\",\n \"593\": \"harmonica, mouth organ, harp, mouth harp\",\n \"594\": \"harp\",\n \"595\": \"harvester, reaper\",\n \"596\": \"hatchet\",\n \"597\": \"holster\",\n \"598\": \"home theater, home theatre\",\n \"599\": \"honeycomb\",\n \"600\": \"hook, claw\",\n \"601\": \"hoopskirt, crinoline\",\n \"602\": \"horizontal bar, high bar\",\n \"603\": \"horse cart, horse-cart\",\n \"604\": \"hourglass\",\n \"605\": \"iPod\",\n \"606\": \"iron, smoothing iron\",\n \"607\": \"jack-o'-lantern\",\n \"608\": \"jean, blue jean, denim\",\n \"609\": \"jeep, landrover\",\n \"610\": \"jersey, T-shirt, tee shirt\",\n \"611\": \"jigsaw puzzle\",\n \"612\": \"jinrikisha, ricksha, rickshaw\",\n \"613\": \"joystick\",\n \"614\": \"kimono\",\n \"615\": \"knee pad\",\n \"616\": \"knot\",\n \"617\": \"lab coat, laboratory coat\",\n \"618\": \"ladle\",\n \"619\": \"lampshade, lamp shade\",\n \"620\": \"laptop, laptop computer\",\n \"621\": \"lawn mower, mower\",\n \"622\": \"lens cap, lens cover\",\n \"623\": \"letter opener, paper knife, paperknife\",\n \"624\": \"library\",\n \"625\": \"lifeboat\",\n \"626\": \"lighter, light, igniter, ignitor\",\n \"627\": \"limousine, limo\",\n \"628\": \"liner, ocean liner\",\n \"629\": \"lipstick, lip rouge\",\n \"630\": \"Loafer\",\n \"631\": \"lotion\",\n \"632\": \"loudspeaker, speaker, speaker unit, loudspeaker system, speaker system\",\n \"633\": \"loupe, jeweler's loupe\",\n \"634\": \"lumbermill, sawmill\",\n \"635\": \"magnetic compass\",\n \"636\": \"mailbag, postbag\",\n \"637\": \"mailbox, letter box\",\n \"638\": \"maillot\",\n \"639\": \"maillot, tank suit\",\n \"640\": \"manhole cover\",\n \"641\": \"maraca\",\n \"642\": \"marimba, xylophone\",\n \"643\": \"mask\",\n \"644\": \"matchstick\",\n \"645\": \"maypole\",\n \"646\": \"maze, labyrinth\",\n \"647\": \"measuring cup\",\n \"648\": \"medicine chest, medicine cabinet\",\n \"649\": \"megalith, megalithic structure\",\n \"650\": \"microphone, mike\",\n \"651\": \"microwave, microwave oven\",\n \"652\": \"military uniform\",\n \"653\": \"milk can\",\n \"654\": \"minibus\",\n \"655\": \"miniskirt, mini\",\n \"656\": \"minivan\",\n \"657\": \"missile\",\n \"658\": \"mitten\",\n \"659\": \"mixing bowl\",\n \"660\": \"mobile home, manufactured home\",\n \"661\": \"Model T\",\n \"662\": \"modem\",\n \"663\": \"monastery\",\n \"664\": \"monitor\",\n \"665\": \"moped\",\n \"666\": \"mortar\",\n \"667\": \"mortarboard\",\n \"668\": \"mosque\",\n \"669\": \"mosquito net\",\n \"670\": \"motor scooter, scooter\",\n \"671\": \"mountain bike, all-terrain bike, off-roader\",\n \"672\": \"mountain tent\",\n \"673\": \"mouse, computer mouse\",\n \"674\": \"mousetrap\",\n \"675\": \"moving van\",\n \"676\": \"muzzle\",\n \"677\": \"nail\",\n \"678\": \"neck brace\",\n \"679\": \"necklace\",\n \"680\": \"nipple\",\n \"681\": \"notebook, notebook computer\",\n \"682\": \"obelisk\",\n \"683\": \"oboe, hautboy, hautbois\",\n \"684\": \"ocarina, sweet potato\",\n \"685\": \"odometer, hodometer, mileometer, milometer\",\n \"686\": \"oil filter\",\n \"687\": \"organ, pipe organ\",\n \"688\": \"oscilloscope, scope, cathode-ray oscilloscope, CRO\",\n \"689\": \"overskirt\",\n \"690\": \"oxcart\",\n \"691\": \"oxygen mask\",\n \"692\": \"packet\",\n \"693\": \"paddle, boat paddle\",\n \"694\": \"paddlewheel, paddle wheel\",\n \"695\": \"padlock\",\n \"696\": \"paintbrush\",\n \"697\": \"pajama, pyjama, pj's, jammies\",\n \"698\": \"palace\",\n \"699\": \"panpipe, pandean pipe, syrinx\",\n \"700\": \"paper towel\",\n \"701\": \"parachute, chute\",\n \"702\": \"parallel bars, bars\",\n \"703\": \"park bench\",\n \"704\": \"parking meter\",\n \"705\": \"passenger car, coach, carriage\",\n \"706\": \"patio, terrace\",\n \"707\": \"pay-phone, pay-station\",\n \"708\": \"pedestal, plinth, footstall\",\n \"709\": \"pencil box, pencil case\",\n \"710\": \"pencil sharpener\",\n \"711\": \"perfume, essence\",\n \"712\": \"Petri dish\",\n \"713\": \"photocopier\",\n \"714\": \"pick, plectrum, plectron\",\n \"715\": \"pickelhaube\",\n \"716\": \"picket fence, paling\",\n \"717\": \"pickup, pickup truck\",\n \"718\": \"pier\",\n \"719\": \"piggy bank, penny bank\",\n \"720\": \"pill bottle\",\n \"721\": \"pillow\",\n \"722\": \"ping-pong ball\",\n \"723\": \"pinwheel\",\n \"724\": \"pirate, pirate ship\",\n \"725\": \"pitcher, ewer\",\n \"726\": \"plane, carpenter's plane, woodworking plane\",\n \"727\": \"planetarium\",\n \"728\": \"plastic bag\",\n \"729\": \"plate rack\",\n \"730\": \"plow, plough\",\n \"731\": \"plunger, plumber's helper\",\n \"732\": \"Polaroid camera, Polaroid Land camera\",\n \"733\": \"pole\",\n \"734\": \"police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria\",\n \"735\": \"poncho\",\n \"736\": \"pool table, billiard table, snooker table\",\n \"737\": \"pop bottle, soda bottle\",\n \"738\": \"pot, flowerpot\",\n \"739\": \"potter's wheel\",\n \"740\": \"power drill\",\n \"741\": \"prayer rug, prayer mat\",\n \"742\": \"printer\",\n \"743\": \"prison, prison house\",\n \"744\": \"projectile, missile\",\n \"745\": \"projector\",\n \"746\": \"puck, hockey puck\",\n \"747\": \"punching bag, punch bag, punching ball, punchball\",\n \"748\": \"purse\",\n \"749\": \"quill, quill pen\",\n \"750\": \"quilt, comforter, comfort, puff\",\n \"751\": \"racer, race car, racing car\",\n \"752\": \"racket, racquet\",\n \"753\": \"radiator\",\n \"754\": \"radio, wireless\",\n \"755\": \"radio telescope, radio reflector\",\n \"756\": \"rain barrel\",\n \"757\": \"recreational vehicle, RV, R.V.\",\n \"758\": \"reel\",\n \"759\": \"reflex camera\",\n \"760\": \"refrigerator, icebox\",\n \"761\": \"remote control, remote\",\n \"762\": \"restaurant, eating house, eating place, eatery\",\n \"763\": \"revolver, six-gun, six-shooter\",\n \"764\": \"rifle\",\n \"765\": \"rocking chair, rocker\",\n \"766\": \"rotisserie\",\n \"767\": \"rubber eraser, rubber, pencil eraser\",\n \"768\": \"rugby ball\",\n \"769\": \"rule, ruler\",\n \"770\": \"running shoe\",\n \"771\": \"safe\",\n \"772\": \"safety pin\",\n \"773\": \"saltshaker, salt shaker\",\n \"774\": \"sandal\",\n \"775\": \"sarong\",\n \"776\": \"sax, saxophone\",\n \"777\": \"scabbard\",\n \"778\": \"scale, weighing machine\",\n \"779\": \"school bus\",\n \"780\": \"schooner\",\n \"781\": \"scoreboard\",\n \"782\": \"screen, CRT screen\",\n \"783\": \"screw\",\n \"784\": \"screwdriver\",\n \"785\": \"seat belt, seatbelt\",\n \"786\": \"sewing machine\",\n \"787\": \"shield, buckler\",\n \"788\": \"shoe shop, shoe-shop, shoe store\",\n \"789\": \"shoji\",\n \"790\": \"shopping basket\",\n \"791\": \"shopping cart\",\n \"792\": \"shovel\",\n \"793\": \"shower cap\",\n \"794\": \"shower curtain\",\n \"795\": \"ski\",\n \"796\": \"ski mask\",\n \"797\": \"sleeping bag\",\n \"798\": \"slide rule, slipstick\",\n \"799\": \"sliding door\",\n \"800\": \"slot, one-armed bandit\",\n \"801\": \"snorkel\",\n \"802\": \"snowmobile\",\n \"803\": \"snowplow, snowplough\",\n \"804\": \"soap dispenser\",\n \"805\": \"soccer ball\",\n \"806\": \"sock\",\n \"807\": \"solar dish, solar collector, solar furnace\",\n \"808\": \"sombrero\",\n \"809\": \"soup bowl\",\n \"810\": \"space bar\",\n \"811\": \"space heater\",\n \"812\": \"space shuttle\",\n \"813\": \"spatula\",\n \"814\": \"speedboat\",\n \"815\": \"spider web, spider's web\",\n \"816\": \"spindle\",\n \"817\": \"sports car, sport car\",\n \"818\": \"spotlight, spot\",\n \"819\": \"stage\",\n \"820\": \"steam locomotive\",\n \"821\": \"steel arch bridge\",\n \"822\": \"steel drum\",\n \"823\": \"stethoscope\",\n \"824\": \"stole\",\n \"825\": \"stone wall\",\n \"826\": \"stopwatch, stop watch\",\n \"827\": \"stove\",\n \"828\": \"strainer\",\n \"829\": \"streetcar, tram, tramcar, trolley, trolley car\",\n \"830\": \"stretcher\",\n \"831\": \"studio couch, day bed\",\n \"832\": \"stupa, tope\",\n \"833\": \"submarine, pigboat, sub, U-boat\",\n \"834\": \"suit, suit of clothes\",\n \"835\": \"sundial\",\n \"836\": \"sunglass\",\n \"837\": \"sunglasses, dark glasses, shades\",\n \"838\": \"sunscreen, sunblock, sun blocker\",\n \"839\": \"suspension bridge\",\n \"840\": \"swab, swob, mop\",\n \"841\": \"sweatshirt\",\n \"842\": \"swimming trunks, bathing trunks\",\n \"843\": \"swing\",\n \"844\": \"switch, electric switch, electrical switch\",\n \"845\": \"syringe\",\n \"846\": \"table lamp\",\n \"847\": \"tank, army tank, armored combat vehicle, armoured combat vehicle\",\n \"848\": \"tape player\",\n \"849\": \"teapot\",\n \"850\": \"teddy, teddy bear\",\n \"851\": \"television, television system\",\n \"852\": \"tennis ball\",\n \"853\": \"thatch, thatched roof\",\n \"854\": \"theater curtain, theatre curtain\",\n \"855\": \"thimble\",\n \"856\": \"thresher, thrasher, threshing machine\",\n \"857\": \"throne\",\n \"858\": \"tile roof\",\n \"859\": \"toaster\",\n \"860\": \"tobacco shop, tobacconist shop, tobacconist\",\n \"861\": \"toilet seat\",\n \"862\": \"torch\",\n \"863\": \"totem pole\",\n \"864\": \"tow truck, tow car, wrecker\",\n \"865\": \"toyshop\",\n \"866\": \"tractor\",\n \"867\": \"trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi\",\n \"868\": \"tray\",\n \"869\": \"trench coat\",\n \"870\": \"tricycle, trike, velocipede\",\n \"871\": \"trimaran\",\n \"872\": \"tripod\",\n \"873\": \"triumphal arch\",\n \"874\": \"trolleybus, trolley coach, trackless trolley\",\n \"875\": \"trombone\",\n \"876\": \"tub, vat\",\n \"877\": \"turnstile\",\n \"878\": \"typewriter keyboard\",\n \"879\": \"umbrella\",\n \"880\": \"unicycle, monocycle\",\n \"881\": \"upright, upright piano\",\n \"882\": \"vacuum, vacuum cleaner\",\n \"883\": \"vase\",\n \"884\": \"vault\",\n \"885\": \"velvet\",\n \"886\": \"vending machine\",\n \"887\": \"vestment\",\n \"888\": \"viaduct\",\n \"889\": \"violin, fiddle\",\n \"890\": \"volleyball\",\n \"891\": \"waffle iron\",\n \"892\": \"wall clock\",\n \"893\": \"wallet, billfold, notecase, pocketbook\",\n \"894\": \"wardrobe, closet, press\",\n \"895\": \"warplane, military plane\",\n \"896\": \"washbasin, handbasin, washbowl, lavabo, wash-hand basin\",\n \"897\": \"washer, automatic washer, washing machine\",\n \"898\": \"water bottle\",\n \"899\": \"water jug\",\n \"900\": \"water tower\",\n \"901\": \"whiskey jug\",\n \"902\": \"whistle\",\n \"903\": \"wig\",\n \"904\": \"window screen\",\n \"905\": \"window shade\",\n \"906\": \"Windsor tie\",\n \"907\": \"wine bottle\",\n \"908\": \"wing\",\n \"909\": \"wok\",\n \"910\": \"wooden spoon\",\n \"911\": \"wool, woolen, woollen\",\n \"912\": \"worm fence, snake fence, snake-rail fence, Virginia fence\",\n \"913\": \"wreck\",\n \"914\": \"yawl\",\n \"915\": \"yurt\",\n \"916\": \"web site, website, internet site, site\",\n \"917\": \"comic book\",\n \"918\": \"crossword puzzle, crossword\",\n \"919\": \"street sign\",\n \"920\": \"traffic light, traffic signal, stoplight\",\n \"921\": \"book jacket, dust cover, dust jacket, dust wrapper\",\n \"922\": \"menu\",\n \"923\": \"plate\",\n \"924\": \"guacamole\",\n \"925\": \"consomme\",\n \"926\": \"hot pot, hotpot\",\n \"927\": \"trifle\",\n \"928\": \"ice cream, icecream\",\n \"929\": \"ice lolly, lolly, lollipop, popsicle\",\n \"930\": \"French loaf\",\n \"931\": \"bagel, beigel\",\n \"932\": \"pretzel\",\n \"933\": \"cheeseburger\",\n \"934\": \"hotdog, hot dog, red hot\",\n \"935\": \"mashed potato\",\n \"936\": \"head cabbage\",\n \"937\": \"broccoli\",\n \"938\": \"cauliflower\",\n \"939\": \"zucchini, courgette\",\n \"940\": \"spaghetti squash\",\n \"941\": \"acorn squash\",\n \"942\": \"butternut squash\",\n \"943\": \"cucumber, cuke\",\n \"944\": \"artichoke, globe artichoke\",\n \"945\": \"bell pepper\",\n \"946\": \"cardoon\",\n \"947\": \"mushroom\",\n \"948\": \"Granny Smith\",\n \"949\": \"strawberry\",\n \"950\": \"orange\",\n \"951\": \"lemon\",\n \"952\": \"fig\",\n \"953\": \"pineapple, ananas\",\n \"954\": \"banana\",\n \"955\": \"jackfruit, jak, jack\",\n \"956\": \"custard apple\",\n \"957\": \"pomegranate\",\n \"958\": \"hay\",\n \"959\": \"carbonara\",\n \"960\": \"chocolate sauce, chocolate syrup\",\n \"961\": \"dough\",\n \"962\": \"meat loaf, meatloaf\",\n \"963\": \"pizza, pizza pie\",\n \"964\": \"potpie\",\n \"965\": \"burrito\",\n \"966\": \"red wine\",\n \"967\": \"espresso\",\n \"968\": \"cup\",\n \"969\": \"eggnog\",\n \"970\": \"alp\",\n \"971\": \"bubble\",\n \"972\": \"cliff, drop, drop-off\",\n \"973\": \"coral reef\",\n \"974\": \"geyser\",\n \"975\": \"lakeside, lakeshore\",\n \"976\": \"promontory, headland, head, foreland\",\n \"977\": \"sandbar, sand bar\",\n \"978\": \"seashore, coast, seacoast, sea-coast\",\n \"979\": \"valley, vale\",\n \"980\": \"volcano\",\n \"981\": \"ballplayer, baseball player\",\n \"982\": \"groom, bridegroom\",\n \"983\": \"scuba diver\",\n \"984\": \"rapeseed\",\n \"985\": \"daisy\",\n \"986\": \"yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum\",\n \"987\": \"corn\",\n \"988\": \"acorn\",\n \"989\": \"hip, rose hip, rosehip\",\n \"990\": \"buckeye, horse chestnut, conker\",\n \"991\": \"coral fungus\",\n \"992\": \"agaric\",\n \"993\": \"gyromitra\",\n \"994\": \"stinkhorn, carrion fungus\",\n \"995\": \"earthstar\",\n \"996\": \"hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa\",\n \"997\": \"bolete\",\n \"998\": \"ear, spike, capitulum\",\n \"999\": \"toilet tissue, toilet paper, bathroom tissue\"}"
  },
  {
    "path": "denoising.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Code for **\\\"Blind restoration of a JPEG-compressed image\\\"** and **\\\"Blind image denoising\\\"** figures. Select `fname` below to switch between the two.\\n\",\n    \"\\n\",\n    \"- To see overfitting set `num_iter` to a large value.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Import libs\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from __future__ import print_function\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"%matplotlib inline\\n\",\n    \"\\n\",\n    \"import os\\n\",\n    \"#os.environ['CUDA_VISIBLE_DEVICES'] = '3'\\n\",\n    \"\\n\",\n    \"import numpy as np\\n\",\n    \"from models import *\\n\",\n    \"\\n\",\n    \"import torch\\n\",\n    \"import torch.optim\\n\",\n    \"\\n\",\n    \"from skimage.measure import compare_psnr\\n\",\n    \"from utils.denoising_utils import *\\n\",\n    \"\\n\",\n    \"torch.backends.cudnn.enabled = True\\n\",\n    \"torch.backends.cudnn.benchmark =True\\n\",\n    \"dtype = torch.cuda.FloatTensor\\n\",\n    \"\\n\",\n    \"imsize =-1\\n\",\n    \"PLOT = True\\n\",\n    \"sigma = 25\\n\",\n    \"sigma_ = sigma/255.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# deJPEG \\n\",\n    \"# fname = 'data/denoising/snail.jpg'\\n\",\n    \"\\n\",\n    \"## denoising\\n\",\n    \"fname = 'data/denoising/F16_GT.png'\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Load image\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"if fname == 'data/denoising/snail.jpg':\\n\",\n    \"    img_noisy_pil = crop_image(get_image(fname, imsize)[0], d=32)\\n\",\n    \"    img_noisy_np = pil_to_np(img_noisy_pil)\\n\",\n    \"    \\n\",\n    \"    # As we don't have ground truth\\n\",\n    \"    img_pil = img_noisy_pil\\n\",\n    \"    img_np = img_noisy_np\\n\",\n    \"    \\n\",\n    \"    if PLOT:\\n\",\n    \"        plot_image_grid([img_np], 4, 5);\\n\",\n    \"        \\n\",\n    \"elif fname == 'data/denoising/F16_GT.png':\\n\",\n    \"    # Add synthetic noise\\n\",\n    \"    img_pil = crop_image(get_image(fname, imsize)[0], d=32)\\n\",\n    \"    img_np = pil_to_np(img_pil)\\n\",\n    \"    \\n\",\n    \"    img_noisy_pil, img_noisy_np = get_noisy_image(img_np, sigma_)\\n\",\n    \"    \\n\",\n    \"    if PLOT:\\n\",\n    \"        plot_image_grid([img_np, img_noisy_np], 4, 6);\\n\",\n    \"else:\\n\",\n    \"    assert False\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Setup\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"INPUT = 'noise' # 'meshgrid'\\n\",\n    \"pad = 'reflection'\\n\",\n    \"OPT_OVER = 'net' # 'net,input'\\n\",\n    \"\\n\",\n    \"reg_noise_std = 1./30. # set to 1./20. for sigma=50\\n\",\n    \"LR = 0.01\\n\",\n    \"\\n\",\n    \"OPTIMIZER='adam' # 'LBFGS'\\n\",\n    \"show_every = 100\\n\",\n    \"exp_weight=0.99\\n\",\n    \"\\n\",\n    \"if fname == 'data/denoising/snail.jpg':\\n\",\n    \"    num_iter = 2400\\n\",\n    \"    input_depth = 3\\n\",\n    \"    figsize = 5 \\n\",\n    \"    \\n\",\n    \"    net = skip(\\n\",\n    \"                input_depth, 3, \\n\",\n    \"                num_channels_down = [8, 16, 32, 64, 128], \\n\",\n    \"                num_channels_up   = [8, 16, 32, 64, 128],\\n\",\n    \"                num_channels_skip = [0, 0, 0, 4, 4], \\n\",\n    \"                upsample_mode='bilinear',\\n\",\n    \"                need_sigmoid=True, need_bias=True, pad=pad, act_fun='LeakyReLU')\\n\",\n    \"\\n\",\n    \"    net = net.type(dtype)\\n\",\n    \"\\n\",\n    \"elif fname == 'data/denoising/F16_GT.png':\\n\",\n    \"    num_iter = 3000\\n\",\n    \"    input_depth = 32 \\n\",\n    \"    figsize = 4 \\n\",\n    \"    \\n\",\n    \"    \\n\",\n    \"    net = get_net(input_depth, 'skip', pad,\\n\",\n    \"                  skip_n33d=128, \\n\",\n    \"                  skip_n33u=128, \\n\",\n    \"                  skip_n11=4, \\n\",\n    \"                  num_scales=5,\\n\",\n    \"                  upsample_mode='bilinear').type(dtype)\\n\",\n    \"\\n\",\n    \"else:\\n\",\n    \"    assert False\\n\",\n    \"    \\n\",\n    \"net_input = get_noise(input_depth, INPUT, (img_pil.size[1], img_pil.size[0])).type(dtype).detach()\\n\",\n    \"\\n\",\n    \"# Compute number of parameters\\n\",\n    \"s  = sum([np.prod(list(p.size())) for p in net.parameters()]); \\n\",\n    \"print ('Number of params: %d' % s)\\n\",\n    \"\\n\",\n    \"# Loss\\n\",\n    \"mse = torch.nn.MSELoss().type(dtype)\\n\",\n    \"\\n\",\n    \"img_noisy_torch = np_to_torch(img_noisy_np).type(dtype)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Optimize\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"scrolled\": true\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"net_input_saved = net_input.detach().clone()\\n\",\n    \"noise = net_input.detach().clone()\\n\",\n    \"out_avg = None\\n\",\n    \"last_net = None\\n\",\n    \"psrn_noisy_last = 0\\n\",\n    \"\\n\",\n    \"i = 0\\n\",\n    \"def closure():\\n\",\n    \"    \\n\",\n    \"    global i, out_avg, psrn_noisy_last, last_net, net_input\\n\",\n    \"    \\n\",\n    \"    if reg_noise_std > 0:\\n\",\n    \"        net_input = net_input_saved + (noise.normal_() * reg_noise_std)\\n\",\n    \"    \\n\",\n    \"    out = net(net_input)\\n\",\n    \"    \\n\",\n    \"    # Smoothing\\n\",\n    \"    if out_avg is None:\\n\",\n    \"        out_avg = out.detach()\\n\",\n    \"    else:\\n\",\n    \"        out_avg = out_avg * exp_weight + out.detach() * (1 - exp_weight)\\n\",\n    \"            \\n\",\n    \"    total_loss = mse(out, img_noisy_torch)\\n\",\n    \"    total_loss.backward()\\n\",\n    \"        \\n\",\n    \"    \\n\",\n    \"    psrn_noisy = compare_psnr(img_noisy_np, out.detach().cpu().numpy()[0]) \\n\",\n    \"    psrn_gt    = compare_psnr(img_np, out.detach().cpu().numpy()[0]) \\n\",\n    \"    psrn_gt_sm = compare_psnr(img_np, out_avg.detach().cpu().numpy()[0]) \\n\",\n    \"    \\n\",\n    \"    # Note that we do not have GT for the \\\"snail\\\" example\\n\",\n    \"    # So 'PSRN_gt', 'PSNR_gt_sm' make no sense\\n\",\n    \"    print ('Iteration %05d    Loss %f   PSNR_noisy: %f   PSRN_gt: %f PSNR_gt_sm: %f' % (i, total_loss.item(), psrn_noisy, psrn_gt, psrn_gt_sm), '\\\\r', end='')\\n\",\n    \"    if  PLOT and i % show_every == 0:\\n\",\n    \"        out_np = torch_to_np(out)\\n\",\n    \"        plot_image_grid([np.clip(out_np, 0, 1), \\n\",\n    \"                         np.clip(torch_to_np(out_avg), 0, 1)], factor=figsize, nrow=1)\\n\",\n    \"        \\n\",\n    \"        \\n\",\n    \"    \\n\",\n    \"    # Backtracking\\n\",\n    \"    if i % show_every:\\n\",\n    \"        if psrn_noisy - psrn_noisy_last < -5: \\n\",\n    \"            print('Falling back to previous checkpoint.')\\n\",\n    \"\\n\",\n    \"            for new_param, net_param in zip(last_net, net.parameters()):\\n\",\n    \"                net_param.data.copy_(new_param.cuda())\\n\",\n    \"\\n\",\n    \"            return total_loss*0\\n\",\n    \"        else:\\n\",\n    \"            last_net = [x.detach().cpu() for x in net.parameters()]\\n\",\n    \"            psrn_noisy_last = psrn_noisy\\n\",\n    \"            \\n\",\n    \"    i += 1\\n\",\n    \"\\n\",\n    \"    return total_loss\\n\",\n    \"\\n\",\n    \"p = get_params(OPT_OVER, net, net_input)\\n\",\n    \"optimize(OPTIMIZER, p, closure, LR, num_iter)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"out_np = torch_to_np(net(net_input))\\n\",\n    \"q = plot_image_grid([np.clip(out_np, 0, 1), img_np], factor=13);\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.6.5\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
  },
  {
    "path": "environment.yml",
    "content": "name: deep-image-prior\nchannels:\n- pytorch\n- defaults\ndependencies:\n- jupyter\n- nb_conda\n- numpy\n- pyyaml\n- mkl\n- setuptools\n- cmake\n- cffi\n- pytorch=0.4\n- matplotlib\n- scikit-image\n- torchvision\n"
  },
  {
    "path": "feature_inversion.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Code for **\\\"AlexNet inversion\\\"** figure from the main paper and **\\\"VGG inversion\\\"** from supmat.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Import libs\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from __future__ import print_function\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"%matplotlib inline\\n\",\n    \"\\n\",\n    \"import argparse\\n\",\n    \"import os\\n\",\n    \"#os.environ['CUDA_VISIBLE_DEVICES'] = '0'\\n\",\n    \"\\n\",\n    \"import numpy as np\\n\",\n    \"from models import *\\n\",\n    \"\\n\",\n    \"import torch\\n\",\n    \"import torch.optim\\n\",\n    \"\\n\",\n    \"from utils.feature_inversion_utils import *\\n\",\n    \"from utils.perceptual_loss.perceptual_loss import get_pretrained_net\\n\",\n    \"from utils.common_utils import *\\n\",\n    \"\\n\",\n    \"torch.backends.cudnn.enabled = True\\n\",\n    \"torch.backends.cudnn.benchmark =True\\n\",\n    \"dtype = torch.cuda.FloatTensor\\n\",\n    \"\\n\",\n    \"PLOT = True\\n\",\n    \"fname = './data/feature_inversion/building.jpg'\\n\",\n    \"\\n\",\n    \"pretrained_net = 'alexnet_caffe' # 'vgg19_caffe'\\n\",\n    \"layers_to_use = 'fc6' # comma-separated string of layer names e.g. 'fc6,fc7'\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Setup pretrained net\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"cnn = get_pretrained_net(pretrained_net).type(dtype)\\n\",\n    \"\\n\",\n    \"opt_content = {'layers': layers_to_use, 'what':'features'}\\n\",\n    \"\\n\",\n    \"# Remove the layers we don't need \\n\",\n    \"keys = [x for x in cnn._modules.keys()]\\n\",\n    \"max_idx = max(keys.index(x) for x in opt_content['layers'].split(','))\\n\",\n    \"for k in keys[max_idx+1:]:\\n\",\n    \"    cnn._modules.pop(k)\\n\",\n    \"    \\n\",\n    \"print(cnn)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Load image\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Target imsize \\n\",\n    \"imsize = 227 if pretrained_net == 'alexnet' else 224\\n\",\n    \"\\n\",\n    \"# Something divisible by a power of two\\n\",\n    \"imsize_net = 256\\n\",\n    \"\\n\",\n    \"# VGG and Alexnet need input to be correctly normalized\\n\",\n    \"preprocess, deprocess = get_preprocessor(imsize), get_deprocessor()\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"img_content_pil, img_content_np  = get_image(fname, imsize)\\n\",\n    \"img_content_prerocessed = preprocess(img_content_pil)[None,:].type(dtype)\\n\",\n    \"\\n\",\n    \"img_content_pil\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Setup matcher and net\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"scrolled\": false\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"matcher_content = get_matcher(cnn, opt_content)\\n\",\n    \"\\n\",\n    \"matcher_content.mode = 'store'\\n\",\n    \"cnn(img_content_prerocessed);\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"INPUT = 'noise'\\n\",\n    \"pad = 'zero' # 'refection'\\n\",\n    \"OPT_OVER = 'net' #'net,input'\\n\",\n    \"OPTIMIZER = 'adam' # 'LBFGS'\\n\",\n    \"LR = 0.001\\n\",\n    \"\\n\",\n    \"num_iter = 3100\\n\",\n    \"\\n\",\n    \"input_depth = 32\\n\",\n    \"net_input = get_noise(input_depth, INPUT, imsize_net).type(dtype).detach()\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"net = skip(input_depth, 3, num_channels_down = [16, 32, 64, 128, 128, 128],\\n\",\n    \"                           num_channels_up =   [16, 32, 64, 128, 128, 128],\\n\",\n    \"                           num_channels_skip = [4, 4, 4, 4, 4, 4],   \\n\",\n    \"                           filter_size_down = [7, 7, 5, 5, 3, 3], filter_size_up = [7, 7, 5, 5, 3, 3], \\n\",\n    \"                           upsample_mode='nearest', downsample_mode='avg',\\n\",\n    \"                           need_sigmoid=True, pad=pad, act_fun='LeakyReLU').type(dtype)\\n\",\n    \"\\n\",\n    \"# Compute number of parameters\\n\",\n    \"s  = sum(np.prod(list(p.size())) for p in net.parameters())\\n\",\n    \"print ('Number of params: %d' % s)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Optimize\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def closure():\\n\",\n    \"    \\n\",\n    \"    global i\\n\",\n    \"           \\n\",\n    \"    out = net(net_input)[:, :, :imsize, :imsize]\\n\",\n    \"    \\n\",\n    \"    cnn(vgg_preprocess_var(out))\\n\",\n    \"    total_loss =  sum(matcher_content.losses.values())\\n\",\n    \"    total_loss.backward()\\n\",\n    \"    \\n\",\n    \"    print ('Iteration %05d    Loss %.3f' % (i, total_loss.item()), '\\\\r', end='')\\n\",\n    \"    if PLOT and i % 200 == 0:\\n\",\n    \"        out_np = np.clip(torch_to_np(out), 0, 1)\\n\",\n    \"        plot_image_grid([out_np], 3, 3);\\n\",\n    \"\\n\",\n    \"    i += 1\\n\",\n    \"    \\n\",\n    \"    return total_loss\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"i=0\\n\",\n    \"matcher_content.mode = 'match'\\n\",\n    \"p = get_params(OPT_OVER, net, net_input)\\n\",\n    \"optimize(OPTIMIZER, p, closure, LR, num_iter)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Result\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"out = net(net_input)[:, :, :imsize, :imsize]\\n\",\n    \"plot_image_grid([torch_to_np(out)], 3, 3);\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"The code above was used to produce the images from the paper.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Appedndix: more noise\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"We also found adding heavy noise sometimes improves the results (see below). Interestingly, network manages to adapt to a very heavy noise.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"input_depth = 2\\n\",\n    \"net_input = get_noise(input_depth, INPUT, imsize_net).type(dtype).detach()\\n\",\n    \"\\n\",\n    \"net = skip(input_depth, 3, num_channels_down = [16, 32, 64, 128, 128, 128],\\n\",\n    \"                           num_channels_up =   [16, 32, 64, 128, 128, 128],\\n\",\n    \"                           num_channels_skip = [4, 4, 4, 4, 4, 4],   \\n\",\n    \"                           filter_size_up = [7, 7, 5, 5, 3, 3], filter_size_down = [7, 7, 5, 5, 3, 3],\\n\",\n    \"                           upsample_mode='nearest', downsample_mode='avg',\\n\",\n    \"                           need_sigmoid=True, need_bias=True, pad=pad, act_fun='LeakyReLU').type(dtype)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def closure():\\n\",\n    \"    \\n\",\n    \"    global i    \\n\",\n    \"    if i < 10000:\\n\",\n    \"        # Weight noise\\n\",\n    \"        for n in [x for x in net.parameters() if len(x) == 4]:\\n\",\n    \"            n = n + n.detach().clone().normal_()*n.std()/50\\n\",\n    \"        \\n\",\n    \"        # Input noise\\n\",\n    \"        net_input = net_input_saved + (noise.normal_() * 10)\\n\",\n    \"\\n\",\n    \"    elif i < 15000:\\n\",\n    \"        # Weight noise\\n\",\n    \"        for n in [x for x in net.parameters() if len(x) == 4]:\\n\",\n    \"            n = n + n.detach().clone().normal_()*n.std()/100\\n\",\n    \"        \\n\",\n    \"        # Input noise\\n\",\n    \"        net_input = net_input_saved + (noise.normal_() * 2)\\n\",\n    \"        \\n\",\n    \"    elif i < 20000:\\n\",\n    \"        # Input noise\\n\",\n    \"        net_input = net_input_saved + (noise.normal_() / 2)\\n\",\n    \"    \\n\",\n    \"    \\n\",\n    \"    out = net(net_input)[:, :, :imsize, :imsize]\\n\",\n    \"    \\n\",\n    \"    cnn(vgg_preprocess_var(out))\\n\",\n    \"    total_loss =  sum(matcher_content.losses.values())\\n\",\n    \"    total_loss.backward()\\n\",\n    \"    \\n\",\n    \"    print ('Iteration %05d    Loss %.3f' % (i, total_loss.item()), '\\\\r', end='')\\n\",\n    \"    if PLOT and i % 1000==0:\\n\",\n    \"        out_np = np.clip(torch_to_np(out), 0, 1)\\n\",\n    \"        plot_image_grid([out_np], 3, 3);\\n\",\n    \"\\n\",\n    \"    i += 1\\n\",\n    \"    \\n\",\n    \"    return total_loss\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"num_iter = 20000\\n\",\n    \"LR = 0.01\\n\",\n    \"\\n\",\n    \"net_input_saved = net_input.detach().clone()\\n\",\n    \"noise = net_input.detach().clone()\\n\",\n    \"i=0\\n\",\n    \"\\n\",\n    \"matcher_content.mode = 'match'\\n\",\n    \"p = get_params(OPT_OVER, net, net_input)\\n\",\n    \"optimize(OPTIMIZER, p, closure, LR, num_iter)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.6.5\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
  },
  {
    "path": "flash-no-flash.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Code for **\\\"Flash/No Flash\\\"** figure. \"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Import libs\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from __future__ import print_function\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"%matplotlib inline\\n\",\n    \"\\n\",\n    \"import os\\n\",\n    \"#os.environ['CUDA_VISIBLE_DEVICES'] = '3'\\n\",\n    \"\\n\",\n    \"import numpy as np\\n\",\n    \"from models import *\\n\",\n    \"\\n\",\n    \"import torch\\n\",\n    \"import torch.optim\\n\",\n    \"\\n\",\n    \"from utils.denoising_utils import *\\n\",\n    \"from utils.sr_utils import load_LR_HR_imgs_sr\\n\",\n    \"torch.backends.cudnn.enabled = True\\n\",\n    \"torch.backends.cudnn.benchmark =True\\n\",\n    \"dtype = torch.cuda.FloatTensor\\n\",\n    \"\\n\",\n    \"imsize =-1\\n\",\n    \"PLOT = True\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Load image\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"imgs = load_LR_HR_imgs_sr('data/flash_no_flash/cave01_00_flash.jpg', -1, 1, enforse_div32='CROP')\\n\",\n    \"img_flash = load_LR_HR_imgs_sr('data/flash_no_flash/cave01_00_flash.jpg', -1, 1, enforse_div32='CROP')['HR_pil']\\n\",\n    \"img_flash_np = pil_to_np(img_flash)\\n\",\n    \"\\n\",\n    \"img_noflash = load_LR_HR_imgs_sr('data/flash_no_flash/cave01_01_noflash.jpg', -1, 1, enforse_div32='CROP')['HR_pil']\\n\",\n    \"img_noflash_np = pil_to_np(img_noflash)\\n\",\n    \"\\n\",\n    \"g = plot_image_grid([img_flash_np, img_noflash_np],3,12)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Setup\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"pad = 'reflection'\\n\",\n    \"OPT_OVER = 'net'\\n\",\n    \"\\n\",\n    \"num_iter = 601\\n\",\n    \"LR = 0.1 \\n\",\n    \"OPTIMIZER = 'adam'\\n\",\n    \"reg_noise_std = 0.0\\n\",\n    \"show_every = 50\\n\",\n    \"figsize = 6\\n\",\n    \"\\n\",\n    \"# We will use flash image as input\\n\",\n    \"input_depth = 3\\n\",\n    \"net_input =np_to_torch(img_flash_np).type(dtype)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"net = skip(input_depth, 3, num_channels_down = [128, 128, 128, 128, 128], \\n\",\n    \"                        num_channels_up   = [128, 128, 128, 128, 128],\\n\",\n    \"                        num_channels_skip = [4, 4, 4, 4, 4], \\n\",\n    \"                        upsample_mode=['nearest', 'nearest', 'bilinear', 'bilinear', 'bilinear'], \\n\",\n    \"                        need_sigmoid=True, need_bias=True, pad=pad).type(dtype)\\n\",\n    \"\\n\",\n    \"mse = torch.nn.MSELoss().type(dtype)\\n\",\n    \"\\n\",\n    \"img_flash_var = np_to_torch(img_flash_np).type(dtype)\\n\",\n    \"img_noflash_var = np_to_torch(img_noflash_np).type(dtype)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Optimize\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"scrolled\": false\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"net_input_saved = net_input.detach().clone()\\n\",\n    \"noise = net_input.detach().clone()\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"i = 0\\n\",\n    \"def closure():\\n\",\n    \"    \\n\",\n    \"    global i, net_input\\n\",\n    \"    \\n\",\n    \"    if reg_noise_std > 0:\\n\",\n    \"        net_input = net_input_saved + (noise.normal_() * reg_noise_std)\\n\",\n    \"    \\n\",\n    \"    out = net(net_input)\\n\",\n    \"   \\n\",\n    \"    total_loss = mse(out, img_noflash_var)\\n\",\n    \"    total_loss.backward()\\n\",\n    \"        \\n\",\n    \"    print ('Iteration %05d    Loss %f' % (i, total_loss.item()), '\\\\r', end='')\\n\",\n    \"    if  PLOT and i % show_every == 0:\\n\",\n    \"        out_np = torch_to_np(out)\\n\",\n    \"        plot_image_grid([np.clip(out_np, 0, 1)], factor=figsize, nrow=1)\\n\",\n    \"        \\n\",\n    \"    i += 1\\n\",\n    \"\\n\",\n    \"    return total_loss\\n\",\n    \"\\n\",\n    \"p = get_params(OPT_OVER, net, net_input)\\n\",\n    \"optimize(OPTIMIZER, p, closure, LR, num_iter)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Sometimes the process stucks at reddish image, just run the code from the top one more time. \"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"out_np = torch_to_np(net(net_input))\\n\",\n    \"q = plot_image_grid([np.clip(out_np, 0, 1), img_noflash_np], factor=13);\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.6.5\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
  },
  {
    "path": "inpainting.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Code for **\\\"Inpainting\\\"** figures $6$, $8$ and 7 (top) from the main paper. \"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Import libs\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from __future__ import print_function\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"%matplotlib inline\\n\",\n    \"\\n\",\n    \"import os\\n\",\n    \"# os.environ['CUDA_VISIBLE_DEVICES'] = '1'\\n\",\n    \"\\n\",\n    \"import numpy as np\\n\",\n    \"from models.resnet import ResNet\\n\",\n    \"from models.unet import UNet\\n\",\n    \"from models.skip import skip\\n\",\n    \"import torch\\n\",\n    \"import torch.optim\\n\",\n    \"\\n\",\n    \"from utils.inpainting_utils import *\\n\",\n    \"\\n\",\n    \"torch.backends.cudnn.enabled = True\\n\",\n    \"torch.backends.cudnn.benchmark =True\\n\",\n    \"dtype = torch.cuda.FloatTensor\\n\",\n    \"\\n\",\n    \"PLOT = True\\n\",\n    \"imsize = -1\\n\",\n    \"dim_div_by = 64\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Choose figure\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"## Fig 6\\n\",\n    \"# img_path  = 'data/inpainting/vase.png'\\n\",\n    \"# mask_path = 'data/inpainting/vase_mask.png'\\n\",\n    \"\\n\",\n    \"## Fig 8\\n\",\n    \"# img_path  = 'data/inpainting/library.png'\\n\",\n    \"# mask_path = 'data/inpainting/library_mask.png'\\n\",\n    \"\\n\",\n    \"## Fig 7 (top)\\n\",\n    \"img_path  = 'data/inpainting/kate.png'\\n\",\n    \"mask_path = 'data/inpainting/kate_mask.png'\\n\",\n    \"\\n\",\n    \"# Another text inpainting example\\n\",\n    \"# img_path  = 'data/inpainting/peppers.png'\\n\",\n    \"# mask_path = 'data/inpainting/peppers_mask.png'\\n\",\n    \"\\n\",\n    \"NET_TYPE = 'skip_depth6' # one of skip_depth4|skip_depth2|UNET|ResNet\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Load mask\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"img_pil, img_np = get_image(img_path, imsize)\\n\",\n    \"img_mask_pil, img_mask_np = get_image(mask_path, imsize)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Center crop\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"img_mask_pil = crop_image(img_mask_pil, dim_div_by)\\n\",\n    \"img_pil      = crop_image(img_pil,      dim_div_by)\\n\",\n    \"\\n\",\n    \"img_np      = pil_to_np(img_pil)\\n\",\n    \"img_mask_np = pil_to_np(img_mask_pil)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"### Visualize\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"scrolled\": true\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"img_mask_var = np_to_torch(img_mask_np).type(dtype)\\n\",\n    \"\\n\",\n    \"plot_image_grid([img_np, img_mask_np, img_mask_np*img_np], 3,11);\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Setup\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"pad = 'reflection' # 'zero'\\n\",\n    \"OPT_OVER = 'net'\\n\",\n    \"OPTIMIZER = 'adam'\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"if 'vase.png' in img_path:\\n\",\n    \"    INPUT = 'meshgrid'\\n\",\n    \"    input_depth = 2\\n\",\n    \"    LR = 0.01 \\n\",\n    \"    num_iter = 5001\\n\",\n    \"    param_noise = False\\n\",\n    \"    show_every = 50\\n\",\n    \"    figsize = 5\\n\",\n    \"    reg_noise_std = 0.03\\n\",\n    \"    \\n\",\n    \"    net = skip(input_depth, img_np.shape[0], \\n\",\n    \"               num_channels_down = [128] * 5,\\n\",\n    \"               num_channels_up   = [128] * 5,\\n\",\n    \"               num_channels_skip = [0] * 5,  \\n\",\n    \"               upsample_mode='nearest', filter_skip_size=1, filter_size_up=3, filter_size_down=3,\\n\",\n    \"               need_sigmoid=True, need_bias=True, pad=pad, act_fun='LeakyReLU').type(dtype)\\n\",\n    \"    \\n\",\n    \"elif ('kate.png' in img_path) or ('peppers.png' in img_path):\\n\",\n    \"    # Same params and net as in super-resolution and denoising\\n\",\n    \"    INPUT = 'noise'\\n\",\n    \"    input_depth = 32\\n\",\n    \"    LR = 0.01 \\n\",\n    \"    num_iter = 6001\\n\",\n    \"    param_noise = False\\n\",\n    \"    show_every = 50\\n\",\n    \"    figsize = 5\\n\",\n    \"    reg_noise_std = 0.03\\n\",\n    \"    \\n\",\n    \"    net = skip(input_depth, img_np.shape[0], \\n\",\n    \"               num_channels_down = [128] * 5,\\n\",\n    \"               num_channels_up =   [128] * 5,\\n\",\n    \"               num_channels_skip =    [128] * 5,  \\n\",\n    \"               filter_size_up = 3, filter_size_down = 3, \\n\",\n    \"               upsample_mode='nearest', filter_skip_size=1,\\n\",\n    \"               need_sigmoid=True, need_bias=True, pad=pad, act_fun='LeakyReLU').type(dtype)\\n\",\n    \"    \\n\",\n    \"elif 'library.png' in img_path:\\n\",\n    \"    \\n\",\n    \"    INPUT = 'noise'\\n\",\n    \"    input_depth = 1\\n\",\n    \"    \\n\",\n    \"    num_iter = 3001\\n\",\n    \"    show_every = 50\\n\",\n    \"    figsize = 8\\n\",\n    \"    reg_noise_std = 0.00\\n\",\n    \"    param_noise = True\\n\",\n    \"    \\n\",\n    \"    if 'skip' in NET_TYPE:\\n\",\n    \"        \\n\",\n    \"        depth = int(NET_TYPE[-1])\\n\",\n    \"        net = skip(input_depth, img_np.shape[0], \\n\",\n    \"               num_channels_down = [16, 32, 64, 128, 128, 128][:depth],\\n\",\n    \"               num_channels_up =   [16, 32, 64, 128, 128, 128][:depth],\\n\",\n    \"               num_channels_skip =    [0, 0, 0, 0, 0, 0][:depth],  \\n\",\n    \"               filter_size_up = 3,filter_size_down = 5,  filter_skip_size=1,\\n\",\n    \"               upsample_mode='nearest', # downsample_mode='avg',\\n\",\n    \"               need1x1_up=False,\\n\",\n    \"               need_sigmoid=True, need_bias=True, pad=pad, act_fun='LeakyReLU').type(dtype)\\n\",\n    \"        \\n\",\n    \"        LR = 0.01 \\n\",\n    \"        \\n\",\n    \"    elif NET_TYPE == 'UNET':\\n\",\n    \"        \\n\",\n    \"        net = UNet(num_input_channels=input_depth, num_output_channels=3, \\n\",\n    \"                   feature_scale=8, more_layers=1, \\n\",\n    \"                   concat_x=False, upsample_mode='deconv', \\n\",\n    \"                   pad='zero', norm_layer=torch.nn.InstanceNorm2d, need_sigmoid=True, need_bias=True)\\n\",\n    \"        \\n\",\n    \"        LR = 0.001\\n\",\n    \"        param_noise = False\\n\",\n    \"        \\n\",\n    \"    elif NET_TYPE == 'ResNet':\\n\",\n    \"        \\n\",\n    \"        net = ResNet(input_depth, img_np.shape[0], 8, 32, need_sigmoid=True, act_fun='LeakyReLU')\\n\",\n    \"        \\n\",\n    \"        LR = 0.001\\n\",\n    \"        param_noise = False\\n\",\n    \"        \\n\",\n    \"    else:\\n\",\n    \"        assert False\\n\",\n    \"else:\\n\",\n    \"    assert False\\n\",\n    \"\\n\",\n    \"net = net.type(dtype)\\n\",\n    \"net_input = get_noise(input_depth, INPUT, img_np.shape[1:]).type(dtype)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Compute number of parameters\\n\",\n    \"s  = sum(np.prod(list(p.size())) for p in net.parameters())\\n\",\n    \"print ('Number of params: %d' % s)\\n\",\n    \"\\n\",\n    \"# Loss\\n\",\n    \"mse = torch.nn.MSELoss().type(dtype)\\n\",\n    \"\\n\",\n    \"img_var = np_to_torch(img_np).type(dtype)\\n\",\n    \"mask_var = np_to_torch(img_mask_np).type(dtype)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Main loop\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"scrolled\": true\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"i = 0\\n\",\n    \"def closure():\\n\",\n    \"    \\n\",\n    \"    global i\\n\",\n    \"    \\n\",\n    \"    if param_noise:\\n\",\n    \"        for n in [x for x in net.parameters() if len(x.size()) == 4]:\\n\",\n    \"            n = n + n.detach().clone().normal_() * n.std() / 50\\n\",\n    \"    \\n\",\n    \"    net_input = net_input_saved\\n\",\n    \"    if reg_noise_std > 0:\\n\",\n    \"        net_input = net_input_saved + (noise.normal_() * reg_noise_std)\\n\",\n    \"        \\n\",\n    \"        \\n\",\n    \"    out = net(net_input)\\n\",\n    \"   \\n\",\n    \"    total_loss = mse(out * mask_var, img_var * mask_var)\\n\",\n    \"    total_loss.backward()\\n\",\n    \"        \\n\",\n    \"    print ('Iteration %05d    Loss %f' % (i, total_loss.item()), '\\\\r', end='')\\n\",\n    \"    if  PLOT and i % show_every == 0:\\n\",\n    \"        out_np = torch_to_np(out)\\n\",\n    \"        plot_image_grid([np.clip(out_np, 0, 1)], factor=figsize, nrow=1)\\n\",\n    \"        \\n\",\n    \"    i += 1\\n\",\n    \"\\n\",\n    \"    return total_loss\\n\",\n    \"\\n\",\n    \"net_input_saved = net_input.detach().clone()\\n\",\n    \"noise = net_input.detach().clone()\\n\",\n    \"\\n\",\n    \"p = get_params(OPT_OVER, net, net_input)\\n\",\n    \"optimize(OPTIMIZER, p, closure, LR, num_iter)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"out_np = torch_to_np(net(net_input))\\n\",\n    \"plot_image_grid([out_np], factor=5);\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.6.5\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
  },
  {
    "path": "models/__init__.py",
    "content": "from .skip import skip\nfrom .texture_nets import get_texture_nets\nfrom .resnet import ResNet\nfrom .unet import UNet\n\nimport torch.nn as nn\n\ndef get_net(input_depth, NET_TYPE, pad, upsample_mode, n_channels=3, act_fun='LeakyReLU', skip_n33d=128, skip_n33u=128, skip_n11=4, num_scales=5, downsample_mode='stride'):\n    if NET_TYPE == 'ResNet':\n        # TODO\n        net = ResNet(input_depth, 3, 10, 16, 1, nn.BatchNorm2d, False)\n    elif NET_TYPE == 'skip':\n        net = skip(input_depth, n_channels, num_channels_down = [skip_n33d]*num_scales if isinstance(skip_n33d, int) else skip_n33d,\n                                            num_channels_up =   [skip_n33u]*num_scales if isinstance(skip_n33u, int) else skip_n33u,\n                                            num_channels_skip = [skip_n11]*num_scales if isinstance(skip_n11, int) else skip_n11, \n                                            upsample_mode=upsample_mode, downsample_mode=downsample_mode,\n                                            need_sigmoid=True, need_bias=True, pad=pad, act_fun=act_fun)\n\n    elif NET_TYPE == 'texture_nets':\n        net = get_texture_nets(inp=input_depth, ratios = [32, 16, 8, 4, 2, 1], fill_noise=False,pad=pad)\n\n    elif NET_TYPE =='UNet':\n        net = UNet(num_input_channels=input_depth, num_output_channels=3, \n                   feature_scale=4, more_layers=0, concat_x=False,\n                   upsample_mode=upsample_mode, pad=pad, norm_layer=nn.BatchNorm2d, need_sigmoid=True, need_bias=True)\n    elif NET_TYPE == 'identity':\n        assert input_depth == 3\n        net = nn.Sequential()\n    else:\n        assert False\n\n    return net"
  },
  {
    "path": "models/common.py",
    "content": "import torch\nimport torch.nn as nn\nimport numpy as np\nfrom .downsampler import Downsampler\n\ndef add_module(self, module):\n    self.add_module(str(len(self) + 1), module)\n    \ntorch.nn.Module.add = add_module\n\nclass Concat(nn.Module):\n    def __init__(self, dim, *args):\n        super(Concat, self).__init__()\n        self.dim = dim\n\n        for idx, module in enumerate(args):\n            self.add_module(str(idx), module)\n\n    def forward(self, input):\n        inputs = []\n        for module in self._modules.values():\n            inputs.append(module(input))\n\n        inputs_shapes2 = [x.shape[2] for x in inputs]\n        inputs_shapes3 = [x.shape[3] for x in inputs]        \n\n        if np.all(np.array(inputs_shapes2) == min(inputs_shapes2)) and np.all(np.array(inputs_shapes3) == min(inputs_shapes3)):\n            inputs_ = inputs\n        else:\n            target_shape2 = min(inputs_shapes2)\n            target_shape3 = min(inputs_shapes3)\n\n            inputs_ = []\n            for inp in inputs: \n                diff2 = (inp.size(2) - target_shape2) // 2 \n                diff3 = (inp.size(3) - target_shape3) // 2 \n                inputs_.append(inp[:, :, diff2: diff2 + target_shape2, diff3:diff3 + target_shape3])\n\n        return torch.cat(inputs_, dim=self.dim)\n\n    def __len__(self):\n        return len(self._modules)\n\n\nclass GenNoise(nn.Module):\n    def __init__(self, dim2):\n        super(GenNoise, self).__init__()\n        self.dim2 = dim2\n\n    def forward(self, input):\n        a = list(input.size())\n        a[1] = self.dim2\n        # print (input.data.type())\n\n        b = torch.zeros(a).type_as(input.data)\n        b.normal_()\n\n        x = torch.autograd.Variable(b)\n\n        return x\n\n\nclass Swish(nn.Module):\n    \"\"\"\n        https://arxiv.org/abs/1710.05941\n        The hype was so huge that I could not help but try it\n    \"\"\"\n    def __init__(self):\n        super(Swish, self).__init__()\n        self.s = nn.Sigmoid()\n\n    def forward(self, x):\n        return x * self.s(x)\n\n\ndef act(act_fun = 'LeakyReLU'):\n    '''\n        Either string defining an activation function or module (e.g. nn.ReLU)\n    '''\n    if isinstance(act_fun, str):\n        if act_fun == 'LeakyReLU':\n            return nn.LeakyReLU(0.2, inplace=True)\n        elif act_fun == 'Swish':\n            return Swish()\n        elif act_fun == 'ELU':\n            return nn.ELU()\n        elif act_fun == 'none':\n            return nn.Sequential()\n        else:\n            assert False\n    else:\n        return act_fun()\n\n\ndef bn(num_features):\n    return nn.BatchNorm2d(num_features)\n\n\ndef conv(in_f, out_f, kernel_size, stride=1, bias=True, pad='zero', downsample_mode='stride'):\n    downsampler = None\n    if stride != 1 and downsample_mode != 'stride':\n\n        if downsample_mode == 'avg':\n            downsampler = nn.AvgPool2d(stride, stride)\n        elif downsample_mode == 'max':\n            downsampler = nn.MaxPool2d(stride, stride)\n        elif downsample_mode  in ['lanczos2', 'lanczos3']:\n            downsampler = Downsampler(n_planes=out_f, factor=stride, kernel_type=downsample_mode, phase=0.5, preserve_size=True)\n        else:\n            assert False\n\n        stride = 1\n\n    padder = None\n    to_pad = int((kernel_size - 1) / 2)\n    if pad == 'reflection':\n        padder = nn.ReflectionPad2d(to_pad)\n        to_pad = 0\n  \n    convolver = nn.Conv2d(in_f, out_f, kernel_size, stride, padding=to_pad, bias=bias)\n\n\n    layers = filter(lambda x: x is not None, [padder, convolver, downsampler])\n    return nn.Sequential(*layers)"
  },
  {
    "path": "models/dcgan.py",
    "content": "import torch\nimport torch.nn as nn \n\ndef dcgan(inp=2,\n          ndf=32,\n          num_ups=4, need_sigmoid=True, need_bias=True, pad='zero', upsample_mode='nearest', need_convT = True):\n    \n    layers= [nn.ConvTranspose2d(inp, ndf, kernel_size=3, stride=1, padding=0, bias=False),\n             nn.BatchNorm2d(ndf),\n             nn.LeakyReLU(True)]\n    \n    for i in range(num_ups-3):\n        if need_convT:\n            layers += [ nn.ConvTranspose2d(ndf, ndf, kernel_size=4, stride=2, padding=1, bias=False),\n                        nn.BatchNorm2d(ndf),\n                        nn.LeakyReLU(True)]\n        else:\n            layers += [ nn.Upsample(scale_factor=2, mode=upsample_mode),\n                        nn.Conv2d(ndf, ndf, kernel_size=3, stride=1, padding=1, bias=False),\n                        nn.BatchNorm2d(ndf),\n                        nn.LeakyReLU(True)]\n            \n    if need_convT:\n        layers += [nn.ConvTranspose2d(ndf, 3, 4, 2, 1, bias=False),]\n    else:\n        layers += [nn.Upsample(scale_factor=2, mode='bilinear'),\n                   nn.Conv2d(ndf, 3, kernel_size=3, stride=1, padding=1, bias=False)]\n    \n    \n    if need_sigmoid:\n        layers += [nn.Sigmoid()]\n\n    model =nn.Sequential(*layers)\n    return model"
  },
  {
    "path": "models/downsampler.py",
    "content": "import numpy as np\nimport torch\nimport torch.nn as nn \n\nclass Downsampler(nn.Module):\n    '''\n        http://www.realitypixels.com/turk/computergraphics/ResamplingFilters.pdf\n    '''\n    def __init__(self, n_planes, factor, kernel_type, phase=0, kernel_width=None, support=None, sigma=None, preserve_size=False):\n        super(Downsampler, self).__init__()\n        \n        assert phase in [0, 0.5], 'phase should be 0 or 0.5'\n\n        if kernel_type == 'lanczos2':\n            support = 2\n            kernel_width = 4 * factor + 1\n            kernel_type_ = 'lanczos'\n\n        elif kernel_type == 'lanczos3':\n            support = 3\n            kernel_width = 6 * factor + 1\n            kernel_type_ = 'lanczos'\n\n        elif kernel_type == 'gauss12':\n            kernel_width = 7\n            sigma = 1/2\n            kernel_type_ = 'gauss'\n\n        elif kernel_type == 'gauss1sq2':\n            kernel_width = 9\n            sigma = 1./np.sqrt(2)\n            kernel_type_ = 'gauss'\n\n        elif kernel_type in ['lanczos', 'gauss', 'box']:\n            kernel_type_ = kernel_type\n\n        else:\n            assert False, 'wrong name kernel'\n            \n            \n        # note that `kernel width` will be different to actual size for phase = 1/2\n        self.kernel = get_kernel(factor, kernel_type_, phase, kernel_width, support=support, sigma=sigma)\n        \n        downsampler = nn.Conv2d(n_planes, n_planes, kernel_size=self.kernel.shape, stride=factor, padding=0)\n        downsampler.weight.data[:] = 0\n        downsampler.bias.data[:] = 0\n\n        kernel_torch = torch.from_numpy(self.kernel)\n        for i in range(n_planes):\n            downsampler.weight.data[i, i] = kernel_torch       \n\n        self.downsampler_ = downsampler\n\n        if preserve_size:\n\n            if  self.kernel.shape[0] % 2 == 1: \n                pad = int((self.kernel.shape[0] - 1) / 2.)\n            else:\n                pad = int((self.kernel.shape[0] - factor) / 2.)\n                \n            self.padding = nn.ReplicationPad2d(pad)\n        \n        self.preserve_size = preserve_size\n        \n    def forward(self, input):\n        if self.preserve_size:\n            x = self.padding(input)\n        else:\n            x= input\n        self.x = x\n        return self.downsampler_(x)\n        \ndef get_kernel(factor, kernel_type, phase, kernel_width, support=None, sigma=None):\n    assert kernel_type in ['lanczos', 'gauss', 'box']\n    \n    # factor  = float(factor)\n    if phase == 0.5 and kernel_type != 'box': \n        kernel = np.zeros([kernel_width - 1, kernel_width - 1])\n    else:\n        kernel = np.zeros([kernel_width, kernel_width])\n    \n        \n    if kernel_type == 'box':\n        assert phase == 0.5, 'Box filter is always half-phased'\n        kernel[:] = 1./(kernel_width * kernel_width)\n        \n    elif kernel_type == 'gauss': \n        assert sigma, 'sigma is not specified'\n        assert phase != 0.5, 'phase 1/2 for gauss not implemented'\n        \n        center = (kernel_width + 1.)/2.\n        print(center, kernel_width)\n        sigma_sq =  sigma * sigma\n        \n        for i in range(1, kernel.shape[0] + 1):\n            for j in range(1, kernel.shape[1] + 1):\n                di = (i - center)/2.\n                dj = (j - center)/2.\n                kernel[i - 1][j - 1] = np.exp(-(di * di + dj * dj)/(2 * sigma_sq))\n                kernel[i - 1][j - 1] = kernel[i - 1][j - 1]/(2. * np.pi * sigma_sq)\n    elif kernel_type == 'lanczos': \n        assert support, 'support is not specified'\n        center = (kernel_width + 1) / 2.\n\n        for i in range(1, kernel.shape[0] + 1):\n            for j in range(1, kernel.shape[1] + 1):\n                \n                if phase == 0.5:\n                    di = abs(i + 0.5 - center) / factor  \n                    dj = abs(j + 0.5 - center) / factor \n                else:\n                    di = abs(i - center) / factor\n                    dj = abs(j - center) / factor\n                \n                \n                pi_sq = np.pi * np.pi\n\n                val = 1\n                if di != 0:\n                    val = val * support * np.sin(np.pi * di) * np.sin(np.pi * di / support)\n                    val = val / (np.pi * np.pi * di * di)\n                \n                if dj != 0:\n                    val = val * support * np.sin(np.pi * dj) * np.sin(np.pi * dj / support)\n                    val = val / (np.pi * np.pi * dj * dj)\n                \n                kernel[i - 1][j - 1] = val\n            \n        \n    else:\n        assert False, 'wrong method name'\n    \n    kernel /= kernel.sum()\n    \n    return kernel\n\n#a = Downsampler(n_planes=3, factor=2, kernel_type='lanczos2', phase='1', preserve_size=True)\n\n\n\n\n\n\n#################\n# Learnable downsampler\n\n# KS = 32\n# dow = nn.Sequential(nn.ReplicationPad2d(int((KS - factor) / 2.)), nn.Conv2d(1,1,KS,factor))\n    \n# class Apply(nn.Module):\n#     def __init__(self, what, dim, *args):\n#         super(Apply, self).__init__()\n#         self.dim = dim\n    \n#         self.what = what\n\n#     def forward(self, input):\n#         inputs = []\n#         for i in range(input.size(self.dim)):\n#             inputs.append(self.what(input.narrow(self.dim, i, 1)))\n\n#         return torch.cat(inputs, dim=self.dim)\n\n#     def __len__(self):\n#         return len(self._modules)\n    \n# downs = Apply(dow, 1)\n# downs.type(dtype)(net_input.type(dtype)).size()\n"
  },
  {
    "path": "models/resnet.py",
    "content": "import torch\nimport torch.nn as nn\nfrom numpy.random import normal\nfrom numpy.linalg import svd\nfrom math import sqrt\nimport torch.nn.init\nfrom .common import *\n\nclass ResidualSequential(nn.Sequential):\n    def __init__(self, *args):\n        super(ResidualSequential, self).__init__(*args)\n\n    def forward(self, x):\n        out = super(ResidualSequential, self).forward(x)\n        # print(x.size(), out.size())\n        x_ = None\n        if out.size(2) != x.size(2) or out.size(3) != x.size(3):\n            diff2 = x.size(2) - out.size(2)\n            diff3 = x.size(3) - out.size(3)\n            # print(1)\n            x_ = x[:, :, diff2 /2:out.size(2) + diff2 / 2, diff3 / 2:out.size(3) + diff3 / 2]\n        else:\n            x_ = x\n        return out + x_\n\n    def eval(self):\n        print(2)\n        for m in self.modules():\n            m.eval()\n        exit()\n\n\ndef get_block(num_channels, norm_layer, act_fun):\n    layers = [\n        nn.Conv2d(num_channels, num_channels, 3, 1, 1, bias=False),\n        norm_layer(num_channels, affine=True),\n        act(act_fun),\n        nn.Conv2d(num_channels, num_channels, 3, 1, 1, bias=False),\n        norm_layer(num_channels, affine=True),\n    ]\n    return layers\n\n\nclass ResNet(nn.Module):\n    def __init__(self, num_input_channels, num_output_channels, num_blocks, num_channels, need_residual=True, act_fun='LeakyReLU', need_sigmoid=True, norm_layer=nn.BatchNorm2d, pad='reflection'):\n        '''\n            pad = 'start|zero|replication'\n        '''\n        super(ResNet, self).__init__()\n\n        if need_residual:\n            s = ResidualSequential\n        else:\n            s = nn.Sequential\n\n        stride = 1\n        # First layers\n        layers = [\n            # nn.ReplicationPad2d(num_blocks * 2 * stride + 3),\n            conv(num_input_channels, num_channels, 3, stride=1, bias=True, pad=pad),\n            act(act_fun)\n        ]\n        # Residual blocks\n        # layers_residual = []\n        for i in range(num_blocks):\n            layers += [s(*get_block(num_channels, norm_layer, act_fun))]\n       \n        layers += [\n            nn.Conv2d(num_channels, num_channels, 3, 1, 1),\n            norm_layer(num_channels, affine=True)\n        ]\n\n        # if need_residual:\n        #     layers += [ResidualSequential(*layers_residual)]\n        # else:\n        #     layers += [Sequential(*layers_residual)]\n\n        # if factor >= 2: \n        #     # Do upsampling if needed\n        #     layers += [\n        #         nn.Conv2d(num_channels, num_channels *\n        #                   factor ** 2, 3, 1),\n        #         nn.PixelShuffle(factor),\n        #         act(act_fun)\n        #     ]\n        layers += [\n            conv(num_channels, num_output_channels, 3, 1, bias=True, pad=pad),\n            nn.Sigmoid()\n        ]\n        self.model = nn.Sequential(*layers)\n\n    def forward(self, input):\n        return self.model(input)\n\n    def eval(self):\n        self.model.eval()\n"
  },
  {
    "path": "models/skip.py",
    "content": "import torch\nimport torch.nn as nn\nfrom .common import *\n\ndef skip(\n        num_input_channels=2, num_output_channels=3, \n        num_channels_down=[16, 32, 64, 128, 128], num_channels_up=[16, 32, 64, 128, 128], num_channels_skip=[4, 4, 4, 4, 4], \n        filter_size_down=3, filter_size_up=3, filter_skip_size=1,\n        need_sigmoid=True, need_bias=True, \n        pad='zero', upsample_mode='nearest', downsample_mode='stride', act_fun='LeakyReLU', \n        need1x1_up=True):\n    \"\"\"Assembles encoder-decoder with skip connections.\n\n    Arguments:\n        act_fun: Either string 'LeakyReLU|Swish|ELU|none' or module (e.g. nn.ReLU)\n        pad (string): zero|reflection (default: 'zero')\n        upsample_mode (string): 'nearest|bilinear' (default: 'nearest')\n        downsample_mode (string): 'stride|avg|max|lanczos2' (default: 'stride')\n\n    \"\"\"\n    assert len(num_channels_down) == len(num_channels_up) == len(num_channels_skip)\n\n    n_scales = len(num_channels_down) \n\n    if not (isinstance(upsample_mode, list) or isinstance(upsample_mode, tuple)) :\n        upsample_mode   = [upsample_mode]*n_scales\n\n    if not (isinstance(downsample_mode, list)or isinstance(downsample_mode, tuple)):\n        downsample_mode   = [downsample_mode]*n_scales\n    \n    if not (isinstance(filter_size_down, list) or isinstance(filter_size_down, tuple)) :\n        filter_size_down   = [filter_size_down]*n_scales\n\n    if not (isinstance(filter_size_up, list) or isinstance(filter_size_up, tuple)) :\n        filter_size_up   = [filter_size_up]*n_scales\n\n    last_scale = n_scales - 1 \n\n    cur_depth = None\n\n    model = nn.Sequential()\n    model_tmp = model\n\n    input_depth = num_input_channels\n    for i in range(len(num_channels_down)):\n\n        deeper = nn.Sequential()\n        skip = nn.Sequential()\n\n        if num_channels_skip[i] != 0:\n            model_tmp.add(Concat(1, skip, deeper))\n        else:\n            model_tmp.add(deeper)\n        \n        model_tmp.add(bn(num_channels_skip[i] + (num_channels_up[i + 1] if i < last_scale else num_channels_down[i])))\n\n        if num_channels_skip[i] != 0:\n            skip.add(conv(input_depth, num_channels_skip[i], filter_skip_size, bias=need_bias, pad=pad))\n            skip.add(bn(num_channels_skip[i]))\n            skip.add(act(act_fun))\n            \n        # skip.add(Concat(2, GenNoise(nums_noise[i]), skip_part))\n\n        deeper.add(conv(input_depth, num_channels_down[i], filter_size_down[i], 2, bias=need_bias, pad=pad, downsample_mode=downsample_mode[i]))\n        deeper.add(bn(num_channels_down[i]))\n        deeper.add(act(act_fun))\n\n        deeper.add(conv(num_channels_down[i], num_channels_down[i], filter_size_down[i], bias=need_bias, pad=pad))\n        deeper.add(bn(num_channels_down[i]))\n        deeper.add(act(act_fun))\n\n        deeper_main = nn.Sequential()\n\n        if i == len(num_channels_down) - 1:\n            # The deepest\n            k = num_channels_down[i]\n        else:\n            deeper.add(deeper_main)\n            k = num_channels_up[i + 1]\n\n        deeper.add(nn.Upsample(scale_factor=2, mode=upsample_mode[i]))\n\n        model_tmp.add(conv(num_channels_skip[i] + k, num_channels_up[i], filter_size_up[i], 1, bias=need_bias, pad=pad))\n        model_tmp.add(bn(num_channels_up[i]))\n        model_tmp.add(act(act_fun))\n\n\n        if need1x1_up:\n            model_tmp.add(conv(num_channels_up[i], num_channels_up[i], 1, bias=need_bias, pad=pad))\n            model_tmp.add(bn(num_channels_up[i]))\n            model_tmp.add(act(act_fun))\n\n        input_depth = num_channels_down[i]\n        model_tmp = deeper_main\n\n    model.add(conv(num_channels_up[0], num_output_channels, 1, bias=need_bias, pad=pad))\n    if need_sigmoid:\n        model.add(nn.Sigmoid())\n\n    return model\n"
  },
  {
    "path": "models/texture_nets.py",
    "content": "import torch\nimport torch.nn as nn\nfrom .common import * \n\n\nnormalization = nn.BatchNorm2d\n\n\ndef conv(in_f, out_f, kernel_size, stride=1, bias=True, pad='zero'):\n    if pad == 'zero':\n        return nn.Conv2d(in_f, out_f, kernel_size, stride, padding=(kernel_size - 1) / 2, bias=bias)\n    elif pad == 'reflection':\n        layers = [nn.ReflectionPad2d((kernel_size - 1) / 2),\n                  nn.Conv2d(in_f, out_f, kernel_size, stride, padding=0, bias=bias)]\n        return nn.Sequential(*layers)\n\ndef get_texture_nets(inp=3, ratios = [32, 16, 8, 4, 2, 1], fill_noise=False, pad='zero', need_sigmoid=False, conv_num=8, upsample_mode='nearest'):\n\n\n    for i in range(len(ratios)):\n        j = i + 1\n\n        seq = nn.Sequential()\n\n        tmp =  nn.AvgPool2d(ratios[i], ratios[i])\n\n        seq.add(tmp)\n        if fill_noise:\n            seq.add(GenNoise(inp))\n\n        seq.add(conv(inp, conv_num, 3, pad=pad))\n        seq.add(normalization(conv_num))\n        seq.add(act())\n\n        seq.add(conv(conv_num, conv_num, 3, pad=pad))\n        seq.add(normalization(conv_num))\n        seq.add(act())\n\n        seq.add(conv(conv_num, conv_num, 1, pad=pad))\n        seq.add(normalization(conv_num))\n        seq.add(act())\n\n        if i == 0:\n            seq.add(nn.Upsample(scale_factor=2, mode=upsample_mode))\n            cur = seq\n        else:\n\n            cur_temp = cur\n\n            cur = nn.Sequential()\n\n            # Batch norm before merging \n            seq.add(normalization(conv_num))\n            cur_temp.add(normalization(conv_num * (j - 1)))\n\n            cur.add(Concat(1, cur_temp, seq))\n\n            cur.add(conv(conv_num * j, conv_num * j, 3, pad=pad))\n            cur.add(normalization(conv_num * j))\n            cur.add(act())\n\n            cur.add(conv(conv_num * j, conv_num * j, 3, pad=pad))\n            cur.add(normalization(conv_num * j))\n            cur.add(act())\n\n            cur.add(conv(conv_num * j, conv_num * j, 1, pad=pad))\n            cur.add(normalization(conv_num * j))\n            cur.add(act())\n\n            if i == len(ratios) - 1: \n                cur.add(conv(conv_num * j, 3, 1, pad=pad))\n            else:\n                cur.add(nn.Upsample(scale_factor=2, mode=upsample_mode)) \n            \n    model = cur\n    if need_sigmoid:\n        model.add(nn.Sigmoid())\n\n    return model\n"
  },
  {
    "path": "models/unet.py",
    "content": "import torch.nn as nn\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom .common import * \n\nclass ListModule(nn.Module):\n    def __init__(self, *args):\n        super(ListModule, self).__init__()\n        idx = 0\n        for module in args:\n            self.add_module(str(idx), module)\n            idx += 1\n\n    def __getitem__(self, idx):\n        if idx >= len(self._modules):\n            raise IndexError('index {} is out of range'.format(idx))\n        if idx < 0: \n            idx = len(self) + idx\n\n        it = iter(self._modules.values())\n        for i in range(idx):\n            next(it)\n        return next(it)\n\n    def __iter__(self):\n        return iter(self._modules.values())\n\n    def __len__(self):\n        return len(self._modules)\n\nclass UNet(nn.Module):\n    '''\n        upsample_mode in ['deconv', 'nearest', 'bilinear']\n        pad in ['zero', 'replication', 'none']\n    '''\n    def __init__(self, num_input_channels=3, num_output_channels=3, \n                       feature_scale=4, more_layers=0, concat_x=False,\n                       upsample_mode='deconv', pad='zero', norm_layer=nn.InstanceNorm2d, need_sigmoid=True, need_bias=True):\n        super(UNet, self).__init__()\n\n        self.feature_scale = feature_scale\n        self.more_layers = more_layers\n        self.concat_x = concat_x\n\n\n        filters = [64, 128, 256, 512, 1024]\n        filters = [x // self.feature_scale for x in filters]\n\n        self.start = unetConv2(num_input_channels, filters[0] if not concat_x else filters[0] - num_input_channels, norm_layer, need_bias, pad)\n\n        self.down1 = unetDown(filters[0], filters[1] if not concat_x else filters[1] - num_input_channels, norm_layer, need_bias, pad)\n        self.down2 = unetDown(filters[1], filters[2] if not concat_x else filters[2] - num_input_channels, norm_layer, need_bias, pad)\n        self.down3 = unetDown(filters[2], filters[3] if not concat_x else filters[3] - num_input_channels, norm_layer, need_bias, pad)\n        self.down4 = unetDown(filters[3], filters[4] if not concat_x else filters[4] - num_input_channels, norm_layer, need_bias, pad)\n\n        # more downsampling layers\n        if self.more_layers > 0:\n            self.more_downs = [\n                unetDown(filters[4], filters[4] if not concat_x else filters[4] - num_input_channels , norm_layer, need_bias, pad) for i in range(self.more_layers)]\n            self.more_ups = [unetUp(filters[4], upsample_mode, need_bias, pad, same_num_filt =True) for i in range(self.more_layers)]\n\n            self.more_downs = ListModule(*self.more_downs)\n            self.more_ups   = ListModule(*self.more_ups)\n\n        self.up4 = unetUp(filters[3], upsample_mode, need_bias, pad)\n        self.up3 = unetUp(filters[2], upsample_mode, need_bias, pad)\n        self.up2 = unetUp(filters[1], upsample_mode, need_bias, pad)\n        self.up1 = unetUp(filters[0], upsample_mode, need_bias, pad)\n\n        self.final = conv(filters[0], num_output_channels, 1, bias=need_bias, pad=pad)\n\n        if need_sigmoid: \n            self.final = nn.Sequential(self.final, nn.Sigmoid())\n\n    def forward(self, inputs):\n\n        # Downsample \n        downs = [inputs]\n        down = nn.AvgPool2d(2, 2)\n        for i in range(4 + self.more_layers):\n            downs.append(down(downs[-1]))\n\n        in64 = self.start(inputs)\n        if self.concat_x:\n            in64 = torch.cat([in64, downs[0]], 1)\n\n        down1 = self.down1(in64)\n        if self.concat_x:\n            down1 = torch.cat([down1, downs[1]], 1)\n\n        down2 = self.down2(down1)\n        if self.concat_x:\n            down2 = torch.cat([down2, downs[2]], 1)\n\n        down3 = self.down3(down2)\n        if self.concat_x:\n            down3 = torch.cat([down3, downs[3]], 1)\n\n        down4 = self.down4(down3)\n        if self.concat_x:\n            down4 = torch.cat([down4, downs[4]], 1)\n\n        if self.more_layers > 0:\n            prevs = [down4]\n            for kk, d in enumerate(self.more_downs):\n                # print(prevs[-1].size())\n                out = d(prevs[-1])\n                if self.concat_x:\n                    out = torch.cat([out,  downs[kk + 5]], 1)\n\n                prevs.append(out)\n\n            up_ = self.more_ups[-1](prevs[-1], prevs[-2])\n            for idx in range(self.more_layers - 1):\n                l = self.more_ups[self.more - idx - 2]\n                up_= l(up_, prevs[self.more - idx - 2])\n        else:\n            up_= down4\n\n        up4= self.up4(up_, down3)\n        up3= self.up3(up4, down2)\n        up2= self.up2(up3, down1)\n        up1= self.up1(up2, in64)\n\n        return self.final(up1)\n\n\n\nclass unetConv2(nn.Module):\n    def __init__(self, in_size, out_size, norm_layer, need_bias, pad):\n        super(unetConv2, self).__init__()\n\n        print(pad)\n        if norm_layer is not None:\n            self.conv1= nn.Sequential(conv(in_size, out_size, 3, bias=need_bias, pad=pad),\n                                       norm_layer(out_size),\n                                       nn.ReLU(),)\n            self.conv2= nn.Sequential(conv(out_size, out_size, 3, bias=need_bias, pad=pad),\n                                       norm_layer(out_size),\n                                       nn.ReLU(),)\n        else:\n            self.conv1= nn.Sequential(conv(in_size, out_size, 3, bias=need_bias, pad=pad),\n                                       nn.ReLU(),)\n            self.conv2= nn.Sequential(conv(out_size, out_size, 3, bias=need_bias, pad=pad),\n                                       nn.ReLU(),)\n    def forward(self, inputs):\n        outputs= self.conv1(inputs)\n        outputs= self.conv2(outputs)\n        return outputs\n\n\nclass unetDown(nn.Module):\n    def __init__(self, in_size, out_size, norm_layer, need_bias, pad):\n        super(unetDown, self).__init__()\n        self.conv= unetConv2(in_size, out_size, norm_layer, need_bias, pad)\n        self.down= nn.MaxPool2d(2, 2)\n\n    def forward(self, inputs):\n        outputs= self.down(inputs)\n        outputs= self.conv(outputs)\n        return outputs\n\n\nclass unetUp(nn.Module):\n    def __init__(self, out_size, upsample_mode, need_bias, pad, same_num_filt=False):\n        super(unetUp, self).__init__()\n\n        num_filt = out_size if same_num_filt else out_size * 2\n        if upsample_mode == 'deconv':\n            self.up= nn.ConvTranspose2d(num_filt, out_size, 4, stride=2, padding=1)\n            self.conv= unetConv2(out_size * 2, out_size, None, need_bias, pad)\n        elif upsample_mode=='bilinear' or upsample_mode=='nearest':\n            self.up = nn.Sequential(nn.Upsample(scale_factor=2, mode=upsample_mode),\n                                   conv(num_filt, out_size, 3, bias=need_bias, pad=pad))\n            self.conv= unetConv2(out_size * 2, out_size, None, need_bias, pad)\n        else:\n            assert False\n\n    def forward(self, inputs1, inputs2):\n        in1_up= self.up(inputs1)\n        \n        if (inputs2.size(2) != in1_up.size(2)) or (inputs2.size(3) != in1_up.size(3)):\n            diff2 = (inputs2.size(2) - in1_up.size(2)) // 2 \n            diff3 = (inputs2.size(3) - in1_up.size(3)) // 2 \n            inputs2_ = inputs2[:, :, diff2 : diff2 + in1_up.size(2), diff3 : diff3 + in1_up.size(3)]\n        else:\n            inputs2_ = inputs2\n\n        output= self.conv(torch.cat([in1_up, inputs2_], 1))\n\n        return output\n"
  },
  {
    "path": "restoration.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Code for the figures, where an image is restored from a fraction of pixels (fig. 7 bottom, fig. 14 of supmat).\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Import libs\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from __future__ import print_function\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"%matplotlib inline\\n\",\n    \"\\n\",\n    \"import os\\n\",\n    \"#os.environ['CUDA_VISIBLE_DEVICES'] = '1'\\n\",\n    \"\\n\",\n    \"import numpy as np\\n\",\n    \"from models.resnet import ResNet\\n\",\n    \"from models.unet import UNet\\n\",\n    \"from models.skip import skip\\n\",\n    \"from models import get_net\\n\",\n    \"import torch\\n\",\n    \"import torch.optim\\n\",\n    \"from skimage.measure import compare_psnr\\n\",\n    \"\\n\",\n    \"from utils.inpainting_utils import *\\n\",\n    \"\\n\",\n    \"torch.backends.cudnn.enabled = True\\n\",\n    \"torch.backends.cudnn.benchmark =True\\n\",\n    \"dtype = torch.cuda.FloatTensor\\n\",\n    \"\\n\",\n    \"PLOT = True\\n\",\n    \"imsize=-1\\n\",\n    \"dim_div_by = 64\\n\",\n    \"dtype = torch.cuda.FloatTensor\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Choose figure\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# fig. 7 (bottom)\\n\",\n    \"f = './data/restoration/barbara.png'\\n\",\n    \"\\n\",\n    \"# fig. 14 of supmat\\n\",\n    \"# f = './data/restoration/kate.png'\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"img_pil, img_np = get_image(f, imsize)\\n\",\n    \"\\n\",\n    \"if 'barbara' in f:\\n\",\n    \"    img_np = nn.ReflectionPad2d(1)(np_to_torch(img_np))[0].numpy()\\n\",\n    \"    img_pil = np_to_pil(img_np)\\n\",\n    \"    \\n\",\n    \"    img_mask = get_bernoulli_mask(img_pil, 0.50)\\n\",\n    \"    img_mask_np = pil_to_np(img_mask)\\n\",\n    \"elif 'kate' in f:\\n\",\n    \"    img_mask = get_bernoulli_mask(img_pil, 0.98)\\n\",\n    \"\\n\",\n    \"    img_mask_np = pil_to_np(img_mask)\\n\",\n    \"    img_mask_np[1] = img_mask_np[0]\\n\",\n    \"    img_mask_np[2] = img_mask_np[0]\\n\",\n    \"else:\\n\",\n    \"    assert False\\n\",\n    \"    \\n\",\n    \"\\n\",\n    \"img_masked = img_np * img_mask_np\\n\",\n    \"\\n\",\n    \"mask_var = np_to_torch(img_mask_np).type(dtype)\\n\",\n    \"\\n\",\n    \"plot_image_grid([img_np, img_mask_np, img_mask_np * img_np], 3,11);\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Set up everything\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"show_every=50\\n\",\n    \"figsize=5\\n\",\n    \"pad = 'reflection' # 'zero'\\n\",\n    \"INPUT = 'noise'\\n\",\n    \"input_depth = 32\\n\",\n    \"OPTIMIZER = 'adam'\\n\",\n    \"OPT_OVER =  'net'\\n\",\n    \"if 'barbara' in f:\\n\",\n    \"    OPTIMIZER = 'adam'\\n\",\n    \"    \\n\",\n    \"    LR = 0.001\\n\",\n    \"    num_iter = 11000\\n\",\n    \"    reg_noise_std = 0.03\\n\",\n    \"    \\n\",\n    \"    NET_TYPE = 'skip'\\n\",\n    \"    net = get_net(input_depth, 'skip', pad, n_channels=1,\\n\",\n    \"                  skip_n33d=128, \\n\",\n    \"                  skip_n33u=128, \\n\",\n    \"                  skip_n11=4, \\n\",\n    \"                  num_scales=5,\\n\",\n    \"                  upsample_mode='bilinear').type(dtype)\\n\",\n    \"elif 'kate' in f:\\n\",\n    \"    OPT_OVER = 'net'\\n\",\n    \"    num_iter = 1000\\n\",\n    \"    LR = 0.01\\n\",\n    \"    reg_noise_std = 0.00\\n\",\n    \"        \\n\",\n    \"    net = skip(input_depth, \\n\",\n    \"               img_np.shape[0], \\n\",\n    \"               num_channels_down = [16, 32, 64, 128, 128],\\n\",\n    \"               num_channels_up   = [16, 32, 64, 128, 128],\\n\",\n    \"               num_channels_skip =    [0, 0, 0, 0, 0],   \\n\",\n    \"               filter_size_down = 3, filter_size_up = 3, filter_skip_size=1,\\n\",\n    \"               upsample_mode='bilinear', \\n\",\n    \"               downsample_mode='avg',\\n\",\n    \"               need_sigmoid=True, need_bias=True, pad=pad).type(dtype)\\n\",\n    \"    \\n\",\n    \"# Loss\\n\",\n    \"mse = torch.nn.MSELoss().type(dtype)\\n\",\n    \"img_var = np_to_torch(img_np).type(dtype)\\n\",\n    \"\\n\",\n    \"net_input = get_noise(input_depth, INPUT, img_np.shape[1:]).type(dtype).detach()\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Main loop\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def closure():\\n\",\n    \"\\n\",\n    \"    global i, psrn_masked_last, last_net, net_input\\n\",\n    \"    \\n\",\n    \"    if reg_noise_std > 0:\\n\",\n    \"        net_input = net_input_saved + (noise.normal_() * reg_noise_std)\\n\",\n    \"    \\n\",\n    \"    out = net(net_input)\\n\",\n    \"\\n\",\n    \"    total_loss = mse(out * mask_var, img_var * mask_var)\\n\",\n    \"    total_loss.backward()\\n\",\n    \"    \\n\",\n    \"    psrn_masked = compare_psnr(img_masked, out.detach().cpu().numpy()[0] * img_mask_np) \\n\",\n    \"    psrn = compare_psnr(img_np, out.detach().cpu().numpy()[0]) \\n\",\n    \"\\n\",\n    \"    print ('Iteration %05d    Loss %f PSNR_masked %f PSNR %f' % (i, total_loss.item(), psrn_masked, psrn),'\\\\r', end='')\\n\",\n    \"    \\n\",\n    \"    \\n\",\n    \"    if  PLOT and i % show_every == 0:\\n\",\n    \"        out_np = torch_to_np(out)\\n\",\n    \"        \\n\",\n    \"        # Backtracking\\n\",\n    \"        if psrn_masked - psrn_masked_last < -5: \\n\",\n    \"            print('Falling back to previous checkpoint.')\\n\",\n    \"\\n\",\n    \"            for new_param, net_param in zip(last_net, net.parameters()):\\n\",\n    \"                net_param.data.copy_(new_param.cuda())\\n\",\n    \"\\n\",\n    \"            return total_loss*0\\n\",\n    \"        else:\\n\",\n    \"            last_net = [x.cpu() for x in net.parameters()]\\n\",\n    \"            psrn_masked_last = psrn_masked\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"\\n\",\n    \"        plot_image_grid([np.clip(out_np, 0, 1)], factor=figsize, nrow=1)\\n\",\n    \"\\n\",\n    \"    i += 1\\n\",\n    \"\\n\",\n    \"    return total_loss\\n\",\n    \"\\n\",\n    \"# Init globals \\n\",\n    \"last_net = None\\n\",\n    \"psrn_masked_last = 0\\n\",\n    \"i = 0\\n\",\n    \"\\n\",\n    \"net_input_saved = net_input.detach().clone()\\n\",\n    \"noise = net_input.detach().clone()\\n\",\n    \"\\n\",\n    \"# Run\\n\",\n    \"p = get_params(OPT_OVER, net, net_input)\\n\",\n    \"optimize(OPTIMIZER, p, closure, LR=LR, num_iter=num_iter)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"out_np = torch_to_np(net(net_input))\\n\",\n    \"q = plot_image_grid([np.clip(out_np, 0, 1), img_np], factor=13);\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.6.5\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
  },
  {
    "path": "sr_prior_effect.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Code for **\\\"Prior effect\\\"** figure from supmat.\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Import libs\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from __future__ import print_function\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"%matplotlib inline\\n\",\n    \"\\n\",\n    \"import argparse\\n\",\n    \"import os\\n\",\n    \"# os.environ['CUDA_VISIBLE_DEVICES'] = '1'\\n\",\n    \"\\n\",\n    \"import numpy as np\\n\",\n    \"from models import *\\n\",\n    \"\\n\",\n    \"import torch\\n\",\n    \"import torch.optim\\n\",\n    \"\\n\",\n    \"from skimage.measure import compare_psnr\\n\",\n    \"from models.downsampler import Downsampler\\n\",\n    \"\\n\",\n    \"from utils.sr_utils import *\\n\",\n    \"\\n\",\n    \"torch.backends.cudnn.enabled = True\\n\",\n    \"torch.backends.cudnn.benchmark =True\\n\",\n    \"dtype = torch.cuda.FloatTensor\\n\",\n    \"\\n\",\n    \"imsize =-1 \\n\",\n    \"factor = 4\\n\",\n    \"enforse_div32 = 'CROP' # we usually need the dimensions to be divisible by a power of two\\n\",\n    \"\\n\",\n    \"PLOT = True\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Load image\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"fname  = 'data/sr/zebra_crop.png'\\n\",\n    \"\\n\",\n    \"imgs = load_LR_HR_imgs_sr(fname, imsize, factor, enforse_div32)\\n\",\n    \"\\n\",\n    \"if PLOT:\\n\",\n    \"    imgs['bicubic_np'], imgs['sharp_np'], imgs['nearest_np'] = get_baselines(imgs['LR_pil'], imgs['HR_pil'])\\n\",\n    \"    plot_image_grid([imgs['HR_np'], imgs['bicubic_np'], imgs['sharp_np'], imgs['nearest_np']], 4,12);\\n\",\n    \"    print ('PSNR bicubic: %.4f   PSNR nearest: %.4f' %  (\\n\",\n    \"                                        compare_psnr(imgs['HR_np'], imgs['bicubic_np']), \\n\",\n    \"                                        compare_psnr(imgs['HR_np'], imgs['nearest_np'])))\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def closure():\\n\",\n    \"    \\n\",\n    \"    global i, net_input\\n\",\n    \"    \\n\",\n    \"    \\n\",\n    \"    if reg_noise_std > 0:\\n\",\n    \"        net_input = net_input_saved + (noise.normal_() * reg_noise_std)\\n\",\n    \"        \\n\",\n    \"    out_HR = net(net_input)\\n\",\n    \"    out_LR = downsampler(out_HR)\\n\",\n    \"\\n\",\n    \"    total_loss = mse(out_LR, img_LR_var) + tv_weight * tv_loss(out_HR)\\n\",\n    \"    total_loss.backward()\\n\",\n    \"\\n\",\n    \"    # Log\\n\",\n    \"    psnr_LR = compare_psnr(imgs['LR_np'], torch_to_np(out_LR))\\n\",\n    \"    psnr_HR = compare_psnr(imgs['HR_np'], torch_to_np(out_HR))\\n\",\n    \"    print ('Iteration %05d    PSNR_LR %.3f   PSNR_HR %.3f' % (i, psnr_LR, psnr_HR), '\\\\r', end='')\\n\",\n    \"                      \\n\",\n    \"    # History\\n\",\n    \"    psnr_history.append([psnr_LR, psnr_HR])\\n\",\n    \"    \\n\",\n    \"    if PLOT and i % 500 == 0:\\n\",\n    \"        out_HR_np = torch_to_np(out_HR)\\n\",\n    \"        plot_image_grid([imgs['HR_np'], np.clip(out_HR_np, 0, 1)], factor=8, nrow=2, interpolation='lanczos')\\n\",\n    \"\\n\",\n    \"    i += 1\\n\",\n    \"    \\n\",\n    \"    return total_loss\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Experiment 1: no prior, optimize over pixels\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"input_depth = 3\\n\",\n    \" \\n\",\n    \"INPUT = 'noise'\\n\",\n    \"pad = 'reflection'\\n\",\n    \"OPT_OVER = 'input'\\n\",\n    \"KERNEL_TYPE='lanczos2'\\n\",\n    \"\\n\",\n    \"LR = 0.01\\n\",\n    \"tv_weight = 0.0\\n\",\n    \"\\n\",\n    \"OPTIMIZER = 'adam'\\n\",\n    \"\\n\",\n    \"num_iter = 2000\\n\",\n    \"reg_noise_std = 0.0\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Identity mapping network, optimize over `net_input`\\n\",\n    \"net = nn.Sequential()\\n\",\n    \"net_input = get_noise(input_depth, INPUT, (imgs['HR_pil'].size[1], imgs['HR_pil'].size[0])).type(dtype).detach()\\n\",\n    \"\\n\",\n    \"downsampler = Downsampler(n_planes=3, factor=factor, kernel_type='lanczos2', phase=0.5, preserve_size=True).type(dtype)\\n\",\n    \"\\n\",\n    \"# Loss\\n\",\n    \"mse = torch.nn.MSELoss().type(dtype)\\n\",\n    \"\\n\",\n    \"img_LR_var = np_to_torch(imgs['LR_np']).type(dtype)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"scrolled\": false\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"psnr_history = [] \\n\",\n    \"i = 0\\n\",\n    \"net_input_saved = net_input.detach().clone()\\n\",\n    \"noise = net_input.detach().clone()\\n\",\n    \" \\n\",\n    \"p = get_params(OPT_OVER, net, net_input)\\n\",\n    \"optimize(OPTIMIZER, p, closure, LR, num_iter)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"out_HR_np = np.clip(torch_to_np(net(net_input)), 0, 1)\\n\",\n    \"\\n\",\n    \"result_no_prior = put_in_center(out_HR_np, imgs['orig_np'].shape[1:])\\n\",\n    \"psnr_history_direct = psnr_history\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Experiment 2: using TV loss\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"tv_weight = 1e-7\\n\",\n    \"net_input = get_noise(input_depth, INPUT, (imgs['HR_pil'].size[1], imgs['HR_pil'].size[0])).type(dtype).detach()\\n\",\n    \"\\n\",\n    \"psnr_history = [] \\n\",\n    \"i = 0\\n\",\n    \" \\n\",\n    \"p = get_params(OPT_OVER, net, net_input)\\n\",\n    \"optimize(OPTIMIZER, p, closure, LR, num_iter)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"out_HR_np = np.clip(torch_to_np(net(net_input)), 0, 1)\\n\",\n    \"\\n\",\n    \"result_tv_prior = put_in_center(out_HR_np, imgs['orig_np'].shape[1:])\\n\",\n    \"psnr_history_tv = psnr_history\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Experiment 3: using deep prior\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Same setting, but use parametrization.\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"OPT_OVER = 'net'\\n\",\n    \"reg_noise_std = 1./30. # This parameter probably should be set to a lower value for this example\\n\",\n    \"tv_weight = 0.0\\n\",\n    \"\\n\",\n    \"net = skip(input_depth, 3, num_channels_down = [128, 128, 128, 128, 128], \\n\",\n    \"                           num_channels_up   = [128, 128, 128, 128, 128],\\n\",\n    \"                           num_channels_skip = [4, 4, 4, 4, 4], \\n\",\n    \"                           upsample_mode='bilinear',\\n\",\n    \"                           need_sigmoid=True, need_bias=True, pad=pad, act_fun='LeakyReLU').type(dtype)\\n\",\n    \"\\n\",\n    \"net_input = get_noise(input_depth, INPUT, (imgs['HR_pil'].size[1], imgs['HR_pil'].size[0])).type(dtype).detach()\\n\",\n    \"\\n\",\n    \"# Compute number of parameters\\n\",\n    \"s  = sum([np.prod(list(p.size())) for p in net.parameters()]); \\n\",\n    \"print ('Number of params: %d' % s)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {\n    \"scrolled\": false\n   },\n   \"outputs\": [],\n   \"source\": [\n    \"psnr_history = [] \\n\",\n    \"net_input_saved = net_input.detach().clone()\\n\",\n    \"noise = net_input.detach().clone()\\n\",\n    \"\\n\",\n    \"i = 0\\n\",\n    \"p = get_params(OPT_OVER, net, net_input)\\n\",\n    \"optimize(OPTIMIZER, p, closure, LR, num_iter)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"out_HR_np = np.clip(torch_to_np(net(net_input)), 0, 1)\\n\",\n    \"\\n\",\n    \"result_deep_prior = put_in_center(out_HR_np, imgs['orig_np'].shape[1:])\\n\",\n    \"psnr_history_deep_prior = psnr_history\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Comparison\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"plot_image_grid([imgs['HR_np'], \\n\",\n    \"                 result_no_prior, \\n\",\n    \"                 result_tv_prior, \\n\",\n    \"                 result_deep_prior], factor=8, nrow=2);\"\n   ]\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.6.5\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
  },
  {
    "path": "super-resolution.ipynb",
    "content": "{\n \"cells\": [\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"Code for **super-resolution** (figures $1$ and $5$ from main paper).. Change `factor` to $8$ to reproduce images from fig. $9$ from supmat.\\n\",\n    \"\\n\",\n    \"You can play with parameters and see how they affect the result. \"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Import libs\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"from __future__ import print_function\\n\",\n    \"import matplotlib.pyplot as plt\\n\",\n    \"%matplotlib inline\\n\",\n    \"\\n\",\n    \"import argparse\\n\",\n    \"import os\\n\",\n    \"# os.environ['CUDA_VISIBLE_DEVICES'] = '1'\\n\",\n    \"\\n\",\n    \"import numpy as np\\n\",\n    \"from models import *\\n\",\n    \"\\n\",\n    \"import torch\\n\",\n    \"import torch.optim\\n\",\n    \"\\n\",\n    \"from skimage.measure import compare_psnr\\n\",\n    \"from models.downsampler import Downsampler\\n\",\n    \"\\n\",\n    \"from utils.sr_utils import *\\n\",\n    \"\\n\",\n    \"torch.backends.cudnn.enabled = True\\n\",\n    \"torch.backends.cudnn.benchmark =True\\n\",\n    \"dtype = torch.cuda.FloatTensor\\n\",\n    \"\\n\",\n    \"imsize = -1 \\n\",\n    \"factor = 4 # 8\\n\",\n    \"enforse_div32 = 'CROP' # we usually need the dimensions to be divisible by a power of two (32 in this case)\\n\",\n    \"PLOT = True\\n\",\n    \"\\n\",\n    \"# To produce images from the paper we took *_GT.png images from LapSRN viewer for corresponding factor,\\n\",\n    \"# e.g. x4/zebra_GT.png for factor=4, and x8/zebra_GT.png for factor=8 \\n\",\n    \"path_to_image = 'data/sr/zebra_GT.png'\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Load image and baselines\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"# Starts here\\n\",\n    \"imgs = load_LR_HR_imgs_sr(path_to_image , imsize, factor, enforse_div32)\\n\",\n    \"\\n\",\n    \"imgs['bicubic_np'], imgs['sharp_np'], imgs['nearest_np'] = get_baselines(imgs['LR_pil'], imgs['HR_pil'])\\n\",\n    \"\\n\",\n    \"if PLOT:\\n\",\n    \"    plot_image_grid([imgs['HR_np'], imgs['bicubic_np'], imgs['sharp_np'], imgs['nearest_np']], 4,12);\\n\",\n    \"    print ('PSNR bicubic: %.4f   PSNR nearest: %.4f' %  (\\n\",\n    \"                                        compare_psnr(imgs['HR_np'], imgs['bicubic_np']), \\n\",\n    \"                                        compare_psnr(imgs['HR_np'], imgs['nearest_np'])))\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Set up parameters and net\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"input_depth = 32\\n\",\n    \" \\n\",\n    \"INPUT =     'noise'\\n\",\n    \"pad   =     'reflection'\\n\",\n    \"OPT_OVER =  'net'\\n\",\n    \"KERNEL_TYPE='lanczos2'\\n\",\n    \"\\n\",\n    \"LR = 0.01\\n\",\n    \"tv_weight = 0.0\\n\",\n    \"\\n\",\n    \"OPTIMIZER = 'adam'\\n\",\n    \"\\n\",\n    \"if factor == 4: \\n\",\n    \"    num_iter = 2000\\n\",\n    \"    reg_noise_std = 0.03\\n\",\n    \"elif factor == 8:\\n\",\n    \"    num_iter = 4000\\n\",\n    \"    reg_noise_std = 0.05\\n\",\n    \"else:\\n\",\n    \"    assert False, 'We did not experiment with other factors'\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"net_input = get_noise(input_depth, INPUT, (imgs['HR_pil'].size[1], imgs['HR_pil'].size[0])).type(dtype).detach()\\n\",\n    \"\\n\",\n    \"NET_TYPE = 'skip' # UNet, ResNet\\n\",\n    \"net = get_net(input_depth, 'skip', pad,\\n\",\n    \"              skip_n33d=128, \\n\",\n    \"              skip_n33u=128, \\n\",\n    \"              skip_n11=4, \\n\",\n    \"              num_scales=5,\\n\",\n    \"              upsample_mode='bilinear').type(dtype)\\n\",\n    \"\\n\",\n    \"# Losses\\n\",\n    \"mse = torch.nn.MSELoss().type(dtype)\\n\",\n    \"\\n\",\n    \"img_LR_var = np_to_torch(imgs['LR_np']).type(dtype)\\n\",\n    \"\\n\",\n    \"downsampler = Downsampler(n_planes=3, factor=factor, kernel_type=KERNEL_TYPE, phase=0.5, preserve_size=True).type(dtype)\"\n   ]\n  },\n  {\n   \"cell_type\": \"markdown\",\n   \"metadata\": {},\n   \"source\": [\n    \"# Define closure and optimize\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"def closure():\\n\",\n    \"    global i, net_input\\n\",\n    \"    \\n\",\n    \"    if reg_noise_std > 0:\\n\",\n    \"        net_input = net_input_saved + (noise.normal_() * reg_noise_std)\\n\",\n    \"\\n\",\n    \"    out_HR = net(net_input)\\n\",\n    \"    out_LR = downsampler(out_HR)\\n\",\n    \"\\n\",\n    \"    total_loss = mse(out_LR, img_LR_var) \\n\",\n    \"    \\n\",\n    \"    if tv_weight > 0:\\n\",\n    \"        total_loss += tv_weight * tv_loss(out_HR)\\n\",\n    \"        \\n\",\n    \"    total_loss.backward()\\n\",\n    \"\\n\",\n    \"    # Log\\n\",\n    \"    psnr_LR = compare_psnr(imgs['LR_np'], torch_to_np(out_LR))\\n\",\n    \"    psnr_HR = compare_psnr(imgs['HR_np'], torch_to_np(out_HR))\\n\",\n    \"    print ('Iteration %05d    PSNR_LR %.3f   PSNR_HR %.3f' % (i, psnr_LR, psnr_HR), '\\\\r', end='')\\n\",\n    \"                      \\n\",\n    \"    # History\\n\",\n    \"    psnr_history.append([psnr_LR, psnr_HR])\\n\",\n    \"    \\n\",\n    \"    if PLOT and i % 100 == 0:\\n\",\n    \"        out_HR_np = torch_to_np(out_HR)\\n\",\n    \"        plot_image_grid([imgs['HR_np'], imgs['bicubic_np'], np.clip(out_HR_np, 0, 1)], factor=13, nrow=3)\\n\",\n    \"\\n\",\n    \"    i += 1\\n\",\n    \"    \\n\",\n    \"    return total_loss\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"psnr_history = [] \\n\",\n    \"net_input_saved = net_input.detach().clone()\\n\",\n    \"noise = net_input.detach().clone()\\n\",\n    \"\\n\",\n    \"i = 0\\n\",\n    \"p = get_params(OPT_OVER, net, net_input)\\n\",\n    \"optimize(OPTIMIZER, p, closure, LR, num_iter)\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": [\n    \"out_HR_np = np.clip(torch_to_np(net(net_input)), 0, 1)\\n\",\n    \"result_deep_prior = put_in_center(out_HR_np, imgs['orig_np'].shape[1:])\\n\",\n    \"\\n\",\n    \"# For the paper we acually took `_bicubic.png` files from LapSRN viewer and used `result_deep_prior` as our result\\n\",\n    \"plot_image_grid([imgs['HR_np'],\\n\",\n    \"                 imgs['bicubic_np'],\\n\",\n    \"                 out_HR_np], factor=4, nrow=1);\"\n   ]\n  },\n  {\n   \"cell_type\": \"code\",\n   \"execution_count\": null,\n   \"metadata\": {},\n   \"outputs\": [],\n   \"source\": []\n  }\n ],\n \"metadata\": {\n  \"kernelspec\": {\n   \"display_name\": \"Python 3\",\n   \"language\": \"python\",\n   \"name\": \"python3\"\n  },\n  \"language_info\": {\n   \"codemirror_mode\": {\n    \"name\": \"ipython\",\n    \"version\": 3\n   },\n   \"file_extension\": \".py\",\n   \"mimetype\": \"text/x-python\",\n   \"name\": \"python\",\n   \"nbconvert_exporter\": \"python\",\n   \"pygments_lexer\": \"ipython3\",\n   \"version\": \"3.6.5\"\n  }\n },\n \"nbformat\": 4,\n \"nbformat_minor\": 2\n}\n"
  },
  {
    "path": "super-resolution_eval_script.py",
    "content": "# This script had been used to get the numbers in the paper\nfrom utils.common_utils import get_image, plot_image_grid\nimport cv2\ndef rgb2ycbcr(im_rgb):\n    im_rgb = im_rgb.astype(np.float32)\n    im_ycrcb = cv2.cvtColor(im_rgb, cv2.COLOR_RGB2YCR_CB)\n    im_ycbcr = im_ycrcb[:,:,(0,2,1)].astype(np.float32)\n    im_ycbcr[:,:,0] = (im_ycbcr[:,:,0]*(235-16)+16)/255.0 #to [16/255, 235/255]\n    im_ycbcr[:,:,1:] = (im_ycbcr[:,:,1:]*(240-16)+16)/255.0 #to [16/255, 240/255]\n    return im_ycbcr\n\ndef compare_psnr_y(x, y):\n    return compare_psnr(rgb2ycbcr(x.transpose(1,2,0))[:,:,0], rgb2ycbcr(y.transpose(1,2,0))[:,:,0])\n    \nfrom collections import defaultdict\ndatasets = { \n    'Set14':   [\"baboon\", \"barbara\", \"bridge\", \"coastguard\", \"comic\", \"face\", \"flowers\", \"foreman\", \"lenna\", \"man\", \"monarch\", \"pepper\", \"ppt3\", \"zebra\"],\n#     'Set5':    ['baby', 'bird', 'butterfly', 'head', 'woman']\n}\nfrom glob import glob\n# g = sorted(glob('../image_compare/data/sr/Set5/x4/*'))\n\nfrom skimage.measure import compare_psnr\n# our \nstats = {}\nimsize  = -1\ndct = defaultdict(lambda : 0)\nfor cur_dataset in datasets.keys():\n    \n    for method_name in postfixes:\n        psnrs = []\n        for name in datasets[cur_dataset]:\n            img_HR = f'/home/dulyanov/dmitryulyanov.github.io/assets/deep-image-prior/SR/{cur_dataset}/x4/{name}_GT.png'\n            ours   = f'/home/dulyanov/dmitryulyanov.github.io/assets/deep-image-prior/SR/{cur_dataset}/x4/{name}_deep_prior.png'\n            method = f'/home/dulyanov/dmitryulyanov.github.io/assets/deep-image-prior/SR/{cur_dataset}/x4/{name}_{method_name}.png'\n\n            gt_pil,     gt      = get_image(img_HR, imsize)\n            ours_pil,   ours    = get_image(ours, imsize)\n            method_pil, methods = get_image(method, imsize)\n            \n            if methods.shape[0] == 1:\n                methods = np.concatenate([methods, methods, methods], 0)\n    \n            q1 = ours[:3].sum(0)\n            t1 = np.where(q1.sum(0) > 0)[0]\n            t2 = np.where(q1.sum(1) > 0)[0]\n\n\n\n            psnr = compare_psnr_y(gt     [:3,t2[0] + 4:t2[-1]-4,t1[0] + 4:t1[-1] - 4], \n                                  methods[:3,t2[0] + 4:t2[-1]-4,t1[0] + 4:t1[-1] - 4])\n\n    #         psnr = compare_psnr(gt  [:3], \n    #                             ours[:3])\n\n            psnrs.append(psnr)\n\n            print(name, psnr)\n\n        \n        header = f'\\small{{{method_name}}} & ' + ' & '.join([f'${x:.4}$' for x in psnrs])\n        \n        stats[method_name] = [header, np.mean(psnrs)]\n        \n        print (header)\n        \n    names = datasets[cur_dataset]\n    header = ' & ' + ' & '.join([f'\\small{{{x.title()}}}' for x in names])    \n"
  },
  {
    "path": "utils/__init__.py",
    "content": ""
  },
  {
    "path": "utils/common_utils.py",
    "content": "import torch\nimport torch.nn as nn\nimport torchvision\nimport sys\n\nimport numpy as np\nfrom PIL import Image\nimport PIL\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\ndef crop_image(img, d=32):\n    '''Make dimensions divisible by `d`'''\n\n    new_size = (img.size[0] - img.size[0] % d, \n                img.size[1] - img.size[1] % d)\n\n    bbox = [\n            int((img.size[0] - new_size[0])/2), \n            int((img.size[1] - new_size[1])/2),\n            int((img.size[0] + new_size[0])/2),\n            int((img.size[1] + new_size[1])/2),\n    ]\n\n    img_cropped = img.crop(bbox)\n    return img_cropped\n\ndef get_params(opt_over, net, net_input, downsampler=None):\n    '''Returns parameters that we want to optimize over.\n\n    Args:\n        opt_over: comma separated list, e.g. \"net,input\" or \"net\"\n        net: network\n        net_input: torch.Tensor that stores input `z`\n    '''\n    opt_over_list = opt_over.split(',')\n    params = []\n    \n    for opt in opt_over_list:\n    \n        if opt == 'net':\n            params += [x for x in net.parameters() ]\n        elif  opt=='down':\n            assert downsampler is not None\n            params = [x for x in downsampler.parameters()]\n        elif opt == 'input':\n            net_input.requires_grad = True\n            params += [net_input]\n        else:\n            assert False, 'what is it?'\n            \n    return params\n\ndef get_image_grid(images_np, nrow=8):\n    '''Creates a grid from a list of images by concatenating them.'''\n    images_torch = [torch.from_numpy(x) for x in images_np]\n    torch_grid = torchvision.utils.make_grid(images_torch, nrow)\n    \n    return torch_grid.numpy()\n\ndef plot_image_grid(images_np, nrow =8, factor=1, interpolation='lanczos'):\n    \"\"\"Draws images in a grid\n    \n    Args:\n        images_np: list of images, each image is np.array of size 3xHxW of 1xHxW\n        nrow: how many images will be in one row\n        factor: size if the plt.figure \n        interpolation: interpolation used in plt.imshow\n    \"\"\"\n    n_channels = max(x.shape[0] for x in images_np)\n    assert (n_channels == 3) or (n_channels == 1), \"images should have 1 or 3 channels\"\n    \n    images_np = [x if (x.shape[0] == n_channels) else np.concatenate([x, x, x], axis=0) for x in images_np]\n\n    grid = get_image_grid(images_np, nrow)\n    \n    plt.figure(figsize=(len(images_np) + factor, 12 + factor))\n    \n    if images_np[0].shape[0] == 1:\n        plt.imshow(grid[0], cmap='gray', interpolation=interpolation)\n    else:\n        plt.imshow(grid.transpose(1, 2, 0), interpolation=interpolation)\n    \n    plt.show()\n    \n    return grid\n\ndef load(path):\n    \"\"\"Load PIL image.\"\"\"\n    img = Image.open(path)\n    return img\n\ndef get_image(path, imsize=-1):\n    \"\"\"Load an image and resize to a cpecific size. \n\n    Args: \n        path: path to image\n        imsize: tuple or scalar with dimensions; -1 for `no resize`\n    \"\"\"\n    img = load(path)\n\n    if isinstance(imsize, int):\n        imsize = (imsize, imsize)\n\n    if imsize[0]!= -1 and img.size != imsize:\n        if imsize[0] > img.size[0]:\n            img = img.resize(imsize, Image.BICUBIC)\n        else:\n            img = img.resize(imsize, Image.ANTIALIAS)\n\n    img_np = pil_to_np(img)\n\n    return img, img_np\n\n\n\ndef fill_noise(x, noise_type):\n    \"\"\"Fills tensor `x` with noise of type `noise_type`.\"\"\"\n    if noise_type == 'u':\n        x.uniform_()\n    elif noise_type == 'n':\n        x.normal_() \n    else:\n        assert False\n\ndef get_noise(input_depth, method, spatial_size, noise_type='u', var=1./10):\n    \"\"\"Returns a pytorch.Tensor of size (1 x `input_depth` x `spatial_size[0]` x `spatial_size[1]`) \n    initialized in a specific way.\n    Args:\n        input_depth: number of channels in the tensor\n        method: `noise` for fillting tensor with noise; `meshgrid` for np.meshgrid\n        spatial_size: spatial size of the tensor to initialize\n        noise_type: 'u' for uniform; 'n' for normal\n        var: a factor, a noise will be multiplicated by. Basically it is standard deviation scaler. \n    \"\"\"\n    if isinstance(spatial_size, int):\n        spatial_size = (spatial_size, spatial_size)\n    if method == 'noise':\n        shape = [1, input_depth, spatial_size[0], spatial_size[1]]\n        net_input = torch.zeros(shape)\n        \n        fill_noise(net_input, noise_type)\n        net_input *= var            \n    elif method == 'meshgrid': \n        assert input_depth == 2\n        X, Y = np.meshgrid(np.arange(0, spatial_size[1])/float(spatial_size[1]-1), np.arange(0, spatial_size[0])/float(spatial_size[0]-1))\n        meshgrid = np.concatenate([X[None,:], Y[None,:]])\n        net_input=  np_to_torch(meshgrid)\n    else:\n        assert False\n        \n    return net_input\n\ndef pil_to_np(img_PIL):\n    '''Converts image in PIL format to np.array.\n    \n    From W x H x C [0...255] to C x W x H [0..1]\n    '''\n    ar = np.array(img_PIL)\n\n    if len(ar.shape) == 3:\n        ar = ar.transpose(2,0,1)\n    else:\n        ar = ar[None, ...]\n\n    return ar.astype(np.float32) / 255.\n\ndef np_to_pil(img_np): \n    '''Converts image in np.array format to PIL image.\n    \n    From C x W x H [0..1] to  W x H x C [0...255]\n    '''\n    ar = np.clip(img_np*255,0,255).astype(np.uint8)\n    \n    if img_np.shape[0] == 1:\n        ar = ar[0]\n    else:\n        ar = ar.transpose(1, 2, 0)\n\n    return Image.fromarray(ar)\n\ndef np_to_torch(img_np):\n    '''Converts image in numpy.array to torch.Tensor.\n\n    From C x W x H [0..1] to  C x W x H [0..1]\n    '''\n    return torch.from_numpy(img_np)[None, :]\n\ndef torch_to_np(img_var):\n    '''Converts an image in torch.Tensor format to np.array.\n\n    From 1 x C x W x H [0..1] to  C x W x H [0..1]\n    '''\n    return img_var.detach().cpu().numpy()[0]\n\n\ndef optimize(optimizer_type, parameters, closure, LR, num_iter):\n    \"\"\"Runs optimization loop.\n\n    Args:\n        optimizer_type: 'LBFGS' of 'adam'\n        parameters: list of Tensors to optimize over\n        closure: function, that returns loss variable\n        LR: learning rate\n        num_iter: number of iterations \n    \"\"\"\n    if optimizer_type == 'LBFGS':\n        # Do several steps with adam first\n        optimizer = torch.optim.Adam(parameters, lr=0.001)\n        for j in range(100):\n            optimizer.zero_grad()\n            closure()\n            optimizer.step()\n\n        print('Starting optimization with LBFGS')        \n        def closure2():\n            optimizer.zero_grad()\n            return closure()\n        optimizer = torch.optim.LBFGS(parameters, max_iter=num_iter, lr=LR, tolerance_grad=-1, tolerance_change=-1)\n        optimizer.step(closure2)\n\n    elif optimizer_type == 'adam':\n        print('Starting optimization with ADAM')\n        optimizer = torch.optim.Adam(parameters, lr=LR)\n        \n        for j in range(num_iter):\n            optimizer.zero_grad()\n            closure()\n            optimizer.step()\n    else:\n        assert False"
  },
  {
    "path": "utils/denoising_utils.py",
    "content": "import os\nfrom .common_utils import *\n\n\n        \ndef get_noisy_image(img_np, sigma):\n    \"\"\"Adds Gaussian noise to an image.\n    \n    Args: \n        img_np: image, np.array with values from 0 to 1\n        sigma: std of the noise\n    \"\"\"\n    img_noisy_np = np.clip(img_np + np.random.normal(scale=sigma, size=img_np.shape), 0, 1).astype(np.float32)\n    img_noisy_pil = np_to_pil(img_noisy_np)\n\n    return img_noisy_pil, img_noisy_np"
  },
  {
    "path": "utils/feature_inversion_utils.py",
    "content": "import torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nimport torchvision.models as models\nfrom .matcher import Matcher\nimport os\nfrom collections import OrderedDict\n\nclass View(nn.Module):\n    def __init__(self):\n        super(View, self).__init__()\n\n    def forward(self, x):\n        return x.view(-1) \n\ndef get_vanilla_vgg_features(cut_idx=-1):\n    if not os.path.exists('vgg_features.pth'):\n        os.system(\n            'wget --no-check-certificate -N https://s3-us-west-2.amazonaws.com/jcjohns-models/vgg19-d01eb7cb.pth')\n        vgg_weights = torch.load('vgg19-d01eb7cb.pth')\n        # fix compatibility issues\n        map = {'classifier.6.weight':u'classifier.7.weight', 'classifier.6.bias':u'classifier.7.bias'}\n        vgg_weights = OrderedDict([(map[k] if k in map else k,v) for k,v in vgg_weights.iteritems()])\n\n        \n\n        model = models.vgg19()\n        model.classifier = nn.Sequential(View(), *model.classifier._modules.values())\n        \n\n        model.load_state_dict(vgg_weights)\n        \n        torch.save(model.features, 'vgg_features.pth')\n        torch.save(model.classifier, 'vgg_classifier.pth')\n\n    vgg = torch.load('vgg_features.pth')\n    if cut_idx > 36:\n        vgg_classifier = torch.load('vgg_classifier.pth')\n        vgg = nn.Sequential(*(vgg._modules.values() + vgg_classifier._modules.values()))\n\n    vgg.eval()\n\n    return vgg\n\n\ndef get_matcher(net, opt):\n    idxs = [x for x in opt['layers'].split(',')]\n    matcher = Matcher(opt['what'])\n\n    def hook(module, input, output):\n        matcher(module, output)\n\n    for i in idxs:\n        net._modules[i].register_forward_hook(hook)\n\n    return matcher\n\n\n\ndef get_vgg(cut_idx=-1):\n    f = get_vanilla_vgg_features(cut_idx)\n\n    if cut_idx > 0: \n        num_modules = len(f._modules)\n        keys_to_delete = [f._modules.keys()[x] for x in range(cut_idx, num_modules)]\n        for k in keys_to_delete:\n            del f._modules[k]\n\n    return f\n\ndef vgg_preprocess_var(var):\n        (r, g, b) = torch.chunk(var, 3, dim=1)\n        bgr = torch.cat((b, g, r), 1)\n        out = bgr * 255 - torch.autograd.Variable(vgg_mean[None, ...]).type(var.type()).expand_as(bgr)\n        return out\n\nvgg_mean = torch.FloatTensor([103.939, 116.779, 123.680]).view(3, 1, 1)\n\n\n\ndef get_preprocessor(imsize):\n    def vgg_preprocess(tensor):\n        (r, g, b) = torch.chunk(tensor, 3, dim=0)\n        bgr = torch.cat((b, g, r), 0)\n        out = bgr * 255 - vgg_mean.type(tensor.type()).expand_as(bgr)\n        return out\n    preprocess = transforms.Compose([\n        transforms.Resize(imsize),\n        transforms.ToTensor(),\n        transforms.Lambda(vgg_preprocess)\n    ])\n\n    return preprocess\n\n\ndef get_deprocessor():\n    def vgg_deprocess(tensor):\n        bgr = (tensor + vgg_mean.expand_as(tensor)) / 255.0\n        (b, g, r) = torch.chunk(bgr, 3, dim=0)\n        rgb = torch.cat((r, g, b), 0)\n        return rgb\n    deprocess = transforms.Compose([\n        transforms.Lambda(vgg_deprocess),\n        transforms.Lambda(lambda x: torch.clamp(x, 0, 1)),\n        transforms.ToPILImage()\n    ])\n    return deprocess\n"
  },
  {
    "path": "utils/inpainting_utils.py",
    "content": "import numpy as np\nfrom PIL import Image\nimport PIL.ImageDraw as ImageDraw\nimport PIL.ImageFont as ImageFont\nfrom .common_utils import *\n\ndef get_text_mask(for_image, sz=20):\n    font_fname = '/usr/share/fonts/truetype/freefont/FreeSansBold.ttf'\n    font_size = sz\n    font = ImageFont.truetype(font_fname, font_size)\n\n    img_mask = Image.fromarray(np.array(for_image)*0+255)\n    draw = ImageDraw.Draw(img_mask)\n    draw.text((128, 128), \"hello world\", font=font, fill='rgb(0, 0, 0)')\n\n    return img_mask\n\ndef get_bernoulli_mask(for_image, zero_fraction=0.95):\n    img_mask_np=(np.random.random_sample(size=pil_to_np(for_image).shape) > zero_fraction).astype(int)\n    img_mask = np_to_pil(img_mask_np)\n    \n    return img_mask\n"
  },
  {
    "path": "utils/matcher.py",
    "content": "import torch\nimport torch.nn as nn\n\nclass Matcher:\n    def __init__(self, how='gram_matrix', loss='mse'):\n        self.mode = 'store'\n        self.stored = {}\n        self.losses = {}\n\n        if how in all_features.keys():\n            self.get_statistics = all_features[how]\n        else:\n            assert False\n        pass\n\n        if loss in all_losses.keys():\n            self.loss = all_losses[loss]\n        else:\n            assert False\n\n    def __call__(self, module, features):\n        statistics = self.get_statistics(features)\n\n        self.statistics = statistics\n        if self.mode == 'store':\n            self.stored[module] = statistics.detach().clone()\n        elif self.mode == 'match':\n            self.losses[module] = self.loss(statistics, self.stored[module])\n\n    def clean(self):\n        self.losses = {}\n\ndef gram_matrix(x):\n    (b, ch, h, w) = x.size()\n    features = x.view(b, ch, w * h)\n    features_t = features.transpose(1, 2)\n    gram = features.bmm(features_t) / (ch * h * w)\n    return gram\n\n\ndef features(x):\n    return x\n\n\nall_features = {\n    'gram_matrix': gram_matrix,\n    'features': features,\n}\n\nall_losses = {\n    'mse': nn.MSELoss(),\n    'smoothL1': nn.SmoothL1Loss(),\n    'L1': nn.L1Loss(),\n}\n"
  },
  {
    "path": "utils/perceptual_loss/__init__.py",
    "content": ""
  },
  {
    "path": "utils/perceptual_loss/matcher.py",
    "content": "import torch\nimport torch.nn as nn\n\n\nclass Matcher:\n    def __init__(self, how='gram_matrix', loss='mse', map_index=933):\n        self.mode = 'store'\n        self.stored = {}\n        self.losses = {}\n\n        if how in all_features.keys():\n            self.get_statistics = all_features[how]\n        else:\n            assert False\n        pass\n\n        if loss in all_losses.keys():\n            self.loss = all_losses[loss]\n        else:\n            assert False\n\n        self.map_index = map_index\n        self.method = 'match'\n\n\n    def __call__(self, module, features):\n        statistics = self.get_statistics(features)\n\n        self.statistics = statistics\n        if self.mode == 'store':\n            self.stored[module] = statistics.detach()\n\n        elif self.mode == 'match':\n           \n            if statistics.ndimension() == 2:\n\n                if self.method == 'maximize':\n                    self.losses[module] = - statistics[0, self.map_index]\n                else:\n                    self.losses[module] = torch.abs(300 - statistics[0, self.map_index]) \n\n            else:\n                ws = self.window_size\n\n                t = statistics.detach() * 0\n\n                s_cc = statistics[:1, :, t.shape[2] // 2 - ws:t.shape[2] // 2 + ws, t.shape[3] // 2 - ws:t.shape[3] // 2 + ws] #* 1.0\n                t_cc = t[:1, :, t.shape[2] // 2 - ws:t.shape[2] // 2 + ws, t.shape[3] // 2 - ws:t.shape[3] // 2 + ws] #* 1.0\n                t_cc[:, self.map_index,...] = 1\n\n                if self.method == 'maximize':\n                    self.losses[module] = -(s_cc * t_cc.contiguous()).sum()\n                else:\n                    self.losses[module] = torch.abs(200 -(s_cc * t_cc.contiguous())).sum()\n\n\n    def clean(self):\n        self.losses = {}\n\ndef gram_matrix(x):\n    (b, ch, h, w) = x.size()\n    features = x.view(b, ch, w * h)\n    features_t = features.transpose(1, 2)\n    gram = features.bmm(features_t) / (ch * h * w)\n    return gram\n\n\ndef features(x):\n    return x\n\n\nall_features = {\n    'gram_matrix': gram_matrix,\n    'features': features,\n}\n\nall_losses = {\n    'mse': nn.MSELoss(),\n    'smoothL1': nn.SmoothL1Loss(),\n    'L1': nn.L1Loss(),\n}\n"
  },
  {
    "path": "utils/perceptual_loss/perceptual_loss.py",
    "content": "import os\nimport torch\nimport torch.nn as nn\nimport torchvision.transforms as transforms\nimport torchvision.models as models\nfrom .matcher import Matcher\nfrom collections import OrderedDict\n\nfrom torchvision.models.vgg import model_urls\nfrom torchvision.models import vgg19\nfrom torch.autograd import Variable\n\nfrom .vgg_modified import VGGModified\n\ndef get_pretrained_net(name):\n    \"\"\"Loads pretrained network\"\"\"\n    if name == 'alexnet_caffe':\n        if not os.path.exists('alexnet-torch_py3.pth'):\n            print('Downloading AlexNet')\n            os.system('wget -O alexnet-torch_py3.pth --no-check-certificate -nc https://box.skoltech.ru/index.php/s/77xSWvrDN0CiQtK/download')\n        return torch.load('alexnet-torch_py3.pth')\n    elif name == 'vgg19_caffe':\n        if not os.path.exists('vgg19-caffe-py3.pth'):\n            print('Downloading VGG-19')\n            os.system('wget -O vgg19-caffe-py3.pth --no-check-certificate -nc https://box.skoltech.ru/index.php/s/HPcOFQTjXxbmp4X/download')\n        \n        vgg = get_vgg19_caffe()\n        \n        return vgg\n    elif name == 'vgg16_caffe':\n        if not os.path.exists('vgg16-caffe-py3.pth'):\n            print('Downloading VGG-16')\n            os.system('wget -O vgg16-caffe-py3.pth --no-check-certificate -nc https://box.skoltech.ru/index.php/s/TUZ62HnPKWdxyLr/download')\n        \n        vgg = get_vgg16_caffe()\n        \n        return vgg\n    elif name == 'vgg19_pytorch_modified':\n        # os.system('wget -O data/feature_inversion/vgg19-caffe.pth --no-check-certificate -nc https://www.dropbox.com/s/xlbdo688dy4keyk/vgg19-caffe.pth?dl=1')\n        \n        model = VGGModified(vgg19(pretrained=False), 0.2)\n        model.load_state_dict(torch.load('vgg_pytorch_modified.pkl')['state_dict'])\n\n        return model\n    else:\n        assert False\n\n\nclass PerceputalLoss(nn.modules.loss._Loss):\n    \"\"\" \n        Assumes input image is in range [0,1] if `input_range` is 'sigmoid', [-1, 1] if 'tanh' \n    \"\"\"\n    def __init__(self, input_range='sigmoid', \n                       net_type = 'vgg_torch', \n                       input_preprocessing='corresponding', \n                       match=[{'layers':[11,20,29],'what':'features'}]):\n        \n        if input_range not in ['sigmoid', 'tanh']:\n            assert False\n\n        self.net = get_pretrained_net(net_type).cuda()\n\n        self.matchers = [get_matcher(self.net, match_opts) for match_opts in match]\n\n        preprocessing_correspondence = {\n            'vgg19_torch': vgg_preprocess_caffe,\n            'vgg16_torch': vgg_preprocess_caffe,\n            'vgg19_pytorch': vgg_preprocess_pytorch,\n            'vgg19_pytorch_modified': vgg_preprocess_pytorch,\n        }\n\n        if input_preprocessing == 'corresponding':\n            self.preprocess_input = preprocessing_correspondence[net_type]\n        else:\n            self.preprocessing = preprocessing_correspondence[input_preprocessing]\n\n    def preprocess_input(self, x):\n        if self.input_range == 'tanh':\n            x = (x + 1.) / 2.\n\n        return self.preprocess(x)\n\n    def __call__(self, x, y):\n\n        # for \n        self.matcher_content.mode = 'store'\n        self.net(self.preprocess_input(y));\n        \n        self.matcher_content.mode = 'match'\n        self.net(self.preprocess_input(x));\n        \n        return sum([sum(matcher.losses.values()) for matcher in self.matchers])\n\n\ndef get_vgg19_caffe():\n    model = vgg19()\n    model.classifier = nn.Sequential(View(), *model.classifier._modules.values())\n    vgg = model.features\n    vgg_classifier = model.classifier\n\n    names = ['conv1_1','relu1_1','conv1_2','relu1_2','pool1',\n             'conv2_1','relu2_1','conv2_2','relu2_2','pool2',\n             'conv3_1','relu3_1','conv3_2','relu3_2','conv3_3','relu3_3','conv3_4','relu3_4','pool3',\n             'conv4_1','relu4_1','conv4_2','relu4_2','conv4_3','relu4_3','conv4_4','relu4_4','pool4',\n             'conv5_1','relu5_1','conv5_2','relu5_2','conv5_3','relu5_3','conv5_4','relu5_4','pool5',\n             'torch_view','fc6','relu6','drop6','fc7','relu7','drop7','fc8']\n    \n    model = nn.Sequential()\n    for n, m in zip(names, list(vgg) + list(vgg_classifier)):\n        model.add_module(n, m)\n\n    model.load_state_dict(torch.load('vgg19-caffe-py3.pth'))\n\n    return model\n\ndef get_vgg16_caffe():\n    vgg = torch.load('vgg16-caffe-py3.pth')\n\n    names = ['conv1_1','relu1_1','conv1_2','relu1_2','pool1',\n             'conv2_1','relu2_1','conv2_2','relu2_2','pool2',\n             'conv3_1','relu3_1','conv3_2','relu3_2','conv3_3','relu3_3','pool3',\n             'conv4_1','relu4_1','conv4_2','relu4_2','conv4_3','relu4_3','pool4',\n             'conv5_1','relu5_1','conv5_2','relu5_2','conv5_3','relu5_3','pool5',\n             'torch_view','fc6','relu6','drop6','fc7','relu7','fc8']\n    \n    model = nn.Sequential()\n    for n, m in zip(names, list(vgg)):\n        model.add_module(n, m)\n\n    # model.load_state_dict(torch.load('vgg19-caffe-py3.pth'))\n\n    return model\n\n\nclass View(nn.Module):\n    def __init__(self):\n        super(View, self).__init__()\n\n    def forward(self, x):\n        return x.view(x.size(0), -1) \n\n\ndef get_matcher(vgg, opt):\n    # idxs = [int(x) for x in opt['layers'].split(',')]\n    matcher = Matcher(opt['what'], 'mse', opt['map_idx'])\n\n    def hook(module, input, output):\n        matcher(module, output)\n\n    for layer_name in opt['layers']:\n        vgg._modules[layer_name].register_forward_hook(hook)\n\n    return matcher\n\n\ndef get_vgg(cut_idx=-1, vgg_type='pytorch'):\n    f = get_vanilla_vgg_features(cut_idx, vgg_type)\n\n    keys = [x for x in cnn._modules.keys()]\n    max_idx = max(keys.index(x) for x in opt_content['layers'].split(','))\n    for k in keys[max_idx+1:]:\n        cnn._modules.pop(k)\n\n    return f\n\nvgg_mean = torch.FloatTensor([103.939, 116.779, 123.680]).view(3, 1, 1)\ndef vgg_preprocess_caffe(var):\n    (r, g, b) = torch.chunk(var, 3, dim=1)\n    bgr = torch.cat((b, g, r), 1)\n    out = bgr * 255 - torch.autograd.Variable(vgg_mean).type(var.type())\n    return out\n\n\n\nmean_pytorch = Variable(torch.Tensor([0.485, 0.456, 0.406]).view(3, 1, 1))\nstd_pytorch =  Variable(torch.Tensor([0.229, 0.224, 0.225]).view(3, 1, 1))\n\ndef vgg_preprocess_pytorch(var):\n    return (var - mean_pytorch.type_as(var))/std_pytorch.type_as(var)\n\n\n\ndef get_preprocessor(imsize):\n    def vgg_preprocess(tensor):\n        (r, g, b) = torch.chunk(tensor, 3, dim=0)\n        bgr = torch.cat((b, g, r), 0)\n        out = bgr * 255 - vgg_mean.type(tensor.type()).expand_as(bgr)\n        return out\n    preprocess = transforms.Compose([\n        transforms.Resize(imsize),\n        transforms.ToTensor(),\n        transforms.Lambda(vgg_preprocess)\n    ])\n\n    return preprocess\n\n\ndef get_deprocessor():\n    def vgg_deprocess(tensor):\n        bgr = (tensor + vgg_mean.expand_as(tensor)) / 255.0\n        (b, g, r) = torch.chunk(bgr, 3, dim=0)\n        rgb = torch.cat((r, g, b), 0)\n        return rgb\n    deprocess = transforms.Compose([\n        transforms.Lambda(vgg_deprocess),\n        transforms.Lambda(lambda x: torch.clamp(x, 0, 1)),\n        transforms.ToPILImage()\n    ])\n    return deprocess\n\n"
  },
  {
    "path": "utils/perceptual_loss/vgg_modified.py",
    "content": "import torch.nn as nn\n\nclass VGGModified(nn.Module):\n    def __init__(self, vgg19_orig, slope=0.01):\n        super(VGGModified, self).__init__()\n        self.features = nn.Sequential()\n        \n        self.features.add_module(str(0), vgg19_orig.features[0])\n        self.features.add_module(str(1), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(2), vgg19_orig.features[2])\n        self.features.add_module(str(3), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(4), nn.AvgPool2d((2,2), (2,2)))\n\n        self.features.add_module(str(5), vgg19_orig.features[5])\n        self.features.add_module(str(6), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(7), vgg19_orig.features[7])\n        self.features.add_module(str(8), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(9), nn.AvgPool2d((2,2), (2,2)))\n\n        self.features.add_module(str(10), vgg19_orig.features[10])\n        self.features.add_module(str(11), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(12), vgg19_orig.features[12])\n        self.features.add_module(str(13), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(14), vgg19_orig.features[14])\n        self.features.add_module(str(15), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(16), vgg19_orig.features[16])\n        self.features.add_module(str(17), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(18), nn.AvgPool2d((2,2), (2,2)))\n\n        self.features.add_module(str(19), vgg19_orig.features[19])\n        self.features.add_module(str(20), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(21), vgg19_orig.features[21])\n        self.features.add_module(str(22), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(23), vgg19_orig.features[23])\n        self.features.add_module(str(24), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(25), vgg19_orig.features[25])\n        self.features.add_module(str(26), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(27), nn.AvgPool2d((2,2), (2,2)))\n\n        self.features.add_module(str(28), vgg19_orig.features[28])\n        self.features.add_module(str(29), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(30), vgg19_orig.features[30])\n        self.features.add_module(str(31), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(32), vgg19_orig.features[32])\n        self.features.add_module(str(33), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(34), vgg19_orig.features[34])\n        self.features.add_module(str(35), nn.LeakyReLU(slope, True))\n        self.features.add_module(str(36), nn.AvgPool2d((2,2), (2,2)))\n        \n        self.classifier = nn.Sequential()\n        \n        self.classifier.add_module(str(0), vgg19_orig.classifier[0])\n        self.classifier.add_module(str(1), nn.LeakyReLU(slope, True))\n        self.classifier.add_module(str(2), nn.Dropout2d(p = 0.5))\n        self.classifier.add_module(str(3), vgg19_orig.classifier[3])\n        self.classifier.add_module(str(4), nn.LeakyReLU(slope, True))\n        self.classifier.add_module(str(5), nn.Dropout2d(p = 0.5))\n        self.classifier.add_module(str(6), vgg19_orig.classifier[6])\n\n    def forward(self, x):\n        return self.classifier(self.features.forward(x))"
  },
  {
    "path": "utils/sr_utils.py",
    "content": "from .common_utils import *\n\ndef put_in_center(img_np, target_size):\n    img_out = np.zeros([3, target_size[0], target_size[1]])\n    \n    bbox = [\n            int((target_size[0] - img_np.shape[1]) / 2),\n            int((target_size[1] - img_np.shape[2]) / 2),\n            int((target_size[0] + img_np.shape[1]) / 2),\n            int((target_size[1] + img_np.shape[2]) / 2),\n    ]\n    \n    img_out[:, bbox[0]:bbox[2], bbox[1]:bbox[3]] = img_np\n    \n    return img_out\n\n\ndef load_LR_HR_imgs_sr(fname, imsize, factor, enforse_div32=None):\n    '''Loads an image, resizes it, center crops and downscales.\n\n    Args: \n        fname: path to the image\n        imsize: new size for the image, -1 for no resizing\n        factor: downscaling factor\n        enforse_div32: if 'CROP' center crops an image, so that its dimensions are divisible by 32.\n    '''\n    img_orig_pil, img_orig_np = get_image(fname, -1)\n\n    if imsize != -1:\n        img_orig_pil, img_orig_np = get_image(fname, imsize)\n        \n    # For comparison with GT\n    if enforse_div32 == 'CROP':\n        new_size = (img_orig_pil.size[0] - img_orig_pil.size[0] % 32, \n                    img_orig_pil.size[1] - img_orig_pil.size[1] % 32)\n\n        bbox = [\n                (img_orig_pil.size[0] - new_size[0])/2, \n                (img_orig_pil.size[1] - new_size[1])/2,\n                (img_orig_pil.size[0] + new_size[0])/2,\n                (img_orig_pil.size[1] + new_size[1])/2,\n        ]\n\n        img_HR_pil = img_orig_pil.crop(bbox)\n        img_HR_np = pil_to_np(img_HR_pil)\n    else:\n        img_HR_pil, img_HR_np = img_orig_pil, img_orig_np\n        \n    LR_size = [\n               img_HR_pil.size[0] // factor, \n               img_HR_pil.size[1] // factor\n    ]\n\n    img_LR_pil = img_HR_pil.resize(LR_size, Image.ANTIALIAS)\n    img_LR_np = pil_to_np(img_LR_pil)\n\n    print('HR and LR resolutions: %s, %s' % (str(img_HR_pil.size), str (img_LR_pil.size)))\n\n    return {\n                'orig_pil': img_orig_pil,\n                'orig_np':  img_orig_np,\n                'LR_pil':  img_LR_pil, \n                'LR_np': img_LR_np,\n                'HR_pil':  img_HR_pil, \n                'HR_np': img_HR_np\n           }\n\n\ndef get_baselines(img_LR_pil, img_HR_pil):\n    '''Gets `bicubic`, sharpened bicubic and `nearest` baselines.'''\n    img_bicubic_pil = img_LR_pil.resize(img_HR_pil.size, Image.BICUBIC)\n    img_bicubic_np = pil_to_np(img_bicubic_pil)\n\n    img_nearest_pil = img_LR_pil.resize(img_HR_pil.size, Image.NEAREST)\n    img_nearest_np = pil_to_np(img_nearest_pil)\n\n    img_bic_sharp_pil = img_bicubic_pil.filter(PIL.ImageFilter.UnsharpMask())\n    img_bic_sharp_np = pil_to_np(img_bic_sharp_pil)\n\n    return img_bicubic_np, img_bic_sharp_np, img_nearest_np\n\n\n\ndef tv_loss(x, beta = 0.5):\n    '''Calculates TV loss for an image `x`.\n        \n    Args:\n        x: image, torch.Variable of torch.Tensor\n        beta: See https://arxiv.org/abs/1412.0035 (fig. 2) to see effect of `beta` \n    '''\n    dh = torch.pow(x[:,:,:,1:] - x[:,:,:,:-1], 2)\n    dw = torch.pow(x[:,:,1:,:] - x[:,:,:-1,:], 2)\n    \n    return torch.sum(torch.pow(dh[:, :, :-1] + dw[:, :, :, :-1], beta))\n"
  }
]