Repository: liaoxy169/deep-image-prior
Branch: master
Commit: f01e27717f26
Files: 33
Total size: 157.7 KB
Directory structure:
gitextract_mdz9j85g/
├── Dockerfile
├── LICENSE
├── README.md
├── activation_maximization.ipynb
├── data/
│ └── imagenet1000_clsid_to_human.txt
├── denoising.ipynb
├── environment.yml
├── feature_inversion.ipynb
├── flash-no-flash.ipynb
├── inpainting.ipynb
├── models/
│ ├── __init__.py
│ ├── common.py
│ ├── dcgan.py
│ ├── downsampler.py
│ ├── resnet.py
│ ├── skip.py
│ ├── texture_nets.py
│ └── unet.py
├── restoration.ipynb
├── sr_prior_effect.ipynb
├── super-resolution.ipynb
├── super-resolution_eval_script.py
└── utils/
├── __init__.py
├── common_utils.py
├── denoising_utils.py
├── feature_inversion_utils.py
├── inpainting_utils.py
├── matcher.py
├── perceptual_loss/
│ ├── __init__.py
│ ├── matcher.py
│ ├── perceptual_loss.py
│ └── vgg_modified.py
└── sr_utils.py
================================================
FILE CONTENTS
================================================
================================================
FILE: Dockerfile
================================================
FROM nvidia/cuda:9.0-cudnn7-devel
# Install system dependencies
RUN apt-get update \
&& DEBIAN_FRONTEND=noninteractive apt-get install -y \
build-essential \
curl \
git \
&& apt-get clean
# Install python miniconda3 + requirements
ENV MINICONDA_HOME="/opt/miniconda"
ENV PATH="${MINICONDA_HOME}/bin:${PATH}"
RUN curl -o Miniconda3-latest-Linux-x86_64.sh https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh \
&& chmod +x Miniconda3-latest-Linux-x86_64.sh \
&& ./Miniconda3-latest-Linux-x86_64.sh -b -p "${MINICONDA_HOME}" \
&& rm Miniconda3-latest-Linux-x86_64.sh
COPY environment.yml environment.yml
RUN conda env update -n=root --file=environment.yml
RUN conda clean -y -i -l -p -t && \
rm environment.yml
# Clone deep image prior repository
RUN git clone https://github.com/DmitryUlyanov/deep-image-prior.git
WORKDIR /deep-image-prior
# Start container in notebook mode
CMD jupyter notebook --ip="*" --no-browser --allow-root
================================================
FILE: LICENSE
================================================
Apache License 2.0
But please contact me if you want to use this software in a commercial application.
Note that Apache License 2.0 asks to include a copyright notice if you use this software.
================================================
FILE: README.md
================================================
**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.
# Deep image prior
In this repository we provide *Jupyter Notebooks* to reproduce each figure from the paper:
> **Deep Image Prior**
> CVPR 2018
> Dmitry Ulyanov, Andrea Vedaldi, Victor Lempitsky
[[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)

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