aryrk
commited on
Commit
·
2bb76b3
1
Parent(s):
52882cc
[init]
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .gitignore +46 -0
- .replit +2 -0
- CycleGAN.ipynb +273 -0
- LICENSE +58 -0
- app.py +55 -0
- data/__init__.py +93 -0
- data/aligned_dataset.py +60 -0
- data/base_dataset.py +167 -0
- data/colorization_dataset.py +68 -0
- data/image_folder.py +65 -0
- data/single_dataset.py +40 -0
- data/template_dataset.py +75 -0
- data/unaligned_dataset.py +71 -0
- docs/Dockerfile +16 -0
- docs/README_es.md +238 -0
- docs/datasets.md +44 -0
- docs/docker.md +38 -0
- docs/overview.md +45 -0
- docs/qa.md +148 -0
- docs/tips.md +74 -0
- environment.yml +17 -0
- models/__init__.py +67 -0
- models/base_model.py +230 -0
- models/colorization_model.py +68 -0
- models/cycle_gan_model.py +194 -0
- models/networks.py +616 -0
- models/pix2pix_model.py +127 -0
- models/template_model.py +99 -0
- models/test_model.py +69 -0
- options/__init__.py +1 -0
- options/base_options.py +139 -0
- options/test_options.py +23 -0
- options/train_options.py +40 -0
- pix2pix.ipynb +283 -0
- requirements.txt +9 -0
- scripts/conda_deps.sh +4 -0
- scripts/download_cyclegan_model.sh +11 -0
- scripts/download_pix2pix_model.sh +10 -0
- scripts/edges/PostprocessHED.m +77 -0
- scripts/edges/batch_hed.py +81 -0
- scripts/eval_cityscapes/caffemodel/deploy.prototxt +769 -0
- scripts/eval_cityscapes/cityscapes.py +141 -0
- scripts/eval_cityscapes/download_fcn8s.sh +3 -0
- scripts/eval_cityscapes/evaluate.py +69 -0
- scripts/eval_cityscapes/util.py +42 -0
- scripts/install_deps.sh +3 -0
- scripts/test_before_push.py +51 -0
- scripts/test_colorization.sh +2 -0
- scripts/test_cyclegan.sh +2 -0
- scripts/test_pix2pix.sh +2 -0
.gitignore
ADDED
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.DS_Store
|
2 |
+
debug*
|
3 |
+
datasets/
|
4 |
+
checkpoints/
|
5 |
+
results/
|
6 |
+
build/
|
7 |
+
dist/
|
8 |
+
*.png
|
9 |
+
torch.egg-info/
|
10 |
+
*/**/__pycache__
|
11 |
+
torch/version.py
|
12 |
+
torch/csrc/generic/TensorMethods.cpp
|
13 |
+
torch/lib/*.so*
|
14 |
+
torch/lib/*.dylib*
|
15 |
+
torch/lib/*.h
|
16 |
+
torch/lib/build
|
17 |
+
torch/lib/tmp_install
|
18 |
+
torch/lib/include
|
19 |
+
torch/lib/torch_shm_manager
|
20 |
+
torch/csrc/cudnn/cuDNN.cpp
|
21 |
+
torch/csrc/nn/THNN.cwrap
|
22 |
+
torch/csrc/nn/THNN.cpp
|
23 |
+
torch/csrc/nn/THCUNN.cwrap
|
24 |
+
torch/csrc/nn/THCUNN.cpp
|
25 |
+
torch/csrc/nn/THNN_generic.cwrap
|
26 |
+
torch/csrc/nn/THNN_generic.cpp
|
27 |
+
torch/csrc/nn/THNN_generic.h
|
28 |
+
docs/src/**/*
|
29 |
+
test/data/legacy_modules.t7
|
30 |
+
test/data/gpu_tensors.pt
|
31 |
+
test/htmlcov
|
32 |
+
test/.coverage
|
33 |
+
*/*.pyc
|
34 |
+
*/**/*.pyc
|
35 |
+
*/**/**/*.pyc
|
36 |
+
*/**/**/**/*.pyc
|
37 |
+
*/**/**/**/**/*.pyc
|
38 |
+
*/*.so*
|
39 |
+
*/**/*.so*
|
40 |
+
*/**/*.dylib*
|
41 |
+
test/data/legacy_serialized.pt
|
42 |
+
*~
|
43 |
+
.idea
|
44 |
+
|
45 |
+
#Ignore Wandb
|
46 |
+
wandb/
|
.replit
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
language = "python3"
|
2 |
+
run = "<p><a href=\"https://github.com/affinelayer/pix2pix-tensorflow\"> [Tensorflow]</a> (by Christopher Hesse), <a href=\"https://github.com/Eyyub/tensorflow-pix2pix\">[Tensorflow]</a> (by Eyyüb Sariu), <a href=\"https://github.com/datitran/face2face-demo\"> [Tensorflow (face2face)]</a> (by Dat Tran), <a href=\"https://github.com/awjuliani/Pix2Pix-Film\"> [Tensorflow (film)]</a> (by Arthur Juliani), <a href=\"https://github.com/kaonashi-tyc/zi2zi\">[Tensorflow (zi2zi)]</a> (by Yuchen Tian), <a href=\"https://github.com/pfnet-research/chainer-pix2pix\">[Chainer]</a> (by mattya), <a href=\"https://github.com/tjwei/GANotebooks\">[tf/torch/keras/lasagne]</a> (by tjwei), <a href=\"https://github.com/taey16/pix2pixBEGAN.pytorch\">[Pytorch]</a> (by taey16) </p> </ul>"
|
CycleGAN.ipynb
ADDED
@@ -0,0 +1,273 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"metadata": {
|
6 |
+
"colab_type": "text",
|
7 |
+
"id": "view-in-github"
|
8 |
+
},
|
9 |
+
"source": [
|
10 |
+
"<a href=\"https://colab.research.google.com/github/bkkaggle/pytorch-CycleGAN-and-pix2pix/blob/master/CycleGAN.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
11 |
+
]
|
12 |
+
},
|
13 |
+
{
|
14 |
+
"cell_type": "markdown",
|
15 |
+
"metadata": {
|
16 |
+
"colab_type": "text",
|
17 |
+
"id": "5VIGyIus8Vr7"
|
18 |
+
},
|
19 |
+
"source": [
|
20 |
+
"Take a look at the [repository](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix) for more information"
|
21 |
+
]
|
22 |
+
},
|
23 |
+
{
|
24 |
+
"cell_type": "markdown",
|
25 |
+
"metadata": {
|
26 |
+
"colab_type": "text",
|
27 |
+
"id": "7wNjDKdQy35h"
|
28 |
+
},
|
29 |
+
"source": [
|
30 |
+
"# Install"
|
31 |
+
]
|
32 |
+
},
|
33 |
+
{
|
34 |
+
"cell_type": "code",
|
35 |
+
"execution_count": null,
|
36 |
+
"metadata": {
|
37 |
+
"colab": {},
|
38 |
+
"colab_type": "code",
|
39 |
+
"id": "TRm-USlsHgEV"
|
40 |
+
},
|
41 |
+
"outputs": [],
|
42 |
+
"source": [
|
43 |
+
"!git clone https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix"
|
44 |
+
]
|
45 |
+
},
|
46 |
+
{
|
47 |
+
"cell_type": "code",
|
48 |
+
"execution_count": null,
|
49 |
+
"metadata": {
|
50 |
+
"colab": {},
|
51 |
+
"colab_type": "code",
|
52 |
+
"id": "Pt3igws3eiVp"
|
53 |
+
},
|
54 |
+
"outputs": [],
|
55 |
+
"source": [
|
56 |
+
"import os\n",
|
57 |
+
"os.chdir('pytorch-CycleGAN-and-pix2pix/')"
|
58 |
+
]
|
59 |
+
},
|
60 |
+
{
|
61 |
+
"cell_type": "code",
|
62 |
+
"execution_count": null,
|
63 |
+
"metadata": {
|
64 |
+
"colab": {},
|
65 |
+
"colab_type": "code",
|
66 |
+
"id": "z1EySlOXwwoa"
|
67 |
+
},
|
68 |
+
"outputs": [],
|
69 |
+
"source": [
|
70 |
+
"!pip install -r requirements.txt"
|
71 |
+
]
|
72 |
+
},
|
73 |
+
{
|
74 |
+
"cell_type": "markdown",
|
75 |
+
"metadata": {
|
76 |
+
"colab_type": "text",
|
77 |
+
"id": "8daqlgVhw29P"
|
78 |
+
},
|
79 |
+
"source": [
|
80 |
+
"# Datasets\n",
|
81 |
+
"\n",
|
82 |
+
"Download one of the official datasets with:\n",
|
83 |
+
"\n",
|
84 |
+
"- `bash ./datasets/download_cyclegan_dataset.sh [apple2orange, summer2winter_yosemite, horse2zebra, monet2photo, cezanne2photo, ukiyoe2photo, vangogh2photo, maps, cityscapes, facades, iphone2dslr_flower, ae_photos]`\n",
|
85 |
+
"\n",
|
86 |
+
"Or use your own dataset by creating the appropriate folders and adding in the images.\n",
|
87 |
+
"\n",
|
88 |
+
"- Create a dataset folder under `/dataset` for your dataset.\n",
|
89 |
+
"- Create subfolders `testA`, `testB`, `trainA`, and `trainB` under your dataset's folder. Place any images you want to transform from a to b (cat2dog) in the `testA` folder, images you want to transform from b to a (dog2cat) in the `testB` folder, and do the same for the `trainA` and `trainB` folders."
|
90 |
+
]
|
91 |
+
},
|
92 |
+
{
|
93 |
+
"cell_type": "code",
|
94 |
+
"execution_count": null,
|
95 |
+
"metadata": {
|
96 |
+
"colab": {},
|
97 |
+
"colab_type": "code",
|
98 |
+
"id": "vrdOettJxaCc"
|
99 |
+
},
|
100 |
+
"outputs": [],
|
101 |
+
"source": [
|
102 |
+
"!bash ./datasets/download_cyclegan_dataset.sh horse2zebra"
|
103 |
+
]
|
104 |
+
},
|
105 |
+
{
|
106 |
+
"cell_type": "markdown",
|
107 |
+
"metadata": {
|
108 |
+
"colab_type": "text",
|
109 |
+
"id": "gdUz4116xhpm"
|
110 |
+
},
|
111 |
+
"source": [
|
112 |
+
"# Pretrained models\n",
|
113 |
+
"\n",
|
114 |
+
"Download one of the official pretrained models with:\n",
|
115 |
+
"\n",
|
116 |
+
"- `bash ./scripts/download_cyclegan_model.sh [apple2orange, orange2apple, summer2winter_yosemite, winter2summer_yosemite, horse2zebra, zebra2horse, monet2photo, style_monet, style_cezanne, style_ukiyoe, style_vangogh, sat2map, map2sat, cityscapes_photo2label, cityscapes_label2photo, facades_photo2label, facades_label2photo, iphone2dslr_flower]`\n",
|
117 |
+
"\n",
|
118 |
+
"Or add your own pretrained model to `./checkpoints/{NAME}_pretrained/latest_net_G.pt`"
|
119 |
+
]
|
120 |
+
},
|
121 |
+
{
|
122 |
+
"cell_type": "code",
|
123 |
+
"execution_count": null,
|
124 |
+
"metadata": {
|
125 |
+
"colab": {},
|
126 |
+
"colab_type": "code",
|
127 |
+
"id": "B75UqtKhxznS"
|
128 |
+
},
|
129 |
+
"outputs": [],
|
130 |
+
"source": [
|
131 |
+
"!bash ./scripts/download_cyclegan_model.sh horse2zebra"
|
132 |
+
]
|
133 |
+
},
|
134 |
+
{
|
135 |
+
"cell_type": "markdown",
|
136 |
+
"metadata": {
|
137 |
+
"colab_type": "text",
|
138 |
+
"id": "yFw1kDQBx3LN"
|
139 |
+
},
|
140 |
+
"source": [
|
141 |
+
"# Training\n",
|
142 |
+
"\n",
|
143 |
+
"- `python train.py --dataroot ./datasets/horse2zebra --name horse2zebra --model cycle_gan`\n",
|
144 |
+
"\n",
|
145 |
+
"Change the `--dataroot` and `--name` to your own dataset's path and model's name. Use `--gpu_ids 0,1,..` to train on multiple GPUs and `--batch_size` to change the batch size. I've found that a batch size of 16 fits onto 4 V100s and can finish training an epoch in ~90s.\n",
|
146 |
+
"\n",
|
147 |
+
"Once your model has trained, copy over the last checkpoint to a format that the testing model can automatically detect:\n",
|
148 |
+
"\n",
|
149 |
+
"Use `cp ./checkpoints/horse2zebra/latest_net_G_A.pth ./checkpoints/horse2zebra/latest_net_G.pth` if you want to transform images from class A to class B and `cp ./checkpoints/horse2zebra/latest_net_G_B.pth ./checkpoints/horse2zebra/latest_net_G.pth` if you want to transform images from class B to class A.\n"
|
150 |
+
]
|
151 |
+
},
|
152 |
+
{
|
153 |
+
"cell_type": "code",
|
154 |
+
"execution_count": null,
|
155 |
+
"metadata": {
|
156 |
+
"colab": {},
|
157 |
+
"colab_type": "code",
|
158 |
+
"id": "0sp7TCT2x9dB"
|
159 |
+
},
|
160 |
+
"outputs": [],
|
161 |
+
"source": [
|
162 |
+
"!python train.py --dataroot ./datasets/horse2zebra --name horse2zebra --model cycle_gan --display_id -1"
|
163 |
+
]
|
164 |
+
},
|
165 |
+
{
|
166 |
+
"cell_type": "markdown",
|
167 |
+
"metadata": {
|
168 |
+
"colab_type": "text",
|
169 |
+
"id": "9UkcaFZiyASl"
|
170 |
+
},
|
171 |
+
"source": [
|
172 |
+
"# Testing\n",
|
173 |
+
"\n",
|
174 |
+
"- `python test.py --dataroot datasets/horse2zebra/testA --name horse2zebra_pretrained --model test --no_dropout`\n",
|
175 |
+
"\n",
|
176 |
+
"Change the `--dataroot` and `--name` to be consistent with your trained model's configuration.\n",
|
177 |
+
"\n",
|
178 |
+
"> from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix:\n",
|
179 |
+
"> The option --model test is used for generating results of CycleGAN only for one side. This option will automatically set --dataset_mode single, which only loads the images from one set. On the contrary, using --model cycle_gan requires loading and generating results in both directions, which is sometimes unnecessary. The results will be saved at ./results/. Use --results_dir {directory_path_to_save_result} to specify the results directory.\n",
|
180 |
+
"\n",
|
181 |
+
"> For your own experiments, you might want to specify --netG, --norm, --no_dropout to match the generator architecture of the trained model."
|
182 |
+
]
|
183 |
+
},
|
184 |
+
{
|
185 |
+
"cell_type": "code",
|
186 |
+
"execution_count": null,
|
187 |
+
"metadata": {
|
188 |
+
"colab": {},
|
189 |
+
"colab_type": "code",
|
190 |
+
"id": "uCsKkEq0yGh0"
|
191 |
+
},
|
192 |
+
"outputs": [],
|
193 |
+
"source": [
|
194 |
+
"!python test.py --dataroot datasets/horse2zebra/testA --name horse2zebra_pretrained --model test --no_dropout"
|
195 |
+
]
|
196 |
+
},
|
197 |
+
{
|
198 |
+
"cell_type": "markdown",
|
199 |
+
"metadata": {
|
200 |
+
"colab_type": "text",
|
201 |
+
"id": "OzSKIPUByfiN"
|
202 |
+
},
|
203 |
+
"source": [
|
204 |
+
"# Visualize"
|
205 |
+
]
|
206 |
+
},
|
207 |
+
{
|
208 |
+
"cell_type": "code",
|
209 |
+
"execution_count": null,
|
210 |
+
"metadata": {
|
211 |
+
"colab": {},
|
212 |
+
"colab_type": "code",
|
213 |
+
"id": "9Mgg8raPyizq"
|
214 |
+
},
|
215 |
+
"outputs": [],
|
216 |
+
"source": [
|
217 |
+
"import matplotlib.pyplot as plt\n",
|
218 |
+
"\n",
|
219 |
+
"img = plt.imread('./results/horse2zebra_pretrained/test_latest/images/n02381460_1010_fake.png')\n",
|
220 |
+
"plt.imshow(img)"
|
221 |
+
]
|
222 |
+
},
|
223 |
+
{
|
224 |
+
"cell_type": "code",
|
225 |
+
"execution_count": null,
|
226 |
+
"metadata": {
|
227 |
+
"colab": {},
|
228 |
+
"colab_type": "code",
|
229 |
+
"id": "0G3oVH9DyqLQ"
|
230 |
+
},
|
231 |
+
"outputs": [],
|
232 |
+
"source": [
|
233 |
+
"import matplotlib.pyplot as plt\n",
|
234 |
+
"\n",
|
235 |
+
"img = plt.imread('./results/horse2zebra_pretrained/test_latest/images/n02381460_1010_real.png')\n",
|
236 |
+
"plt.imshow(img)"
|
237 |
+
]
|
238 |
+
}
|
239 |
+
],
|
240 |
+
"metadata": {
|
241 |
+
"accelerator": "GPU",
|
242 |
+
"colab": {
|
243 |
+
"collapsed_sections": [],
|
244 |
+
"include_colab_link": true,
|
245 |
+
"name": "CycleGAN",
|
246 |
+
"provenance": []
|
247 |
+
},
|
248 |
+
"environment": {
|
249 |
+
"name": "tf2-gpu.2-3.m74",
|
250 |
+
"type": "gcloud",
|
251 |
+
"uri": "gcr.io/deeplearning-platform-release/tf2-gpu.2-3:m74"
|
252 |
+
},
|
253 |
+
"kernelspec": {
|
254 |
+
"display_name": "Python 3",
|
255 |
+
"language": "python",
|
256 |
+
"name": "python3"
|
257 |
+
},
|
258 |
+
"language_info": {
|
259 |
+
"codemirror_mode": {
|
260 |
+
"name": "ipython",
|
261 |
+
"version": 3
|
262 |
+
},
|
263 |
+
"file_extension": ".py",
|
264 |
+
"mimetype": "text/x-python",
|
265 |
+
"name": "python",
|
266 |
+
"nbconvert_exporter": "python",
|
267 |
+
"pygments_lexer": "ipython3",
|
268 |
+
"version": "3.7.10"
|
269 |
+
}
|
270 |
+
},
|
271 |
+
"nbformat": 4,
|
272 |
+
"nbformat_minor": 4
|
273 |
+
}
|
LICENSE
ADDED
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Copyright (c) 2017, Jun-Yan Zhu and Taesung Park
|
2 |
+
All rights reserved.
|
3 |
+
|
4 |
+
Redistribution and use in source and binary forms, with or without
|
5 |
+
modification, are permitted provided that the following conditions are met:
|
6 |
+
|
7 |
+
* Redistributions of source code must retain the above copyright notice, this
|
8 |
+
list of conditions and the following disclaimer.
|
9 |
+
|
10 |
+
* Redistributions in binary form must reproduce the above copyright notice,
|
11 |
+
this list of conditions and the following disclaimer in the documentation
|
12 |
+
and/or other materials provided with the distribution.
|
13 |
+
|
14 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
15 |
+
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
16 |
+
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
17 |
+
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
18 |
+
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
19 |
+
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
20 |
+
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
21 |
+
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
22 |
+
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
23 |
+
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
24 |
+
|
25 |
+
|
26 |
+
--------------------------- LICENSE FOR pix2pix --------------------------------
|
27 |
+
BSD License
|
28 |
+
|
29 |
+
For pix2pix software
|
30 |
+
Copyright (c) 2016, Phillip Isola and Jun-Yan Zhu
|
31 |
+
All rights reserved.
|
32 |
+
|
33 |
+
Redistribution and use in source and binary forms, with or without
|
34 |
+
modification, are permitted provided that the following conditions are met:
|
35 |
+
|
36 |
+
* Redistributions of source code must retain the above copyright notice, this
|
37 |
+
list of conditions and the following disclaimer.
|
38 |
+
|
39 |
+
* Redistributions in binary form must reproduce the above copyright notice,
|
40 |
+
this list of conditions and the following disclaimer in the documentation
|
41 |
+
and/or other materials provided with the distribution.
|
42 |
+
|
43 |
+
----------------------------- LICENSE FOR DCGAN --------------------------------
|
44 |
+
BSD License
|
45 |
+
|
46 |
+
For dcgan.torch software
|
47 |
+
|
48 |
+
Copyright (c) 2015, Facebook, Inc. All rights reserved.
|
49 |
+
|
50 |
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
51 |
+
|
52 |
+
Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
53 |
+
|
54 |
+
Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
55 |
+
|
56 |
+
Neither the name Facebook nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
57 |
+
|
58 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
app.py
ADDED
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import shutil
|
3 |
+
import os
|
4 |
+
import subprocess
|
5 |
+
from PIL import Image
|
6 |
+
from huggingface_hub import hf_hub_download
|
7 |
+
|
8 |
+
UPLOAD_DIR = "./uploaded_images"
|
9 |
+
RESULTS_DIR = "./results"
|
10 |
+
CHECKPOINTS_DIR = "./checkpoints/SingleImageReflectionRemoval"
|
11 |
+
|
12 |
+
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
13 |
+
os.makedirs(RESULTS_DIR, exist_ok=True)
|
14 |
+
os.makedirs(CHECKPOINTS_DIR, exist_ok=True)
|
15 |
+
|
16 |
+
REPO_ID = "hasnafk/SingleImageReflectionRemoval"
|
17 |
+
MODEL_FILE = "pix2pix_model.pth"
|
18 |
+
|
19 |
+
model_path = hf_hub_download(repo_id=REPO_ID, filename=MODEL_FILE, cache_dir=CHECKPOINTS_DIR)
|
20 |
+
|
21 |
+
def reflection_removal(input_images):
|
22 |
+
for input_image in input_images:
|
23 |
+
file_path = os.path.join(UPLOAD_DIR, input_image.name)
|
24 |
+
input_image.save(file_path)
|
25 |
+
|
26 |
+
cmd = [
|
27 |
+
"python", "test.py",
|
28 |
+
"--dataroot", UPLOAD_DIR,
|
29 |
+
"--name", "SingleImageReflectionRemoval",
|
30 |
+
"--model", "test", "--netG", "unet_256",
|
31 |
+
"--direction", "AtoB", "--dataset_mode", "single",
|
32 |
+
"--norm", "batch", "--epoch", "310",
|
33 |
+
"--num_test", str(len(input_images)),
|
34 |
+
"--gpu_ids", "-1"
|
35 |
+
]
|
36 |
+
subprocess.run(cmd, check=True)
|
37 |
+
|
38 |
+
output_images = []
|
39 |
+
for root, _, files in os.walk(RESULTS_DIR):
|
40 |
+
for file in files:
|
41 |
+
if file.endswith("_fake_B.png"):
|
42 |
+
output_images.append(Image.open(os.path.join(root, file)))
|
43 |
+
|
44 |
+
return output_images
|
45 |
+
|
46 |
+
iface = gr.Interface(
|
47 |
+
fn=reflection_removal,
|
48 |
+
inputs=gr.File(file_types=["image"], file_count="multiple"),
|
49 |
+
outputs=gr.Gallery(label="Results after Reflection Removal"),
|
50 |
+
title="Reflection Remover with Pix2Pix",
|
51 |
+
description="Upload images to remove reflections using a Pix2Pix model."
|
52 |
+
)
|
53 |
+
|
54 |
+
if __name__ == "__main__":
|
55 |
+
iface.launch()
|
data/__init__.py
ADDED
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""This package includes all the modules related to data loading and preprocessing
|
2 |
+
|
3 |
+
To add a custom dataset class called 'dummy', you need to add a file called 'dummy_dataset.py' and define a subclass 'DummyDataset' inherited from BaseDataset.
|
4 |
+
You need to implement four functions:
|
5 |
+
-- <__init__>: initialize the class, first call BaseDataset.__init__(self, opt).
|
6 |
+
-- <__len__>: return the size of dataset.
|
7 |
+
-- <__getitem__>: get a data point from data loader.
|
8 |
+
-- <modify_commandline_options>: (optionally) add dataset-specific options and set default options.
|
9 |
+
|
10 |
+
Now you can use the dataset class by specifying flag '--dataset_mode dummy'.
|
11 |
+
See our template dataset class 'template_dataset.py' for more details.
|
12 |
+
"""
|
13 |
+
import importlib
|
14 |
+
import torch.utils.data
|
15 |
+
from data.base_dataset import BaseDataset
|
16 |
+
|
17 |
+
|
18 |
+
def find_dataset_using_name(dataset_name):
|
19 |
+
"""Import the module "data/[dataset_name]_dataset.py".
|
20 |
+
|
21 |
+
In the file, the class called DatasetNameDataset() will
|
22 |
+
be instantiated. It has to be a subclass of BaseDataset,
|
23 |
+
and it is case-insensitive.
|
24 |
+
"""
|
25 |
+
dataset_filename = "data." + dataset_name + "_dataset"
|
26 |
+
datasetlib = importlib.import_module(dataset_filename)
|
27 |
+
|
28 |
+
dataset = None
|
29 |
+
target_dataset_name = dataset_name.replace('_', '') + 'dataset'
|
30 |
+
for name, cls in datasetlib.__dict__.items():
|
31 |
+
if name.lower() == target_dataset_name.lower() \
|
32 |
+
and issubclass(cls, BaseDataset):
|
33 |
+
dataset = cls
|
34 |
+
|
35 |
+
if dataset is None:
|
36 |
+
raise NotImplementedError("In %s.py, there should be a subclass of BaseDataset with class name that matches %s in lowercase." % (dataset_filename, target_dataset_name))
|
37 |
+
|
38 |
+
return dataset
|
39 |
+
|
40 |
+
|
41 |
+
def get_option_setter(dataset_name):
|
42 |
+
"""Return the static method <modify_commandline_options> of the dataset class."""
|
43 |
+
dataset_class = find_dataset_using_name(dataset_name)
|
44 |
+
return dataset_class.modify_commandline_options
|
45 |
+
|
46 |
+
|
47 |
+
def create_dataset(opt):
|
48 |
+
"""Create a dataset given the option.
|
49 |
+
|
50 |
+
This function wraps the class CustomDatasetDataLoader.
|
51 |
+
This is the main interface between this package and 'train.py'/'test.py'
|
52 |
+
|
53 |
+
Example:
|
54 |
+
>>> from data import create_dataset
|
55 |
+
>>> dataset = create_dataset(opt)
|
56 |
+
"""
|
57 |
+
data_loader = CustomDatasetDataLoader(opt)
|
58 |
+
dataset = data_loader.load_data()
|
59 |
+
return dataset
|
60 |
+
|
61 |
+
|
62 |
+
class CustomDatasetDataLoader():
|
63 |
+
"""Wrapper class of Dataset class that performs multi-threaded data loading"""
|
64 |
+
|
65 |
+
def __init__(self, opt):
|
66 |
+
"""Initialize this class
|
67 |
+
|
68 |
+
Step 1: create a dataset instance given the name [dataset_mode]
|
69 |
+
Step 2: create a multi-threaded data loader.
|
70 |
+
"""
|
71 |
+
self.opt = opt
|
72 |
+
dataset_class = find_dataset_using_name(opt.dataset_mode)
|
73 |
+
self.dataset = dataset_class(opt)
|
74 |
+
print("dataset [%s] was created" % type(self.dataset).__name__)
|
75 |
+
self.dataloader = torch.utils.data.DataLoader(
|
76 |
+
self.dataset,
|
77 |
+
batch_size=opt.batch_size,
|
78 |
+
shuffle=not opt.serial_batches,
|
79 |
+
num_workers=int(opt.num_threads))
|
80 |
+
|
81 |
+
def load_data(self):
|
82 |
+
return self
|
83 |
+
|
84 |
+
def __len__(self):
|
85 |
+
"""Return the number of data in the dataset"""
|
86 |
+
return min(len(self.dataset), self.opt.max_dataset_size)
|
87 |
+
|
88 |
+
def __iter__(self):
|
89 |
+
"""Return a batch of data"""
|
90 |
+
for i, data in enumerate(self.dataloader):
|
91 |
+
if i * self.opt.batch_size >= self.opt.max_dataset_size:
|
92 |
+
break
|
93 |
+
yield data
|
data/aligned_dataset.py
ADDED
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from data.base_dataset import BaseDataset, get_params, get_transform
|
3 |
+
from data.image_folder import make_dataset
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
|
7 |
+
class AlignedDataset(BaseDataset):
|
8 |
+
"""A dataset class for paired image dataset.
|
9 |
+
|
10 |
+
It assumes that the directory '/path/to/data/train' contains image pairs in the form of {A,B}.
|
11 |
+
During test time, you need to prepare a directory '/path/to/data/test'.
|
12 |
+
"""
|
13 |
+
|
14 |
+
def __init__(self, opt):
|
15 |
+
"""Initialize this dataset class.
|
16 |
+
|
17 |
+
Parameters:
|
18 |
+
opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
|
19 |
+
"""
|
20 |
+
BaseDataset.__init__(self, opt)
|
21 |
+
self.dir_AB = os.path.join(opt.dataroot, opt.phase) # get the image directory
|
22 |
+
self.AB_paths = sorted(make_dataset(self.dir_AB, opt.max_dataset_size)) # get image paths
|
23 |
+
assert(self.opt.load_size >= self.opt.crop_size) # crop_size should be smaller than the size of loaded image
|
24 |
+
self.input_nc = self.opt.output_nc if self.opt.direction == 'BtoA' else self.opt.input_nc
|
25 |
+
self.output_nc = self.opt.input_nc if self.opt.direction == 'BtoA' else self.opt.output_nc
|
26 |
+
|
27 |
+
def __getitem__(self, index):
|
28 |
+
"""Return a data point and its metadata information.
|
29 |
+
|
30 |
+
Parameters:
|
31 |
+
index - - a random integer for data indexing
|
32 |
+
|
33 |
+
Returns a dictionary that contains A, B, A_paths and B_paths
|
34 |
+
A (tensor) - - an image in the input domain
|
35 |
+
B (tensor) - - its corresponding image in the target domain
|
36 |
+
A_paths (str) - - image paths
|
37 |
+
B_paths (str) - - image paths (same as A_paths)
|
38 |
+
"""
|
39 |
+
# read a image given a random integer index
|
40 |
+
AB_path = self.AB_paths[index]
|
41 |
+
AB = Image.open(AB_path).convert('RGB')
|
42 |
+
# split AB image into A and B
|
43 |
+
w, h = AB.size
|
44 |
+
w2 = int(w / 2)
|
45 |
+
A = AB.crop((0, 0, w2, h))
|
46 |
+
B = AB.crop((w2, 0, w, h))
|
47 |
+
|
48 |
+
# apply the same transform to both A and B
|
49 |
+
transform_params = get_params(self.opt, A.size)
|
50 |
+
A_transform = get_transform(self.opt, transform_params, grayscale=(self.input_nc == 1))
|
51 |
+
B_transform = get_transform(self.opt, transform_params, grayscale=(self.output_nc == 1))
|
52 |
+
|
53 |
+
A = A_transform(A)
|
54 |
+
B = B_transform(B)
|
55 |
+
|
56 |
+
return {'A': A, 'B': B, 'A_paths': AB_path, 'B_paths': AB_path}
|
57 |
+
|
58 |
+
def __len__(self):
|
59 |
+
"""Return the total number of images in the dataset."""
|
60 |
+
return len(self.AB_paths)
|
data/base_dataset.py
ADDED
@@ -0,0 +1,167 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""This module implements an abstract base class (ABC) 'BaseDataset' for datasets.
|
2 |
+
|
3 |
+
It also includes common transformation functions (e.g., get_transform, __scale_width), which can be later used in subclasses.
|
4 |
+
"""
|
5 |
+
import random
|
6 |
+
import numpy as np
|
7 |
+
import torch.utils.data as data
|
8 |
+
from PIL import Image
|
9 |
+
import torchvision.transforms as transforms
|
10 |
+
from abc import ABC, abstractmethod
|
11 |
+
|
12 |
+
|
13 |
+
class BaseDataset(data.Dataset, ABC):
|
14 |
+
"""This class is an abstract base class (ABC) for datasets.
|
15 |
+
|
16 |
+
To create a subclass, you need to implement the following four functions:
|
17 |
+
-- <__init__>: initialize the class, first call BaseDataset.__init__(self, opt).
|
18 |
+
-- <__len__>: return the size of dataset.
|
19 |
+
-- <__getitem__>: get a data point.
|
20 |
+
-- <modify_commandline_options>: (optionally) add dataset-specific options and set default options.
|
21 |
+
"""
|
22 |
+
|
23 |
+
def __init__(self, opt):
|
24 |
+
"""Initialize the class; save the options in the class
|
25 |
+
|
26 |
+
Parameters:
|
27 |
+
opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
|
28 |
+
"""
|
29 |
+
self.opt = opt
|
30 |
+
self.root = opt.dataroot
|
31 |
+
|
32 |
+
@staticmethod
|
33 |
+
def modify_commandline_options(parser, is_train):
|
34 |
+
"""Add new dataset-specific options, and rewrite default values for existing options.
|
35 |
+
|
36 |
+
Parameters:
|
37 |
+
parser -- original option parser
|
38 |
+
is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.
|
39 |
+
|
40 |
+
Returns:
|
41 |
+
the modified parser.
|
42 |
+
"""
|
43 |
+
return parser
|
44 |
+
|
45 |
+
@abstractmethod
|
46 |
+
def __len__(self):
|
47 |
+
"""Return the total number of images in the dataset."""
|
48 |
+
return 0
|
49 |
+
|
50 |
+
@abstractmethod
|
51 |
+
def __getitem__(self, index):
|
52 |
+
"""Return a data point and its metadata information.
|
53 |
+
|
54 |
+
Parameters:
|
55 |
+
index - - a random integer for data indexing
|
56 |
+
|
57 |
+
Returns:
|
58 |
+
a dictionary of data with their names. It ususally contains the data itself and its metadata information.
|
59 |
+
"""
|
60 |
+
pass
|
61 |
+
|
62 |
+
|
63 |
+
def get_params(opt, size):
|
64 |
+
w, h = size
|
65 |
+
new_h = h
|
66 |
+
new_w = w
|
67 |
+
if opt.preprocess == 'resize_and_crop':
|
68 |
+
new_h = new_w = opt.load_size
|
69 |
+
elif opt.preprocess == 'scale_width_and_crop':
|
70 |
+
new_w = opt.load_size
|
71 |
+
new_h = opt.load_size * h // w
|
72 |
+
|
73 |
+
x = random.randint(0, np.maximum(0, new_w - opt.crop_size))
|
74 |
+
y = random.randint(0, np.maximum(0, new_h - opt.crop_size))
|
75 |
+
|
76 |
+
flip = random.random() > 0.5
|
77 |
+
|
78 |
+
return {'crop_pos': (x, y), 'flip': flip}
|
79 |
+
|
80 |
+
|
81 |
+
def get_transform(opt, params=None, grayscale=False, method=transforms.InterpolationMode.BICUBIC, convert=True):
|
82 |
+
transform_list = []
|
83 |
+
if grayscale:
|
84 |
+
transform_list.append(transforms.Grayscale(1))
|
85 |
+
if 'resize' in opt.preprocess:
|
86 |
+
osize = [opt.load_size, opt.load_size]
|
87 |
+
transform_list.append(transforms.Resize(osize, method))
|
88 |
+
elif 'scale_width' in opt.preprocess:
|
89 |
+
transform_list.append(transforms.Lambda(lambda img: __scale_width(img, opt.load_size, opt.crop_size, method)))
|
90 |
+
|
91 |
+
if 'crop' in opt.preprocess:
|
92 |
+
if params is None:
|
93 |
+
transform_list.append(transforms.RandomCrop(opt.crop_size))
|
94 |
+
else:
|
95 |
+
transform_list.append(transforms.Lambda(lambda img: __crop(img, params['crop_pos'], opt.crop_size)))
|
96 |
+
|
97 |
+
if opt.preprocess == 'none':
|
98 |
+
transform_list.append(transforms.Lambda(lambda img: __make_power_2(img, base=4, method=method)))
|
99 |
+
|
100 |
+
if not opt.no_flip:
|
101 |
+
if params is None:
|
102 |
+
transform_list.append(transforms.RandomHorizontalFlip())
|
103 |
+
elif params['flip']:
|
104 |
+
transform_list.append(transforms.Lambda(lambda img: __flip(img, params['flip'])))
|
105 |
+
|
106 |
+
if convert:
|
107 |
+
transform_list += [transforms.ToTensor()]
|
108 |
+
if grayscale:
|
109 |
+
transform_list += [transforms.Normalize((0.5,), (0.5,))]
|
110 |
+
else:
|
111 |
+
transform_list += [transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))]
|
112 |
+
return transforms.Compose(transform_list)
|
113 |
+
|
114 |
+
|
115 |
+
def __transforms2pil_resize(method):
|
116 |
+
mapper = {transforms.InterpolationMode.BILINEAR: Image.BILINEAR,
|
117 |
+
transforms.InterpolationMode.BICUBIC: Image.BICUBIC,
|
118 |
+
transforms.InterpolationMode.NEAREST: Image.NEAREST,
|
119 |
+
transforms.InterpolationMode.LANCZOS: Image.LANCZOS,}
|
120 |
+
return mapper[method]
|
121 |
+
|
122 |
+
|
123 |
+
def __make_power_2(img, base, method=transforms.InterpolationMode.BICUBIC):
|
124 |
+
method = __transforms2pil_resize(method)
|
125 |
+
ow, oh = img.size
|
126 |
+
h = int(round(oh / base) * base)
|
127 |
+
w = int(round(ow / base) * base)
|
128 |
+
if h == oh and w == ow:
|
129 |
+
return img
|
130 |
+
|
131 |
+
__print_size_warning(ow, oh, w, h)
|
132 |
+
return img.resize((w, h), method)
|
133 |
+
|
134 |
+
|
135 |
+
def __scale_width(img, target_size, crop_size, method=transforms.InterpolationMode.BICUBIC):
|
136 |
+
method = __transforms2pil_resize(method)
|
137 |
+
ow, oh = img.size
|
138 |
+
if ow == target_size and oh >= crop_size:
|
139 |
+
return img
|
140 |
+
w = target_size
|
141 |
+
h = int(max(target_size * oh / ow, crop_size))
|
142 |
+
return img.resize((w, h), method)
|
143 |
+
|
144 |
+
|
145 |
+
def __crop(img, pos, size):
|
146 |
+
ow, oh = img.size
|
147 |
+
x1, y1 = pos
|
148 |
+
tw = th = size
|
149 |
+
if (ow > tw or oh > th):
|
150 |
+
return img.crop((x1, y1, x1 + tw, y1 + th))
|
151 |
+
return img
|
152 |
+
|
153 |
+
|
154 |
+
def __flip(img, flip):
|
155 |
+
if flip:
|
156 |
+
return img.transpose(Image.FLIP_LEFT_RIGHT)
|
157 |
+
return img
|
158 |
+
|
159 |
+
|
160 |
+
def __print_size_warning(ow, oh, w, h):
|
161 |
+
"""Print warning information about image size(only print once)"""
|
162 |
+
if not hasattr(__print_size_warning, 'has_printed'):
|
163 |
+
print("The image size needs to be a multiple of 4. "
|
164 |
+
"The loaded image size was (%d, %d), so it was adjusted to "
|
165 |
+
"(%d, %d). This adjustment will be done to all images "
|
166 |
+
"whose sizes are not multiples of 4" % (ow, oh, w, h))
|
167 |
+
__print_size_warning.has_printed = True
|
data/colorization_dataset.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from data.base_dataset import BaseDataset, get_transform
|
3 |
+
from data.image_folder import make_dataset
|
4 |
+
from skimage import color # require skimage
|
5 |
+
from PIL import Image
|
6 |
+
import numpy as np
|
7 |
+
import torchvision.transforms as transforms
|
8 |
+
|
9 |
+
|
10 |
+
class ColorizationDataset(BaseDataset):
|
11 |
+
"""This dataset class can load a set of natural images in RGB, and convert RGB format into (L, ab) pairs in Lab color space.
|
12 |
+
|
13 |
+
This dataset is required by pix2pix-based colorization model ('--model colorization')
|
14 |
+
"""
|
15 |
+
@staticmethod
|
16 |
+
def modify_commandline_options(parser, is_train):
|
17 |
+
"""Add new dataset-specific options, and rewrite default values for existing options.
|
18 |
+
|
19 |
+
Parameters:
|
20 |
+
parser -- original option parser
|
21 |
+
is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.
|
22 |
+
|
23 |
+
Returns:
|
24 |
+
the modified parser.
|
25 |
+
|
26 |
+
By default, the number of channels for input image is 1 (L) and
|
27 |
+
the number of channels for output image is 2 (ab). The direction is from A to B
|
28 |
+
"""
|
29 |
+
parser.set_defaults(input_nc=1, output_nc=2, direction='AtoB')
|
30 |
+
return parser
|
31 |
+
|
32 |
+
def __init__(self, opt):
|
33 |
+
"""Initialize this dataset class.
|
34 |
+
|
35 |
+
Parameters:
|
36 |
+
opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
|
37 |
+
"""
|
38 |
+
BaseDataset.__init__(self, opt)
|
39 |
+
self.dir = os.path.join(opt.dataroot, opt.phase)
|
40 |
+
self.AB_paths = sorted(make_dataset(self.dir, opt.max_dataset_size))
|
41 |
+
assert(opt.input_nc == 1 and opt.output_nc == 2 and opt.direction == 'AtoB')
|
42 |
+
self.transform = get_transform(self.opt, convert=False)
|
43 |
+
|
44 |
+
def __getitem__(self, index):
|
45 |
+
"""Return a data point and its metadata information.
|
46 |
+
|
47 |
+
Parameters:
|
48 |
+
index - - a random integer for data indexing
|
49 |
+
|
50 |
+
Returns a dictionary that contains A, B, A_paths and B_paths
|
51 |
+
A (tensor) - - the L channel of an image
|
52 |
+
B (tensor) - - the ab channels of the same image
|
53 |
+
A_paths (str) - - image paths
|
54 |
+
B_paths (str) - - image paths (same as A_paths)
|
55 |
+
"""
|
56 |
+
path = self.AB_paths[index]
|
57 |
+
im = Image.open(path).convert('RGB')
|
58 |
+
im = self.transform(im)
|
59 |
+
im = np.array(im)
|
60 |
+
lab = color.rgb2lab(im).astype(np.float32)
|
61 |
+
lab_t = transforms.ToTensor()(lab)
|
62 |
+
A = lab_t[[0], ...] / 50.0 - 1.0
|
63 |
+
B = lab_t[[1, 2], ...] / 110.0
|
64 |
+
return {'A': A, 'B': B, 'A_paths': path, 'B_paths': path}
|
65 |
+
|
66 |
+
def __len__(self):
|
67 |
+
"""Return the total number of images in the dataset."""
|
68 |
+
return len(self.AB_paths)
|
data/image_folder.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""A modified image folder class
|
2 |
+
|
3 |
+
We modify the official PyTorch image folder (https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py)
|
4 |
+
so that this class can load images from both current directory and its subdirectories.
|
5 |
+
"""
|
6 |
+
|
7 |
+
import torch.utils.data as data
|
8 |
+
|
9 |
+
from PIL import Image
|
10 |
+
import os
|
11 |
+
|
12 |
+
IMG_EXTENSIONS = [
|
13 |
+
'.jpg', '.JPG', '.jpeg', '.JPEG',
|
14 |
+
'.png', '.PNG', '.ppm', '.PPM', '.bmp', '.BMP',
|
15 |
+
'.tif', '.TIF', '.tiff', '.TIFF',
|
16 |
+
]
|
17 |
+
|
18 |
+
|
19 |
+
def is_image_file(filename):
|
20 |
+
return any(filename.endswith(extension) for extension in IMG_EXTENSIONS)
|
21 |
+
|
22 |
+
|
23 |
+
def make_dataset(dir, max_dataset_size=float("inf")):
|
24 |
+
images = []
|
25 |
+
assert os.path.isdir(dir), '%s is not a valid directory' % dir
|
26 |
+
|
27 |
+
for root, _, fnames in sorted(os.walk(dir)):
|
28 |
+
for fname in fnames:
|
29 |
+
if is_image_file(fname):
|
30 |
+
path = os.path.join(root, fname)
|
31 |
+
images.append(path)
|
32 |
+
return images[:min(max_dataset_size, len(images))]
|
33 |
+
|
34 |
+
|
35 |
+
def default_loader(path):
|
36 |
+
return Image.open(path).convert('RGB')
|
37 |
+
|
38 |
+
|
39 |
+
class ImageFolder(data.Dataset):
|
40 |
+
|
41 |
+
def __init__(self, root, transform=None, return_paths=False,
|
42 |
+
loader=default_loader):
|
43 |
+
imgs = make_dataset(root)
|
44 |
+
if len(imgs) == 0:
|
45 |
+
raise(RuntimeError("Found 0 images in: " + root + "\n"
|
46 |
+
"Supported image extensions are: " + ",".join(IMG_EXTENSIONS)))
|
47 |
+
|
48 |
+
self.root = root
|
49 |
+
self.imgs = imgs
|
50 |
+
self.transform = transform
|
51 |
+
self.return_paths = return_paths
|
52 |
+
self.loader = loader
|
53 |
+
|
54 |
+
def __getitem__(self, index):
|
55 |
+
path = self.imgs[index]
|
56 |
+
img = self.loader(path)
|
57 |
+
if self.transform is not None:
|
58 |
+
img = self.transform(img)
|
59 |
+
if self.return_paths:
|
60 |
+
return img, path
|
61 |
+
else:
|
62 |
+
return img
|
63 |
+
|
64 |
+
def __len__(self):
|
65 |
+
return len(self.imgs)
|
data/single_dataset.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from data.base_dataset import BaseDataset, get_transform
|
2 |
+
from data.image_folder import make_dataset
|
3 |
+
from PIL import Image
|
4 |
+
|
5 |
+
|
6 |
+
class SingleDataset(BaseDataset):
|
7 |
+
"""This dataset class can load a set of images specified by the path --dataroot /path/to/data.
|
8 |
+
|
9 |
+
It can be used for generating CycleGAN results only for one side with the model option '-model test'.
|
10 |
+
"""
|
11 |
+
|
12 |
+
def __init__(self, opt):
|
13 |
+
"""Initialize this dataset class.
|
14 |
+
|
15 |
+
Parameters:
|
16 |
+
opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
|
17 |
+
"""
|
18 |
+
BaseDataset.__init__(self, opt)
|
19 |
+
self.A_paths = sorted(make_dataset(opt.dataroot, opt.max_dataset_size))
|
20 |
+
input_nc = self.opt.output_nc if self.opt.direction == 'BtoA' else self.opt.input_nc
|
21 |
+
self.transform = get_transform(opt, grayscale=(input_nc == 1))
|
22 |
+
|
23 |
+
def __getitem__(self, index):
|
24 |
+
"""Return a data point and its metadata information.
|
25 |
+
|
26 |
+
Parameters:
|
27 |
+
index - - a random integer for data indexing
|
28 |
+
|
29 |
+
Returns a dictionary that contains A and A_paths
|
30 |
+
A(tensor) - - an image in one domain
|
31 |
+
A_paths(str) - - the path of the image
|
32 |
+
"""
|
33 |
+
A_path = self.A_paths[index]
|
34 |
+
A_img = Image.open(A_path).convert('RGB')
|
35 |
+
A = self.transform(A_img)
|
36 |
+
return {'A': A, 'A_paths': A_path}
|
37 |
+
|
38 |
+
def __len__(self):
|
39 |
+
"""Return the total number of images in the dataset."""
|
40 |
+
return len(self.A_paths)
|
data/template_dataset.py
ADDED
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Dataset class template
|
2 |
+
|
3 |
+
This module provides a template for users to implement custom datasets.
|
4 |
+
You can specify '--dataset_mode template' to use this dataset.
|
5 |
+
The class name should be consistent with both the filename and its dataset_mode option.
|
6 |
+
The filename should be <dataset_mode>_dataset.py
|
7 |
+
The class name should be <Dataset_mode>Dataset.py
|
8 |
+
You need to implement the following functions:
|
9 |
+
-- <modify_commandline_options>: Add dataset-specific options and rewrite default values for existing options.
|
10 |
+
-- <__init__>: Initialize this dataset class.
|
11 |
+
-- <__getitem__>: Return a data point and its metadata information.
|
12 |
+
-- <__len__>: Return the number of images.
|
13 |
+
"""
|
14 |
+
from data.base_dataset import BaseDataset, get_transform
|
15 |
+
# from data.image_folder import make_dataset
|
16 |
+
# from PIL import Image
|
17 |
+
|
18 |
+
|
19 |
+
class TemplateDataset(BaseDataset):
|
20 |
+
"""A template dataset class for you to implement custom datasets."""
|
21 |
+
@staticmethod
|
22 |
+
def modify_commandline_options(parser, is_train):
|
23 |
+
"""Add new dataset-specific options, and rewrite default values for existing options.
|
24 |
+
|
25 |
+
Parameters:
|
26 |
+
parser -- original option parser
|
27 |
+
is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.
|
28 |
+
|
29 |
+
Returns:
|
30 |
+
the modified parser.
|
31 |
+
"""
|
32 |
+
parser.add_argument('--new_dataset_option', type=float, default=1.0, help='new dataset option')
|
33 |
+
parser.set_defaults(max_dataset_size=10, new_dataset_option=2.0) # specify dataset-specific default values
|
34 |
+
return parser
|
35 |
+
|
36 |
+
def __init__(self, opt):
|
37 |
+
"""Initialize this dataset class.
|
38 |
+
|
39 |
+
Parameters:
|
40 |
+
opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
|
41 |
+
|
42 |
+
A few things can be done here.
|
43 |
+
- save the options (have been done in BaseDataset)
|
44 |
+
- get image paths and meta information of the dataset.
|
45 |
+
- define the image transformation.
|
46 |
+
"""
|
47 |
+
# save the option and dataset root
|
48 |
+
BaseDataset.__init__(self, opt)
|
49 |
+
# get the image paths of your dataset;
|
50 |
+
self.image_paths = [] # You can call sorted(make_dataset(self.root, opt.max_dataset_size)) to get all the image paths under the directory self.root
|
51 |
+
# define the default transform function. You can use <base_dataset.get_transform>; You can also define your custom transform function
|
52 |
+
self.transform = get_transform(opt)
|
53 |
+
|
54 |
+
def __getitem__(self, index):
|
55 |
+
"""Return a data point and its metadata information.
|
56 |
+
|
57 |
+
Parameters:
|
58 |
+
index -- a random integer for data indexing
|
59 |
+
|
60 |
+
Returns:
|
61 |
+
a dictionary of data with their names. It usually contains the data itself and its metadata information.
|
62 |
+
|
63 |
+
Step 1: get a random image path: e.g., path = self.image_paths[index]
|
64 |
+
Step 2: load your data from the disk: e.g., image = Image.open(path).convert('RGB').
|
65 |
+
Step 3: convert your data to a PyTorch tensor. You can use helpder functions such as self.transform. e.g., data = self.transform(image)
|
66 |
+
Step 4: return a data point as a dictionary.
|
67 |
+
"""
|
68 |
+
path = 'temp' # needs to be a string
|
69 |
+
data_A = None # needs to be a tensor
|
70 |
+
data_B = None # needs to be a tensor
|
71 |
+
return {'data_A': data_A, 'data_B': data_B, 'path': path}
|
72 |
+
|
73 |
+
def __len__(self):
|
74 |
+
"""Return the total number of images."""
|
75 |
+
return len(self.image_paths)
|
data/unaligned_dataset.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from data.base_dataset import BaseDataset, get_transform
|
3 |
+
from data.image_folder import make_dataset
|
4 |
+
from PIL import Image
|
5 |
+
import random
|
6 |
+
|
7 |
+
|
8 |
+
class UnalignedDataset(BaseDataset):
|
9 |
+
"""
|
10 |
+
This dataset class can load unaligned/unpaired datasets.
|
11 |
+
|
12 |
+
It requires two directories to host training images from domain A '/path/to/data/trainA'
|
13 |
+
and from domain B '/path/to/data/trainB' respectively.
|
14 |
+
You can train the model with the dataset flag '--dataroot /path/to/data'.
|
15 |
+
Similarly, you need to prepare two directories:
|
16 |
+
'/path/to/data/testA' and '/path/to/data/testB' during test time.
|
17 |
+
"""
|
18 |
+
|
19 |
+
def __init__(self, opt):
|
20 |
+
"""Initialize this dataset class.
|
21 |
+
|
22 |
+
Parameters:
|
23 |
+
opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
|
24 |
+
"""
|
25 |
+
BaseDataset.__init__(self, opt)
|
26 |
+
self.dir_A = os.path.join(opt.dataroot, opt.phase + 'A') # create a path '/path/to/data/trainA'
|
27 |
+
self.dir_B = os.path.join(opt.dataroot, opt.phase + 'B') # create a path '/path/to/data/trainB'
|
28 |
+
|
29 |
+
self.A_paths = sorted(make_dataset(self.dir_A, opt.max_dataset_size)) # load images from '/path/to/data/trainA'
|
30 |
+
self.B_paths = sorted(make_dataset(self.dir_B, opt.max_dataset_size)) # load images from '/path/to/data/trainB'
|
31 |
+
self.A_size = len(self.A_paths) # get the size of dataset A
|
32 |
+
self.B_size = len(self.B_paths) # get the size of dataset B
|
33 |
+
btoA = self.opt.direction == 'BtoA'
|
34 |
+
input_nc = self.opt.output_nc if btoA else self.opt.input_nc # get the number of channels of input image
|
35 |
+
output_nc = self.opt.input_nc if btoA else self.opt.output_nc # get the number of channels of output image
|
36 |
+
self.transform_A = get_transform(self.opt, grayscale=(input_nc == 1))
|
37 |
+
self.transform_B = get_transform(self.opt, grayscale=(output_nc == 1))
|
38 |
+
|
39 |
+
def __getitem__(self, index):
|
40 |
+
"""Return a data point and its metadata information.
|
41 |
+
|
42 |
+
Parameters:
|
43 |
+
index (int) -- a random integer for data indexing
|
44 |
+
|
45 |
+
Returns a dictionary that contains A, B, A_paths and B_paths
|
46 |
+
A (tensor) -- an image in the input domain
|
47 |
+
B (tensor) -- its corresponding image in the target domain
|
48 |
+
A_paths (str) -- image paths
|
49 |
+
B_paths (str) -- image paths
|
50 |
+
"""
|
51 |
+
A_path = self.A_paths[index % self.A_size] # make sure index is within then range
|
52 |
+
if self.opt.serial_batches: # make sure index is within then range
|
53 |
+
index_B = index % self.B_size
|
54 |
+
else: # randomize the index for domain B to avoid fixed pairs.
|
55 |
+
index_B = random.randint(0, self.B_size - 1)
|
56 |
+
B_path = self.B_paths[index_B]
|
57 |
+
A_img = Image.open(A_path).convert('RGB')
|
58 |
+
B_img = Image.open(B_path).convert('RGB')
|
59 |
+
# apply image transformation
|
60 |
+
A = self.transform_A(A_img)
|
61 |
+
B = self.transform_B(B_img)
|
62 |
+
|
63 |
+
return {'A': A, 'B': B, 'A_paths': A_path, 'B_paths': B_path}
|
64 |
+
|
65 |
+
def __len__(self):
|
66 |
+
"""Return the total number of images in the dataset.
|
67 |
+
|
68 |
+
As we have two datasets with potentially different number of images,
|
69 |
+
we take a maximum of
|
70 |
+
"""
|
71 |
+
return max(self.A_size, self.B_size)
|
docs/Dockerfile
ADDED
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FROM nvidia/cuda:10.1-base
|
2 |
+
|
3 |
+
#Nvidia Public GPG Key
|
4 |
+
RUN apt-key adv --fetch-keys https://developer.download.nvidia.com/compute/cuda/repos/ubuntu1804/x86_64/3bf863cc.pub
|
5 |
+
|
6 |
+
RUN apt update && apt install -y wget unzip curl bzip2 git
|
7 |
+
RUN curl -LO http://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh
|
8 |
+
RUN bash Miniconda3-latest-Linux-x86_64.sh -p /miniconda -b
|
9 |
+
RUN rm Miniconda3-latest-Linux-x86_64.sh
|
10 |
+
ENV PATH=/miniconda/bin:${PATH}
|
11 |
+
RUN conda update -y conda
|
12 |
+
|
13 |
+
RUN conda install -y pytorch torchvision -c pytorch
|
14 |
+
RUN mkdir /workspace/ && cd /workspace/ && git clone https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix.git && cd pytorch-CycleGAN-and-pix2pix && pip install -r requirements.txt
|
15 |
+
|
16 |
+
WORKDIR /workspace
|
docs/README_es.md
ADDED
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<img src='https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/raw/master/imgs/horse2zebra.gif' align="right" width=384>
|
2 |
+
|
3 |
+
<br><br><br>
|
4 |
+
|
5 |
+
# CycleGAN y pix2pix en PyTorch
|
6 |
+
|
7 |
+
Implementacion en PyTorch de Unpaired Image-to-Image Translation.
|
8 |
+
|
9 |
+
Este codigo fue escrito por [Jun-Yan Zhu](https://github.com/junyanz) y [Taesung Park](https://github.com/taesung), y con ayuda de [Tongzhou Wang](https://ssnl.github.io/).
|
10 |
+
|
11 |
+
Esta implementacion de PyTorch produce resultados comparables o mejores que nuestros original software de Torch. Si te gustaria producir los mismos resultados que en documento oficial, echa un vistazo al codigo original [CycleGAN Torch](https://github.com/junyanz/CycleGAN) y [pix2pix Torch](https://github.com/phillipi/pix2pix)
|
12 |
+
|
13 |
+
**Aviso**: El software actual funciona correctamente en PyTorch 0.41+. Para soporte en PyTorch 0.1-0.3: [branch](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/tree/pytorch0.3.1).
|
14 |
+
|
15 |
+
Puede encontrar información útil en [training/test tips](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/tips.md) y [preguntas frecuentes](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/qa.md). Para implementar modelos y conjuntos de datos personalizados, consulte nuestro [templates](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/README_es.md#modelo-y-dataset-personalizado). Para ayudar a los usuarios a comprender y adaptar mejor nuestra base de código, proporcionamos un [overview](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/overview.md) de la estructura de código de este repositorio.
|
16 |
+
|
17 |
+
**CycleGAN: [Proyecto](https://junyanz.github.io/CycleGAN/) | [PDF](https://arxiv.org/pdf/1703.10593.pdf) | [Torch](https://github.com/junyanz/CycleGAN) |
|
18 |
+
[Guia de Tensorflow Core](https://www.tensorflow.org/tutorials/generative/cyclegan) | [PyTorch Colab](https://colab.research.google.com/github/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/CycleGAN.ipynb)**
|
19 |
+
|
20 |
+
<img src="https://junyanz.github.io/CycleGAN/images/teaser_high_res.jpg" width="800"/>
|
21 |
+
|
22 |
+
**Pix2pix: [Proyeto](https://phillipi.github.io/pix2pix/) | [PDF](https://arxiv.org/pdf/1611.07004.pdf) | [Torch](https://github.com/phillipi/pix2pix) |
|
23 |
+
[Guia de Tensorflow Core](https://www.tensorflow.org/tutorials/generative/cyclegan) | [PyTorch Colab](https://colab.research.google.com/github/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/pix2pix.ipynb)**
|
24 |
+
|
25 |
+
<img src="https://phillipi.github.io/pix2pix/images/teaser_v3.png" width="800px"/>
|
26 |
+
|
27 |
+
|
28 |
+
**[EdgesCats Demo](https://affinelayer.com/pixsrv/) | [pix2pix-tensorflow](https://github.com/affinelayer/pix2pix-tensorflow) | por [Christopher Hesse](https://twitter.com/christophrhesse)**
|
29 |
+
|
30 |
+
<img src='https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/imgs/edges2cats.jpg' width="400px"/>
|
31 |
+
|
32 |
+
Si usa este código para su investigación, cite:
|
33 |
+
|
34 |
+
Unpaired Image-to-Image Translation usando Cycle-Consistent Adversarial Networks.<br>
|
35 |
+
[Jun-Yan Zhu](https://www.cs.cmu.edu/~junyanz/)\*, [Taesung Park](https://taesung.me/)\*, [Phillip Isola](https://people.eecs.berkeley.edu/~isola/), [Alexei A. Efros](https://people.eecs.berkeley.edu/~efros). In ICCV 2017. (* contribucion igualitaria) [[Bibtex]](https://junyanz.github.io/CycleGAN/CycleGAN.txt)
|
36 |
+
|
37 |
+
|
38 |
+
Image-to-Image Translation usando Conditional Adversarial Networks.<br>
|
39 |
+
[Phillip Isola](https://people.eecs.berkeley.edu/~isola), [Jun-Yan Zhu](https://www.cs.cmu.edu/~junyanz/), [Tinghui Zhou](https://people.eecs.berkeley.edu/~tinghuiz), [Alexei A. Efros](https://people.eecs.berkeley.edu/~efros). In CVPR 2017. [[Bibtex]](https://www.cs.cmu.edu/~junyanz/projects/pix2pix/pix2pix.bib)
|
40 |
+
|
41 |
+
## Charlas y curso
|
42 |
+
Presentacion en PowerPoint de Pix2pix: [keynote](http://efrosgans.eecs.berkeley.edu/CVPR18_slides/pix2pix.key) | [pdf](http://efrosgans.eecs.berkeley.edu/CVPR18_slides/pix2pix.pdf),
|
43 |
+
Presentacion en PowerPoint de CycleGAN: [pptx](http://efrosgans.eecs.berkeley.edu/CVPR18_slides/CycleGAN.pptx) | [pdf](http://efrosgans.eecs.berkeley.edu/CVPR18_slides/CycleGAN.pdf)
|
44 |
+
|
45 |
+
Asignación del curso CycleGAN [codigo](http://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/assignments/a4-code.zip) y [handout](http://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/assignments/a4-handout.pdf) diseñado por el Prof. [Roger Grosse](http://www.cs.toronto.edu/~rgrosse/) for [CSC321](http://www.cs.toronto.edu/~rgrosse/courses/csc321_2018/) "Intro to Neural Networks and Machine Learning" en la universidad de Toronto. Póngase en contacto con el instructor si desea adoptarlo en su curso.
|
46 |
+
|
47 |
+
## Colab Notebook
|
48 |
+
TensorFlow Core CycleGAN Tutorial: [Google Colab](https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/generative/cyclegan.ipynb) | [Codigo](https://github.com/tensorflow/docs/blob/master/site/en/tutorials/generative/cyclegan.ipynb)
|
49 |
+
|
50 |
+
Guia de TensorFlow Core pix2pix : [Google Colab](https://colab.research.google.com/github/tensorflow/docs/blob/master/site/en/tutorials/generative/pix2pix.ipynb) | [Codigo](https://github.com/tensorflow/docs/blob/master/site/en/tutorials/generative/pix2pix.ipynb)
|
51 |
+
|
52 |
+
PyTorch Colab notebook: [CycleGAN](https://colab.research.google.com/github/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/CycleGAN.ipynb) y [pix2pix](https://colab.research.google.com/github/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/pix2pix.ipynb)
|
53 |
+
|
54 |
+
## Otras implementaciones
|
55 |
+
### CycleGAN
|
56 |
+
<p><a href="https://github.com/leehomyc/cyclegan-1"> [Tensorflow]</a> (por Harry Yang),
|
57 |
+
<a href="https://github.com/architrathore/CycleGAN/">[Tensorflow]</a> (por Archit Rathore),
|
58 |
+
<a href="https://github.com/vanhuyz/CycleGAN-TensorFlow">[Tensorflow]</a> (por Van Huy),
|
59 |
+
<a href="https://github.com/XHUJOY/CycleGAN-tensorflow">[Tensorflow]</a> (por Xiaowei Hu),
|
60 |
+
<a href="https://github.com/LynnHo/CycleGAN-Tensorflow-Simple"> [Tensorflow-simple]</a> (por Zhenliang He),
|
61 |
+
<a href="https://github.com/luoxier/CycleGAN_Tensorlayer"> [TensorLayer]</a> (por luoxier),
|
62 |
+
<a href="https://github.com/Aixile/chainer-cyclegan">[Chainer]</a> (por Yanghua Jin),
|
63 |
+
<a href="https://github.com/yunjey/mnist-svhn-transfer">[Minimal PyTorch]</a> (por yunjey),
|
64 |
+
<a href="https://github.com/Ldpe2G/DeepLearningForFun/tree/master/Mxnet-Scala/CycleGAN">[Mxnet]</a> (por Ldpe2G),
|
65 |
+
<a href="https://github.com/tjwei/GANotebooks">[lasagne/Keras]</a> (por tjwei),
|
66 |
+
<a href="https://github.com/simontomaskarlsson/CycleGAN-Keras">[Keras]</a> (por Simon Karlsson)
|
67 |
+
</p>
|
68 |
+
</ul>
|
69 |
+
|
70 |
+
### pix2pix
|
71 |
+
<p><a href="https://github.com/affinelayer/pix2pix-tensorflow"> [Tensorflow]</a> (por Christopher Hesse),
|
72 |
+
<a href="https://github.com/Eyyub/tensorflow-pix2pix">[Tensorflow]</a> (por Eyyüb Sariu),
|
73 |
+
<a href="https://github.com/datitran/face2face-demo"> [Tensorflow (face2face)]</a> (por Dat Tran),
|
74 |
+
<a href="https://github.com/awjuliani/Pix2Pix-Film"> [Tensorflow (film)]</a> (por Arthur Juliani),
|
75 |
+
<a href="https://github.com/kaonashi-tyc/zi2zi">[Tensorflow (zi2zi)]</a> (por Yuchen Tian),
|
76 |
+
<a href="https://github.com/pfnet-research/chainer-pix2pix">[Chainer]</a> (por mattya),
|
77 |
+
<a href="https://github.com/tjwei/GANotebooks">[tf/torch/keras/lasagne]</a> (por tjwei),
|
78 |
+
<a href="https://github.com/taey16/pix2pixBEGAN.pytorch">[Pytorch]</a> (por taey16)
|
79 |
+
</p>
|
80 |
+
</ul>
|
81 |
+
|
82 |
+
## Requerimientos
|
83 |
+
- Linux o macOS
|
84 |
+
- Python 3
|
85 |
+
- CPU o NVIDIA GPU usando CUDA CuDNN
|
86 |
+
|
87 |
+
## Inicio
|
88 |
+
### Instalación
|
89 |
+
|
90 |
+
- Clone este repositorio:
|
91 |
+
```bash
|
92 |
+
git clone https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix
|
93 |
+
cd pytorch-CycleGAN-and-pix2pix
|
94 |
+
```
|
95 |
+
|
96 |
+
- Instale [PyTorch](http://pytorch.org) 0.4+ y sus otras dependencias (e.g., torchvision, [visdom](https://github.com/facebookresearch/visdom) y [dominate](https://github.com/Knio/dominate)).
|
97 |
+
- Para uso de pip, por favor escriba el comando `pip install -r requirements.txt`.
|
98 |
+
- Para uso de Conda, proporcionamos un script de instalación `./scripts/conda_deps.sh`. De forma alterna, puede crear un nuevo entorno Conda usando `conda env create -f environment.yml`.
|
99 |
+
- Para uso de Docker, Proporcionamos la imagen Docker y el archivo Docker preconstruidos. Por favor, consulte nuestra página
|
100 |
+
[Docker](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/docker.md).
|
101 |
+
|
102 |
+
### CycleGAN entreanimiento/test
|
103 |
+
- Descargar el dataset de CycleGAN (e.g. maps):
|
104 |
+
```bash
|
105 |
+
bash ./datasets/download_cyclegan_dataset.sh maps
|
106 |
+
```
|
107 |
+
- Para ver los resultados del entrenamiento y las gráficas de pérdidas, `python -m visdom.server` y haga clic en la URL
|
108 |
+
http://localhost:8097.
|
109 |
+
- Entrenar el modelo:
|
110 |
+
```bash
|
111 |
+
#!./scripts/train_cyclegan.sh
|
112 |
+
python train.py --dataroot ./datasets/maps --name maps_cyclegan --model cycle_gan
|
113 |
+
```
|
114 |
+
Para ver más resultados intermedios, consulte `./checkpoints/maps_cyclegan/web/index.html`.
|
115 |
+
- Pruebe el modelo:
|
116 |
+
```bash
|
117 |
+
#!./scripts/test_cyclegan.sh
|
118 |
+
python test.py --dataroot ./datasets/maps --name maps_cyclegan --model cycle_gan
|
119 |
+
```
|
120 |
+
-Los resultados de la prueba se guardarán en un archivo html aquí: `./results/maps_cyclegan/latest_test/index.html`.
|
121 |
+
|
122 |
+
### pix2pix entrenamiento/test
|
123 |
+
- Descargue el dataset de pix2pix (e.g.[facades](http://cmp.felk.cvut.cz/~tylecr1/facade/)):
|
124 |
+
```bash
|
125 |
+
bash ./datasets/download_pix2pix_dataset.sh facades
|
126 |
+
```
|
127 |
+
- Para ver los resultados del entrenamiento y las gráficas de pérdidas `python -m visdom.server`, haga clic en la URL http://localhost:8097.
|
128 |
+
- Para entrenar el modelo:
|
129 |
+
```bash
|
130 |
+
#!./scripts/train_pix2pix.sh
|
131 |
+
python train.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --direction BtoA
|
132 |
+
```
|
133 |
+
Para ver más resultados intermedios, consulte `./checkpoints/facades_pix2pix/web/index.html`.
|
134 |
+
|
135 |
+
- Pruebe el modelo (`bash ./scripts/test_pix2pix.sh`):
|
136 |
+
```bash
|
137 |
+
#!./scripts/test_pix2pix.sh
|
138 |
+
python test.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --direction BtoA
|
139 |
+
```
|
140 |
+
- Los resultados de la prueba se guardarán en un archivo html aquí: `./results/facades_pix2pix/test_latest/index.html`. Puede encontrar más scripts en `scripts` directory.
|
141 |
+
- Para entrenar y probar modelos de colorización basados en pix2pix, agregue la linea `--model colorization` y `--dataset_mode colorization`. Para más detalles de nuestro entrenamiento [tips](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/tips.md#notes-on-colorization).
|
142 |
+
|
143 |
+
### Aplicar un modelo pre-entrenado (CycleGAN)
|
144 |
+
- Puedes descargar un modelo previamente entrenado (e.g. horse2zebra) con el siguiente script:
|
145 |
+
```bash
|
146 |
+
bash ./scripts/download_cyclegan_model.sh horse2zebra
|
147 |
+
```
|
148 |
+
- El modelo pre-entrenado se guarda en `./checkpoints/{name}_pretrained/latest_net_G.pth`. Revise [aqui](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/scripts/download_cyclegan_model.sh#L3) para todos los modelos CycleGAN disponibles.
|
149 |
+
|
150 |
+
- Para probar el modelo, también debe descargar el dataset horse2zebra:
|
151 |
+
```bash
|
152 |
+
bash ./datasets/download_cyclegan_dataset.sh horse2zebra
|
153 |
+
```
|
154 |
+
|
155 |
+
- Luego genere los resultados usando:
|
156 |
+
```bash
|
157 |
+
python test.py --dataroot datasets/horse2zebra/testA --name horse2zebra_pretrained --model test --no_dropout
|
158 |
+
```
|
159 |
+
- La opcion `--model test` ise usa para generar resultados de CycleGAN de un solo lado. Esta opción configurará automáticamente
|
160 |
+
`--dataset_mode single`, carga solo las imágenes de un conjunto. Por el contrario, el uso de `--model cycle_gan` requiere cargar y generar resultados en ambas direcciones, lo que a veces es innecesario. Los resultados se guardarán en `./results/`. Use `--results_dir {directory_path_to_save_result}` para especificar el directorio de resultados.
|
161 |
+
|
162 |
+
- Para sus propios experimentos, es posible que desee especificar `--netG`, `--norm`, `--no_dropout` para que coincida con la arquitectura del generador del modelo entrenado.
|
163 |
+
|
164 |
+
### Aplicar un modelo pre-entrenado (pix2pix)
|
165 |
+
Descargue un modelo pre-entrenado con `./scripts/download_pix2pix_model.sh`.
|
166 |
+
|
167 |
+
- Revise [aqui](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/scripts/download_pix2pix_model.sh#L3) para todos los modelos pix2pix disponibles. Por ejemplo, si desea descargar el modelo label2photo en el dataset:
|
168 |
+
```bash
|
169 |
+
bash ./scripts/download_pix2pix_model.sh facades_label2photo
|
170 |
+
```
|
171 |
+
- Descarga el dataset facades de pix2pix:
|
172 |
+
```bash
|
173 |
+
bash ./datasets/download_pix2pix_dataset.sh facades
|
174 |
+
```
|
175 |
+
- Luego genere los resultados usando:
|
176 |
+
```bash
|
177 |
+
python test.py --dataroot ./datasets/facades/ --direction BtoA --model pix2pix --name facades_label2photo_pretrained
|
178 |
+
```
|
179 |
+
- Tenga en cuenta que `--direction BtoA` como Facades dataset's, son direcciones A o B para etiquetado de fotos.
|
180 |
+
|
181 |
+
- Si desea aplicar un modelo previamente entrenado a una colección de imágenes de entrada (en lugar de pares de imágenes), use la opcion `--model test`. Vea `./scripts/test_single.sh` obre cómo aplicar un modelo a Facade label maps (almacenados en el directorio `facades/testB`).
|
182 |
+
|
183 |
+
- Vea una lista de los modelos disponibles actualmente en `./scripts/download_pix2pix_model.sh`
|
184 |
+
|
185 |
+
## [Docker](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/docker.md)
|
186 |
+
Proporcionamos la imagen Docker y el archivo Docker preconstruidos que pueden ejecutar este repositorio de código. Ver [docker](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/docker.md).
|
187 |
+
|
188 |
+
## [Datasets](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/datasets.md)
|
189 |
+
Descargue los conjuntos de datos pix2pix / CycleGAN y cree sus propios conjuntos de datos.
|
190 |
+
|
191 |
+
## [Entretanimiento/Test Tips](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/tips.md)
|
192 |
+
Las mejores prácticas para entrenar y probar sus modelos.
|
193 |
+
|
194 |
+
## [Preguntas frecuentes](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/qa.md)
|
195 |
+
Antes de publicar una nueva pregunta, primero mire las preguntas y respuestas anteriores y los problemas existentes de GitHub.
|
196 |
+
|
197 |
+
## Modelo y Dataset personalizado
|
198 |
+
Si planea implementar modelos y conjuntos de datos personalizados para sus nuevas aplicaciones, proporcionamos un conjunto de datos [template](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/data/template_dataset.py) y un modelo [template](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/template_model.py) como punto de partida.
|
199 |
+
|
200 |
+
|
201 |
+
## [Estructura de codigo](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/overview.md)
|
202 |
+
Para ayudar a los usuarios a comprender mejor y usar nuestro código, presentamos brevemente la funcionalidad e implementación de cada paquete y cada módulo.
|
203 |
+
|
204 |
+
## Solicitud de Pull
|
205 |
+
Siempre puede contribuir a este repositorio enviando un [pull request](https://help.github.com/articles/about-pull-requests/).
|
206 |
+
Por favor ejecute `flake8 --ignore E501 .` y `python ./scripts/test_before_push.py` antes de realizar un Pull en el código, asegure de también actualizar la estructura del código [overview](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/overview.md) en consecuencia si agrega o elimina archivos.
|
207 |
+
|
208 |
+
|
209 |
+
## Citación
|
210 |
+
Si utiliza este código para su investigación, cite nuestros documentos.
|
211 |
+
```
|
212 |
+
@inproceedings{CycleGAN2017,
|
213 |
+
title={Unpaired Image-to-Image Translation using Cycle-Consistent Adversarial Networkss},
|
214 |
+
author={Zhu, Jun-Yan and Park, Taesung and Isola, Phillip and Efros, Alexei A},
|
215 |
+
booktitle={Computer Vision (ICCV), 2017 IEEE International Conference on},
|
216 |
+
year={2017}
|
217 |
+
}
|
218 |
+
|
219 |
+
|
220 |
+
@inproceedings{isola2017image,
|
221 |
+
title={Image-to-Image Translation with Conditional Adversarial Networks},
|
222 |
+
author={Isola, Phillip and Zhu, Jun-Yan and Zhou, Tinghui and Efros, Alexei A},
|
223 |
+
booktitle={Computer Vision and Pattern Recognition (CVPR), 2017 IEEE Conference on},
|
224 |
+
year={2017}
|
225 |
+
}
|
226 |
+
```
|
227 |
+
|
228 |
+
## Proyectos relacionados
|
229 |
+
**[CycleGAN-Torch](https://github.com/junyanz/CycleGAN) |
|
230 |
+
[pix2pix-Torch](https://github.com/phillipi/pix2pix) | [pix2pixHD](https://github.com/NVIDIA/pix2pixHD)|
|
231 |
+
[BicycleGAN](https://github.com/junyanz/BicycleGAN) | [vid2vid](https://tcwang0509.github.io/vid2vid/) | [SPADE/GauGAN](https://github.com/NVlabs/SPADE)**<br>
|
232 |
+
**[iGAN](https://github.com/junyanz/iGAN) | [GAN Dissection](https://github.com/CSAILVision/GANDissect) | [GAN Paint](http://ganpaint.io/)**
|
233 |
+
|
234 |
+
## Cat Paper Collection
|
235 |
+
Si amas a los gatos y te encanta leer gráficos geniales, computer vision y documentos de aprendizaje, echa un vistazo a Cat Paper [Collection](https://github.com/junyanz/CatPapers).
|
236 |
+
|
237 |
+
## Agradecimientos
|
238 |
+
Nuestro código fue inspirado en [pytorch-DCGAN](https://github.com/pytorch/examples/tree/master/dcgan).
|
docs/datasets.md
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
|
3 |
+
### CycleGAN Datasets
|
4 |
+
Download the CycleGAN datasets using the following script. Some of the datasets are collected by other researchers. Please cite their papers if you use the data.
|
5 |
+
```bash
|
6 |
+
bash ./datasets/download_cyclegan_dataset.sh dataset_name
|
7 |
+
```
|
8 |
+
- `facades`: 400 images from the [CMP Facades dataset](http://cmp.felk.cvut.cz/~tylecr1/facade). [[Citation](../datasets/bibtex/facades.tex)]
|
9 |
+
- `cityscapes`: 2975 images from the [Cityscapes training set](https://www.cityscapes-dataset.com). [[Citation](../datasets/bibtex/cityscapes.tex)]. Note: Due to license issue, we cannot directly provide the Cityscapes dataset. Please download the Cityscapes dataset from [https://cityscapes-dataset.com](https://cityscapes-dataset.com) and use the script `./datasets/prepare_cityscapes_dataset.py`.
|
10 |
+
- `maps`: 1096 training images scraped from Google Maps.
|
11 |
+
- `horse2zebra`: 939 horse images and 1177 zebra images downloaded from [ImageNet](http://www.image-net.org) using keywords `wild horse` and `zebra`
|
12 |
+
- `apple2orange`: 996 apple images and 1020 orange images downloaded from [ImageNet](http://www.image-net.org) using keywords `apple` and `navel orange`.
|
13 |
+
- `summer2winter_yosemite`: 1273 summer Yosemite images and 854 winter Yosemite images were downloaded using Flickr API. See more details in our paper.
|
14 |
+
- `monet2photo`, `vangogh2photo`, `ukiyoe2photo`, `cezanne2photo`: The art images were downloaded from [Wikiart](https://www.wikiart.org/). The real photos are downloaded from Flickr using the combination of the tags *landscape* and *landscapephotography*. The training set size of each class is Monet:1074, Cezanne:584, Van Gogh:401, Ukiyo-e:1433, Photographs:6853.
|
15 |
+
- `iphone2dslr_flower`: both classes of images were downlaoded from Flickr. The training set size of each class is iPhone:1813, DSLR:3316. See more details in our paper.
|
16 |
+
|
17 |
+
To train a model on your own datasets, you need to create a data folder with two subdirectories `trainA` and `trainB` that contain images from domain A and B. You can test your model on your training set by setting `--phase train` in `test.py`. You can also create subdirectories `testA` and `testB` if you have test data.
|
18 |
+
|
19 |
+
You should **not** expect our method to work on just any random combination of input and output datasets (e.g. `cats<->keyboards`). From our experiments, we find it works better if two datasets share similar visual content. For example, `landscape painting<->landscape photographs` works much better than `portrait painting <-> landscape photographs`. `zebras<->horses` achieves compelling results while `cats<->dogs` completely fails.
|
20 |
+
|
21 |
+
### pix2pix datasets
|
22 |
+
Download the pix2pix datasets using the following script. Some of the datasets are collected by other researchers. Please cite their papers if you use the data.
|
23 |
+
```bash
|
24 |
+
bash ./datasets/download_pix2pix_dataset.sh dataset_name
|
25 |
+
```
|
26 |
+
- `facades`: 400 images from [CMP Facades dataset](http://cmp.felk.cvut.cz/~tylecr1/facade). [[Citation](../datasets/bibtex/facades.tex)]
|
27 |
+
- `cityscapes`: 2975 images from the [Cityscapes training set](https://www.cityscapes-dataset.com). [[Citation](../datasets/bibtex/cityscapes.tex)]
|
28 |
+
- `maps`: 1096 training images scraped from Google Maps
|
29 |
+
- `edges2shoes`: 50k training images from [UT Zappos50K dataset](http://vision.cs.utexas.edu/projects/finegrained/utzap50k). Edges are computed by [HED](https://github.com/s9xie/hed) edge detector + post-processing. [[Citation](datasets/bibtex/shoes.tex)]
|
30 |
+
- `edges2handbags`: 137K Amazon Handbag images from [iGAN project](https://github.com/junyanz/iGAN). Edges are computed by [HED](https://github.com/s9xie/hed) edge detector + post-processing. [[Citation](datasets/bibtex/handbags.tex)]
|
31 |
+
- `night2day`: around 20K natural scene images from [Transient Attributes dataset](http://transattr.cs.brown.edu/) [[Citation](datasets/bibtex/transattr.tex)]. To train a `day2night` pix2pix model, you need to add `--direction BtoA`.
|
32 |
+
|
33 |
+
We provide a python script to generate pix2pix training data in the form of pairs of images {A,B}, where A and B are two different depictions of the same underlying scene. For example, these might be pairs {label map, photo} or {bw image, color image}. Then we can learn to translate A to B or B to A:
|
34 |
+
|
35 |
+
Create folder `/path/to/data` with subfolders `A` and `B`. `A` and `B` should each have their own subfolders `train`, `val`, `test`, etc. In `/path/to/data/A/train`, put training images in style A. In `/path/to/data/B/train`, put the corresponding images in style B. Repeat same for other data splits (`val`, `test`, etc).
|
36 |
+
|
37 |
+
Corresponding images in a pair {A,B} must be the same size and have the same filename, e.g., `/path/to/data/A/train/1.jpg` is considered to correspond to `/path/to/data/B/train/1.jpg`.
|
38 |
+
|
39 |
+
Once the data is formatted this way, call:
|
40 |
+
```bash
|
41 |
+
python datasets/combine_A_and_B.py --fold_A /path/to/data/A --fold_B /path/to/data/B --fold_AB /path/to/data
|
42 |
+
```
|
43 |
+
|
44 |
+
This will combine each pair of images (A,B) into a single image file, ready for training.
|
docs/docker.md
ADDED
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Docker image with pytorch-CycleGAN-and-pix2pix
|
2 |
+
|
3 |
+
We provide both Dockerfile and pre-built Docker container that can run this code repo.
|
4 |
+
|
5 |
+
## Prerequisite
|
6 |
+
|
7 |
+
- Install [docker-ce](https://docs.docker.com/install/linux/docker-ce/ubuntu/)
|
8 |
+
- Install [nvidia-docker](https://github.com/NVIDIA/nvidia-docker#quickstart)
|
9 |
+
|
10 |
+
## Running pre-built Dockerfile
|
11 |
+
|
12 |
+
- Pull the pre-built docker file
|
13 |
+
|
14 |
+
```bash
|
15 |
+
docker pull taesungp/pytorch-cyclegan-and-pix2pix
|
16 |
+
```
|
17 |
+
|
18 |
+
- Start an interactive docker session. `-p 8097:8097` option is needed if you want to run `visdom` server on the Docker container.
|
19 |
+
|
20 |
+
```bash
|
21 |
+
nvidia-docker run -it -p 8097:8097 taesungp/pytorch-cyclegan-and-pix2pix
|
22 |
+
```
|
23 |
+
|
24 |
+
- Now you are in the Docker environment. Go to our code repo and start running things.
|
25 |
+
```bash
|
26 |
+
cd /workspace/pytorch-CycleGAN-and-pix2pix
|
27 |
+
bash datasets/download_pix2pix_dataset.sh facades
|
28 |
+
python -m visdom.server &
|
29 |
+
bash scripts/train_pix2pix.sh
|
30 |
+
```
|
31 |
+
|
32 |
+
## Running with Dockerfile
|
33 |
+
|
34 |
+
We also posted the [Dockerfile](Dockerfile). To generate the pre-built file, download the Dockerfile in this directory and run
|
35 |
+
```bash
|
36 |
+
docker build -t [target_tag] .
|
37 |
+
```
|
38 |
+
in the directory that contains the Dockerfile.
|
docs/overview.md
ADDED
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Overview of Code Structure
|
2 |
+
To help users better understand and use our codebase, we briefly overview the functionality and implementation of each package and each module. Please see the documentation in each file for more details. If you have questions, you may find useful information in [training/test tips](tips.md) and [frequently asked questions](qa.md).
|
3 |
+
|
4 |
+
[train.py](../train.py) is a general-purpose training script. It works for various models (with option `--model`: e.g., `pix2pix`, `cyclegan`, `colorization`) and different datasets (with option `--dataset_mode`: e.g., `aligned`, `unaligned`, `single`, `colorization`). See the main [README](.../README.md) and [training/test tips](tips.md) for more details.
|
5 |
+
|
6 |
+
[test.py](../test.py) is a general-purpose test script. Once you have trained your model with `train.py`, you can use this script to test the model. It will load a saved model from `--checkpoints_dir` and save the results to `--results_dir`. See the main [README](.../README.md) and [training/test tips](tips.md) for more details.
|
7 |
+
|
8 |
+
|
9 |
+
[data](../data) directory contains all the modules related to data loading and preprocessing. To add a custom dataset class called `dummy`, you need to add a file called `dummy_dataset.py` and define a subclass `DummyDataset` inherited from `BaseDataset`. You need to implement four functions: `__init__` (initialize the class, you need to first call `BaseDataset.__init__(self, opt)`), `__len__` (return the size of dataset), `__getitem__` (get a data point), and optionally `modify_commandline_options` (add dataset-specific options and set default options). Now you can use the dataset class by specifying flag `--dataset_mode dummy`. See our template dataset [class](../data/template_dataset.py) for an example. Below we explain each file in details.
|
10 |
+
|
11 |
+
* [\_\_init\_\_.py](../data/__init__.py) implements the interface between this package and training and test scripts. `train.py` and `test.py` call `from data import create_dataset` and `dataset = create_dataset(opt)` to create a dataset given the option `opt`.
|
12 |
+
* [base_dataset.py](../data/base_dataset.py) implements an abstract base class ([ABC](https://docs.python.org/3/library/abc.html)) for datasets. It also includes common transformation functions (e.g., `get_transform`, `__scale_width`), which can be later used in subclasses.
|
13 |
+
* [image_folder.py](../data/image_folder.py) implements an image folder class. We modify the official PyTorch image folder [code](https://github.com/pytorch/vision/blob/master/torchvision/datasets/folder.py) so that this class can load images from both the current directory and its subdirectories.
|
14 |
+
* [template_dataset.py](../data/template_dataset.py) provides a dataset template with detailed documentation. Check out this file if you plan to implement your own dataset.
|
15 |
+
* [aligned_dataset.py](../data/aligned_dataset.py) includes a dataset class that can load image pairs. It assumes a single image directory `/path/to/data/train`, which contains image pairs in the form of {A,B}. See [here](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/tips.md#prepare-your-own-datasets-for-pix2pix) on how to prepare aligned datasets. During test time, you need to prepare a directory `/path/to/data/test` as test data.
|
16 |
+
* [unaligned_dataset.py](../data/unaligned_dataset.py) includes a dataset class that can load unaligned/unpaired datasets. It assumes that two directories to host training images from domain A `/path/to/data/trainA` and from domain B `/path/to/data/trainB` respectively. Then you can train the model with the dataset flag `--dataroot /path/to/data`. Similarly, you need to prepare two directories `/path/to/data/testA` and `/path/to/data/testB` during test time.
|
17 |
+
* [single_dataset.py](../data/single_dataset.py) includes a dataset class that can load a set of single images specified by the path `--dataroot /path/to/data`. It can be used for generating CycleGAN results only for one side with the model option `-model test`.
|
18 |
+
* [colorization_dataset.py](../data/colorization_dataset.py) implements a dataset class that can load a set of nature images in RGB, and convert RGB format into (L, ab) pairs in [Lab](https://en.wikipedia.org/wiki/CIELAB_color_space) color space. It is required by pix2pix-based colorization model (`--model colorization`).
|
19 |
+
|
20 |
+
|
21 |
+
[models](../models) directory contains modules related to objective functions, optimizations, and network architectures. To add a custom model class called `dummy`, you need to add a file called `dummy_model.py` and define a subclass `DummyModel` inherited from `BaseModel`. You need to implement four functions: `__init__` (initialize the class; you need to first call `BaseModel.__init__(self, opt)`), `set_input` (unpack data from dataset and apply preprocessing), `forward` (generate intermediate results), `optimize_parameters` (calculate loss, gradients, and update network weights), and optionally `modify_commandline_options` (add model-specific options and set default options). Now you can use the model class by specifying flag `--model dummy`. See our template model [class](../models/template_model.py) for an example. Below we explain each file in details.
|
22 |
+
|
23 |
+
* [\_\_init\_\_.py](../models/__init__.py) implements the interface between this package and training and test scripts. `train.py` and `test.py` call `from models import create_model` and `model = create_model(opt)` to create a model given the option `opt`. You also need to call `model.setup(opt)` to properly initialize the model.
|
24 |
+
* [base_model.py](../models/base_model.py) implements an abstract base class ([ABC](https://docs.python.org/3/library/abc.html)) for models. It also includes commonly used helper functions (e.g., `setup`, `test`, `update_learning_rate`, `save_networks`, `load_networks`), which can be later used in subclasses.
|
25 |
+
* [template_model.py](../models/template_model.py) provides a model template with detailed documentation. Check out this file if you plan to implement your own model.
|
26 |
+
* [pix2pix_model.py](../models/pix2pix_model.py) implements the pix2pix [model](https://phillipi.github.io/pix2pix/), for learning a mapping from input images to output images given paired data. The model training requires `--dataset_mode aligned` dataset. By default, it uses a `--netG unet256` [U-Net](https://arxiv.org/pdf/1505.04597.pdf) generator, a `--netD basic` discriminator (PatchGAN), and a `--gan_mode vanilla` GAN loss (standard cross-entropy objective).
|
27 |
+
* [colorization_model.py](../models/colorization_model.py) implements a subclass of `Pix2PixModel` for image colorization (black & white image to colorful image). The model training requires `-dataset_model colorization` dataset. It trains a pix2pix model, mapping from L channel to ab channels in [Lab](https://en.wikipedia.org/wiki/CIELAB_color_space) color space. By default, the `colorization` dataset will automatically set `--input_nc 1` and `--output_nc 2`.
|
28 |
+
* [cycle_gan_model.py](../models/cycle_gan_model.py) implements the CycleGAN [model](https://junyanz.github.io/CycleGAN/), for learning image-to-image translation without paired data. The model training requires `--dataset_mode unaligned` dataset. By default, it uses a `--netG resnet_9blocks` ResNet generator, a `--netD basic` discriminator (PatchGAN introduced by pix2pix), and a least-square GANs [objective](https://arxiv.org/abs/1611.04076) (`--gan_mode lsgan`).
|
29 |
+
* [networks.py](../models/networks.py) module implements network architectures (both generators and discriminators), as well as normalization layers, initialization methods, optimization scheduler (i.e., learning rate policy), and GAN objective function (`vanilla`, `lsgan`, `wgangp`).
|
30 |
+
* [test_model.py](../models/test_model.py) implements a model that can be used to generate CycleGAN results for only one direction. This model will automatically set `--dataset_mode single`, which only loads the images from one set. See the test [instruction](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix#apply-a-pre-trained-model-cyclegan) for more details.
|
31 |
+
|
32 |
+
[options](../options) directory includes our option modules: training options, test options, and basic options (used in both training and test). `TrainOptions` and `TestOptions` are both subclasses of `BaseOptions`. They will reuse the options defined in `BaseOptions`.
|
33 |
+
* [\_\_init\_\_.py](../options/__init__.py) is required to make Python treat the directory `options` as containing packages,
|
34 |
+
* [base_options.py](../options/base_options.py) includes options that are used in both training and test. It also implements a few helper functions such as parsing, printing, and saving the options. It also gathers additional options defined in `modify_commandline_options` functions in both dataset class and model class.
|
35 |
+
* [train_options.py](../options/train_options.py) includes options that are only used during training time.
|
36 |
+
* [test_options.py](../options/test_options.py) includes options that are only used during test time.
|
37 |
+
|
38 |
+
|
39 |
+
[util](../util) directory includes a miscellaneous collection of useful helper functions.
|
40 |
+
* [\_\_init\_\_.py](../util/__init__.py) is required to make Python treat the directory `util` as containing packages,
|
41 |
+
* [get_data.py](../util/get_data.py) provides a Python script for downloading CycleGAN and pix2pix datasets. Alternatively, You can also use bash scripts such as [download_pix2pix_model.sh](../scripts/download_pix2pix_model.sh) and [download_cyclegan_model.sh](../scripts/download_cyclegan_model.sh).
|
42 |
+
* [html.py](../util/html.py) implements a module that saves images into a single HTML file. It consists of functions such as `add_header` (add a text header to the HTML file), `add_images` (add a row of images to the HTML file), `save` (save the HTML to the disk). It is based on Python library `dominate`, a Python library for creating and manipulating HTML documents using a DOM API.
|
43 |
+
* [image_pool.py](../util/image_pool.py) implements an image buffer that stores previously generated images. This buffer enables us to update discriminators using a history of generated images rather than the ones produced by the latest generators. The original idea was discussed in this [paper](http://openaccess.thecvf.com/content_cvpr_2017/papers/Shrivastava_Learning_From_Simulated_CVPR_2017_paper.pdf). The size of the buffer is controlled by the flag `--pool_size`.
|
44 |
+
* [visualizer.py](../util/visualizer.py) includes several functions that can display/save images and print/save logging information. It uses a Python library `visdom` for display and a Python library `dominate` (wrapped in `HTML`) for creating HTML files with images.
|
45 |
+
* [util.py](../util/util.py) consists of simple helper functions such as `tensor2im` (convert a tensor array to a numpy image array), `diagnose_network` (calculate and print the mean of average absolute value of gradients), and `mkdirs` (create multiple directories).
|
docs/qa.md
ADDED
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Frequently Asked Questions
|
2 |
+
Before you post a new question, please first look at the following Q & A and existing GitHub issues. You may also want to read [Training/Test tips](tips.md) for more suggestions.
|
3 |
+
|
4 |
+
#### Connection Error:HTTPConnectionPool ([#230](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/230), [#24](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/24), [#38](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/38))
|
5 |
+
Similar error messages include “Failed to establish a new connection/Connection refused”.
|
6 |
+
|
7 |
+
Please start the visdom server before starting the training:
|
8 |
+
```bash
|
9 |
+
python -m visdom.server
|
10 |
+
```
|
11 |
+
To install the visdom, you can use the following command:
|
12 |
+
```bash
|
13 |
+
pip install visdom
|
14 |
+
```
|
15 |
+
You can also disable the visdom by setting `--display_id 0`.
|
16 |
+
|
17 |
+
#### My PyTorch errors on CUDA related code.
|
18 |
+
Try to run the following code snippet to make sure that CUDA is working (assuming using PyTorch >= 0.4):
|
19 |
+
```python
|
20 |
+
import torch
|
21 |
+
torch.cuda.init()
|
22 |
+
print(torch.randn(1, device='cuda'))
|
23 |
+
```
|
24 |
+
|
25 |
+
If you met an error, it is likely that your PyTorch build does not work with CUDA, e.g., it is installed from the official MacOS binary, or you have a GPU that is too old and not supported anymore. You may run the the code with CPU using `--gpu_ids -1`.
|
26 |
+
|
27 |
+
#### TypeError: Object of type 'Tensor' is not JSON serializable ([#258](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/258))
|
28 |
+
Similar errors: AttributeError: module 'torch' has no attribute 'device' ([#314](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/314))
|
29 |
+
|
30 |
+
The current code only works with PyTorch 0.4+. An earlier PyTorch version can often cause the above errors.
|
31 |
+
|
32 |
+
#### ValueError: empty range for randrange() ([#390](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/390), [#376](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/376), [#194](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/194))
|
33 |
+
Similar error messages include "ConnectionRefusedError: [Errno 111] Connection refused"
|
34 |
+
|
35 |
+
It is related to the data augmentation step. It often happens when you use `--preprocess crop`. The program will crop random `crop_size x crop_size` patches out of the input training images. But if some of your image sizes (e.g., `256x384`) are smaller than the `crop_size` (e.g., 512), you will get this error. A simple fix will be to use other data augmentation methods such as `resize_and_crop` or `scale_width_and_crop`. Our program will automatically resize the images according to `load_size` before apply `crop_size x crop_size` cropping. Make sure that `load_size >= crop_size`.
|
36 |
+
|
37 |
+
|
38 |
+
#### Can I continue/resume my training? ([#350](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/350), [#275](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/275), [#234](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/234), [#87](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/87))
|
39 |
+
You can use the option `--continue_train`. Also set `--epoch_count` to specify a different starting epoch count. See more discussion in [training/test tips](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/tips.md#trainingtest-tips).
|
40 |
+
|
41 |
+
#### Why does my training loss not converge? ([#335](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/335), [#164](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/164), [#30](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/30))
|
42 |
+
Many GAN losses do not converge (exception: WGAN, WGAN-GP, etc. ) due to the nature of minimax optimization. For DCGAN and LSGAN objective, it is quite normal for the G and D losses to go up and down. It should be fine as long as they do not blow up.
|
43 |
+
|
44 |
+
#### How can I make it work for my own data (e.g., 16-bit png, tiff, hyperspectral images)? ([#309](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/309), [#320](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/), [#202](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/202))
|
45 |
+
The current code only supports RGB and grayscale images. If you would like to train the model on other data types, please follow the following steps:
|
46 |
+
|
47 |
+
- change the parameters `--input_nc` and `--output_nc` to the number of channels in your input/output images.
|
48 |
+
- Write your own custom data loader (It is easy as long as you know how to load your data with python). If you write a new data loader class, you need to change the flag `--dataset_mode` accordingly. Alternatively, you can modify the existing data loader. For aligned datasets, change this [line](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/data/aligned_dataset.py#L41); For unaligned datasets, change these two [lines](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/data/unaligned_dataset.py#L57).
|
49 |
+
|
50 |
+
- If you use visdom and HTML to visualize the results, you may also need to change the visualization code.
|
51 |
+
|
52 |
+
#### Multi-GPU Training ([#327](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/327), [#292](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/292), [#137](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/137), [#35](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/35))
|
53 |
+
You can use Multi-GPU training by setting `--gpu_ids` (e.g., `--gpu_ids 0,1,2,3` for the first four GPUs on your machine.) To fully utilize all the GPUs, you need to increase your batch size. Try `--batch_size 4`, `--batch_size 16`, or even a larger batch_size. Each GPU will process batch_size/#GPUs images. The optimal batch size depends on the number of GPUs you have, GPU memory per GPU, and the resolution of your training images.
|
54 |
+
|
55 |
+
We also recommend that you use the instance normalization for multi-GPU training by setting `--norm instance`. The current batch normalization might not work for multi-GPUs as the batchnorm parameters are not shared across different GPUs. Advanced users can try [synchronized batchnorm](https://github.com/vacancy/Synchronized-BatchNorm-PyTorch).
|
56 |
+
|
57 |
+
|
58 |
+
#### Can I run the model on CPU? ([#310](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/310))
|
59 |
+
Yes, you can set `--gpu_ids -1`. See [training/test tips](tips.md) for more details.
|
60 |
+
|
61 |
+
|
62 |
+
#### Are pre-trained models available? ([#10](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/10))
|
63 |
+
Yes, you can download pretrained models with the bash script `./scripts/download_cyclegan_model.sh`. See [here](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix#apply-a-pre-trained-model-cyclegan) for more details. We are slowly adding more models to the repo.
|
64 |
+
|
65 |
+
#### Out of memory ([#174](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/174))
|
66 |
+
CycleGAN is more memory-intensive than pix2pix as it requires two generators and two discriminators. If you would like to produce high-resolution images, you can do the following.
|
67 |
+
|
68 |
+
- During training, train CycleGAN on cropped images of the training set. Please be careful not to change the aspect ratio or the scale of the original image, as this can lead to the training/test gap. You can usually do this by using `--preprocess crop` option, or `--preprocess scale_width_and_crop`.
|
69 |
+
|
70 |
+
- Then at test time, you can load only one generator to produce the results in a single direction. This greatly saves GPU memory as you are not loading the discriminators and the other generator in the opposite direction. You can probably take the whole image as input. You can do this using `--model test --dataroot [path to the directory that contains your test images (e.g., ./datasets/horse2zebra/trainA)] --model_suffix _A --preprocess none`. You can use either `--preprocess none` or `--preprocess scale_width --crop_size [your_desired_image_width]`. Please see the [model_suffix](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/test_model.py#L16) and [preprocess](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/data/base_dataset.py#L24) for more details.
|
71 |
+
|
72 |
+
#### RuntimeError: Error(s) in loading state_dict ([#812](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/812), [#671](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/671),[#461](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/461), [#296](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/296))
|
73 |
+
If you get the above errors when loading the generator during test time, you probably have used different network configurations for training and test. There are a few things to check: (1) the network architecture `--netG`: you will get an error if you use `--netG unet256` during training, and use `--netG resnet_6blocks` during test. Make sure that the flag is the same. (2) the normalization parameters `--norm`: we use different default `--norm` parameters for `--model cycle_gan`, `--model pix2pix`, and `--model test`. They might be different from the one you used in your training time. Make sure that you add the `--norm` flag in your test code. (3) If you use dropout during training time, make sure that you use the same Dropout setting in your test. Check the flag `--no_dropout`.
|
74 |
+
|
75 |
+
Note that we use different default generators, normalization, and dropout options for different models. The model file can overwrite the default arguments and add new arguments. For example, this [line](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/models/pix2pix_model.py#L32) adds and changes default arguments for pix2pix. For CycleGAN, the default is `--netG resnet_9blocks --no_dropout --norm instance --dataset_mode unaligned`. For pix2pix, the default is `--netG unet_256 --norm batch --dataset_mode aligned`. For model testing with single direction (`--model test`), the default is `--netG resnet_9blocks --norm instance --dataset_mode single`. To make sure that your training and test follow the same setting, you are encouraged to plicitly specify the `--netG`, `--norm`, `--dataset_mode`, and `--no_dropout` (or not) in your script.
|
76 |
+
|
77 |
+
#### NotSupportedError ([#829](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/829))
|
78 |
+
The error message states that `slicing multiple dimensions at the same time isn't supported yet proposals (Tensor): boxes to be encoded`. It is not related to our repo. It is often caused by incompatibility between the `torhvision` version and `pytorch` version. You need to re-intall or upgrade your `torchvision` to be compatible with the `pytorch` version.
|
79 |
+
|
80 |
+
|
81 |
+
#### What is the identity loss? ([#322](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/322), [#373](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/373), [#362](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/pull/362))
|
82 |
+
We use the identity loss for our photo to painting application. The identity loss can regularize the generator to be close to an identity mapping when fed with real samples from the *target* domain. If something already looks like from the target domain, you should preserve the image without making additional changes. The generator trained with this loss will often be more conservative for unknown content. Please see more details in Sec 5.2 ''Photo generation from paintings'' and Figure 12 in the CycleGAN [paper](https://arxiv.org/pdf/1703.10593.pdf). The loss was first proposed in Equation 6 of the prior work [[Taigman et al., 2017]](https://arxiv.org/pdf/1611.02200.pdf).
|
83 |
+
|
84 |
+
#### The color gets inverted from the beginning of training ([#249](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/249))
|
85 |
+
The authors also observe that the generator unnecessarily inverts the color of the input image early in training, and then never learns to undo the inversion. In this case, you can try two things.
|
86 |
+
|
87 |
+
- First, try using identity loss `--lambda_identity 1.0` or `--lambda_identity 0.1`. We observe that the identity loss makes the generator to be more conservative and make fewer unnecessary changes. However, because of this, the change may not be as dramatic.
|
88 |
+
|
89 |
+
- Second, try smaller variance when initializing weights by changing `--init_gain`. We observe that a smaller variance in weight initialization results in less color inversion.
|
90 |
+
|
91 |
+
#### For labels2photo Cityscapes evaluation, why does the pretrained FCN-8s model not work well on the original Cityscapes input images? ([#150](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/150))
|
92 |
+
The model was trained on 256x256 images that are resized/upsampled to 1024x2048, so expected input images to the network are very blurry. The purpose of the resizing was to 1) keep the label maps in the original high resolution untouched and 2) avoid the need to change the standard FCN training code for Cityscapes.
|
93 |
+
|
94 |
+
#### How do I get the `ground-truth` numbers on the labels2photo Cityscapes evaluation? ([#150](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/150))
|
95 |
+
You need to resize the original Cityscapes images to 256x256 before running the evaluation code.
|
96 |
+
|
97 |
+
#### What is a good evaluation metric for CycleGAN? ([#730](https://github.com/pulls), [#716](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/716), [#166](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/166))
|
98 |
+
The evaluation metric highly depends on your specific task and dataset. There is no single metric that works for all the datasets and tasks.
|
99 |
+
|
100 |
+
There are a few popular choices: (1) we often evaluate CycleGAN on paired datasets (e.g., Cityscapes dataset and the meanIOU metric used in the CycleGAN paper), in which the model was trained without pairs. (2) Many researchers have adopted standard GAN metrics such as FID. Note that FID only evaluates the output images, while it ignores the correspondence between output and input. (3) A user study regarding photorealism might be helpful. Please check out the details of a user study in the CycleGAN paper (Section 5.1.1).
|
101 |
+
|
102 |
+
In summary, how to automatically evaluate the results is an open research problem for GANs research. But for many creative applications, the results are subjective and hard to quantify without humans in the loop.
|
103 |
+
|
104 |
+
|
105 |
+
#### What dose the CycleGAN loss look like if training goes well? ([#1096](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/1096), [#1086](ttps://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/1086), [#288](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/288), [#30](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/30))
|
106 |
+
Typically, the cycle-consistency loss and identity loss decrease during training, while GAN losses oscillate. To evaluate the quality of your results, you need to adopt additional evaluation metrics to your training and test images. See the Q & A above.
|
107 |
+
|
108 |
+
|
109 |
+
#### Using resize-conv to reduce checkerboard artifacts ([#190](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/190), [#64](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/64))
|
110 |
+
This Distill [blog](https://distill.pub/2016/deconv-checkerboard/) discussed one of the potential causes of the checkerboard artifacts. You can fix that issue by switching from "deconvolution" to nearest-neighbor upsampling, followed by regular convolution. Here is one implementation provided by [@SsnL](https://github.com/SsnL). You can replace the ConvTranspose2d with the following layers.
|
111 |
+
```python
|
112 |
+
nn.Upsample(scale_factor = 2, mode='bilinear'),
|
113 |
+
nn.ReflectionPad2d(1),
|
114 |
+
nn.Conv2d(ngf * mult, int(ngf * mult / 2), kernel_size=3, stride=1, padding=0),
|
115 |
+
```
|
116 |
+
We have also noticed that sometimes the checkboard artifacts will go away if you train long enough. Maybe you can try training your model a bit longer.
|
117 |
+
|
118 |
+
#### pix2pix/CycleGAN has no random noise z ([#152](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/152))
|
119 |
+
The current pix2pix/CycleGAN model does not take z as input. In both pix2pix and CycleGAN, we tried to add z to the generator: e.g., adding z to a latent state, concatenating with a latent state, applying dropout, etc., but often found the output did not vary significantly as a function of z. Conditional GANs do not need noise as long as the input is sufficiently complex so that the input can kind of play the role of noise. Without noise, the mapping is deterministic.
|
120 |
+
|
121 |
+
Please check out the following papers that show ways of getting z to actually have a substantial effect: e.g., [BicycleGAN](https://github.com/junyanz/BicycleGAN), [AugmentedCycleGAN](https://arxiv.org/abs/1802.10151), [MUNIT](https://arxiv.org/abs/1804.04732), [DRIT](https://arxiv.org/pdf/1808.00948.pdf), etc.
|
122 |
+
|
123 |
+
#### Experiment details (e.g., BW->color) ([#306](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/issues/306))
|
124 |
+
You can find more training details and hyperparameter settings in the appendix of [CycleGAN](https://arxiv.org/abs/1703.10593) and [pix2pix](https://arxiv.org/abs/1611.07004) papers.
|
125 |
+
|
126 |
+
#### Results with [Cycada](https://arxiv.org/pdf/1711.03213.pdf)
|
127 |
+
We generated the [result of translating GTA images to Cityscapes-style images](https://junyanz.github.io/CycleGAN/) using our Torch repo. Our PyTorch and Torch implementation seemed to produce a little bit different results, although we have not measured the FCN score using the PyTorch-trained model. To reproduce the result of Cycada, please use the Torch repo for now.
|
128 |
+
|
129 |
+
#### Loading and using the saved model in your code
|
130 |
+
You can easily consume the model in your code using the below code snippet:
|
131 |
+
|
132 |
+
```python
|
133 |
+
import torch
|
134 |
+
from models.networks import define_G
|
135 |
+
from collections import OrderedDict
|
136 |
+
|
137 |
+
model_dict = torch.load("checkpoints/stars_pix2pix/latest_net_G.pth")
|
138 |
+
new_dict = OrderedDict()
|
139 |
+
for k, v in model_dict.items():
|
140 |
+
# load_state_dict expects keys with prefix 'module.'
|
141 |
+
new_dict["module." + k] = v
|
142 |
+
|
143 |
+
# make sure you pass the correct parameters to the define_G method
|
144 |
+
generator_model = define_G(input_nc=1,output_nc=1,ngf=64,netG="resnet_9blocks",
|
145 |
+
norm="batch",use_dropout=True,init_gain=0.02,gpu_ids=[0])
|
146 |
+
generator_model.load_state_dict(new_dict)
|
147 |
+
```
|
148 |
+
If everything goes well you should see a '\<All keys matched successfully\>' message.
|
docs/tips.md
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## Training/test Tips
|
2 |
+
#### Training/test options
|
3 |
+
Please see `options/train_options.py` and `options/base_options.py` for the training flags; see `options/test_options.py` and `options/base_options.py` for the test flags. There are some model-specific flags as well, which are added in the model files, such as `--lambda_A` option in `model/cycle_gan_model.py`. The default values of these options are also adjusted in the model files.
|
4 |
+
#### CPU/GPU (default `--gpu_ids 0`)
|
5 |
+
Please set`--gpu_ids -1` to use CPU mode; set `--gpu_ids 0,1,2` for multi-GPU mode. You need a large batch size (e.g., `--batch_size 32`) to benefit from multiple GPUs.
|
6 |
+
|
7 |
+
#### Visualization
|
8 |
+
During training, the current results can be viewed using two methods. First, if you set `--display_id` > 0, the results and loss plot will appear on a local graphics web server launched by [visdom](https://github.com/facebookresearch/visdom). To do this, you should have `visdom` installed and a server running by the command `python -m visdom.server`. The default server URL is `http://localhost:8097`. `display_id` corresponds to the window ID that is displayed on the `visdom` server. The `visdom` display functionality is turned on by default. To avoid the extra overhead of communicating with `visdom` set `--display_id -1`. Second, the intermediate results are saved to `[opt.checkpoints_dir]/[opt.name]/web/` as an HTML file. To avoid this, set `--no_html`.
|
9 |
+
|
10 |
+
#### Preprocessing
|
11 |
+
Images can be resized and cropped in different ways using `--preprocess` option. The default option `'resize_and_crop'` resizes the image to be of size `(opt.load_size, opt.load_size)` and does a random crop of size `(opt.crop_size, opt.crop_size)`. `'crop'` skips the resizing step and only performs random cropping. `'scale_width'` resizes the image to have width `opt.crop_size` while keeping the aspect ratio. `'scale_width_and_crop'` first resizes the image to have width `opt.load_size` and then does random cropping of size `(opt.crop_size, opt.crop_size)`. `'none'` tries to skip all these preprocessing steps. However, if the image size is not a multiple of some number depending on the number of downsamplings of the generator, you will get an error because the size of the output image may be different from the size of the input image. Therefore, `'none'` option still tries to adjust the image size to be a multiple of 4. You might need a bigger adjustment if you change the generator architecture. Please see `data/base_dataset.py` do see how all these were implemented.
|
12 |
+
|
13 |
+
#### Fine-tuning/resume training
|
14 |
+
To fine-tune a pre-trained model, or resume the previous training, use the `--continue_train` flag. The program will then load the model based on `epoch`. By default, the program will initialize the epoch count as 1. Set `--epoch_count <int>` to specify a different starting epoch count.
|
15 |
+
|
16 |
+
|
17 |
+
#### Prepare your own datasets for CycleGAN
|
18 |
+
You need to create two directories to host images from domain A `/path/to/data/trainA` and from domain B `/path/to/data/trainB`. Then you can train the model with the dataset flag `--dataroot /path/to/data`. Optionally, you can create hold-out test datasets at `/path/to/data/testA` and `/path/to/data/testB` to test your model on unseen images.
|
19 |
+
|
20 |
+
#### Prepare your own datasets for pix2pix
|
21 |
+
Pix2pix's training requires paired data. We provide a python script to generate training data in the form of pairs of images {A,B}, where A and B are two different depictions of the same underlying scene. For example, these might be pairs {label map, photo} or {bw image, color image}. Then we can learn to translate A to B or B to A:
|
22 |
+
|
23 |
+
Create folder `/path/to/data` with subdirectories `A` and `B`. `A` and `B` should each have their own subdirectories `train`, `val`, `test`, etc. In `/path/to/data/A/train`, put training images in style A. In `/path/to/data/B/train`, put the corresponding images in style B. Repeat same for other data splits (`val`, `test`, etc).
|
24 |
+
|
25 |
+
Corresponding images in a pair {A,B} must be the same size and have the same filename, e.g., `/path/to/data/A/train/1.jpg` is considered to correspond to `/path/to/data/B/train/1.jpg`.
|
26 |
+
|
27 |
+
Once the data is formatted this way, call:
|
28 |
+
```bash
|
29 |
+
python datasets/combine_A_and_B.py --fold_A /path/to/data/A --fold_B /path/to/data/B --fold_AB /path/to/data
|
30 |
+
```
|
31 |
+
|
32 |
+
This will combine each pair of images (A,B) into a single image file, ready for training.
|
33 |
+
|
34 |
+
|
35 |
+
#### About image size
|
36 |
+
Since the generator architecture in CycleGAN involves a series of downsampling / upsampling operations, the size of the input and output image may not match if the input image size is not a multiple of 4. As a result, you may get a runtime error because the L1 identity loss cannot be enforced with images of different size. Therefore, we slightly resize the image to become multiples of 4 even with `--preprocess none` option. For the same reason, `--crop_size` needs to be a multiple of 4.
|
37 |
+
|
38 |
+
#### Training/Testing with high res images
|
39 |
+
CycleGAN is quite memory-intensive as four networks (two generators and two discriminators) need to be loaded on one GPU, so a large image cannot be entirely loaded. In this case, we recommend training with cropped images. For example, to generate 1024px results, you can train with `--preprocess scale_width_and_crop --load_size 1024 --crop_size 360`, and test with `--preprocess scale_width --load_size 1024`. This way makes sure the training and test will be at the same scale. At test time, you can afford higher resolution because you don’t need to load all networks.
|
40 |
+
|
41 |
+
#### Training/Testing with rectangular images
|
42 |
+
Both pix2pix and CycleGAN can work for rectangular images. To make them work, you need to use different preprocessing flags. Let's say that you are working with `360x256` images. During training, you can specify `--preprocess crop` and `--crop_size 256`. This will allow your model to be trained on randomly cropped `256x256` images during training time. During test time, you can apply the model on `360x256` images with the flag `--preprocess none`.
|
43 |
+
|
44 |
+
There are practical restrictions regarding image sizes for each generator architecture. For `unet256`, it only supports images whose width and height are divisible by 256. For `unet128`, the width and height need to be divisible by 128. For `resnet_6blocks` and `resnet_9blocks`, the width and height need to be divisible by 4.
|
45 |
+
|
46 |
+
#### About loss curve
|
47 |
+
Unfortunately, the loss curve does not reveal much information in training GANs, and CycleGAN is no exception. To check whether the training has converged or not, we recommend periodically generating a few samples and looking at them.
|
48 |
+
|
49 |
+
#### About batch size
|
50 |
+
For all experiments in the paper, we set the batch size to be 1. If there is room for memory, you can use higher batch size with batch norm or instance norm. (Note that the default batchnorm does not work well with multi-GPU training. You may consider using [synchronized batchnorm](https://github.com/vacancy/Synchronized-BatchNorm-PyTorch) instead). But please be aware that it can impact the training. In particular, even with Instance Normalization, different batch sizes can lead to different results. Moreover, increasing `--crop_size` may be a good alternative to increasing the batch size.
|
51 |
+
|
52 |
+
|
53 |
+
#### Notes on Colorization
|
54 |
+
No need to run `combine_A_and_B.py` for colorization. Instead, you need to prepare natural images and set `--dataset_mode colorization` and `--model colorization` in the script. The program will automatically convert each RGB image into Lab color space, and create `L -> ab` image pair during the training. Also set `--input_nc 1` and `--output_nc 2`. The training and test directory should be organized as `/your/data/train` and `your/data/test`. See example scripts `scripts/train_colorization.sh` and `scripts/test_colorization` for more details.
|
55 |
+
|
56 |
+
#### Notes on Extracting Edges
|
57 |
+
We provide python and Matlab scripts to extract coarse edges from photos. Run `scripts/edges/batch_hed.py` to compute [HED](https://github.com/s9xie/hed) edges. Run `scripts/edges/PostprocessHED.m` to simplify edges with additional post-processing steps. Check the code documentation for more details.
|
58 |
+
|
59 |
+
#### Evaluating Labels2Photos on Cityscapes
|
60 |
+
We provide scripts for running the evaluation of the Labels2Photos task on the Cityscapes **validation** set. We assume that you have installed `caffe` (and `pycaffe`) in your system. If not, see the [official website](http://caffe.berkeleyvision.org/installation.html) for installation instructions. Once `caffe` is successfully installed, download the pre-trained FCN-8s semantic segmentation model (512MB) by running
|
61 |
+
```bash
|
62 |
+
bash ./scripts/eval_cityscapes/download_fcn8s.sh
|
63 |
+
```
|
64 |
+
Then make sure `./scripts/eval_cityscapes/` is in your system's python path. If not, run the following command to add it
|
65 |
+
```bash
|
66 |
+
export PYTHONPATH=${PYTHONPATH}:./scripts/eval_cityscapes/
|
67 |
+
```
|
68 |
+
Now you can run the following command to evaluate your predictions:
|
69 |
+
```bash
|
70 |
+
python ./scripts/eval_cityscapes/evaluate.py --cityscapes_dir /path/to/original/cityscapes/dataset/ --result_dir /path/to/your/predictions/ --output_dir /path/to/output/directory/
|
71 |
+
```
|
72 |
+
Images stored under `--result_dir` should contain your model predictions on the Cityscapes **validation** split, and have the original Cityscapes naming convention (e.g., `frankfurt_000001_038418_leftImg8bit.png`). The script will output a text file under `--output_dir` containing the metric.
|
73 |
+
|
74 |
+
**Further notes**: Our pre-trained FCN model is **not** supposed to work on Cityscapes in the original resolution (1024x2048) as it was trained on 256x256 images that are then upsampled to 1024x2048 during training. The purpose of the resizing during training was to 1) keep the label maps in the original high resolution untouched and 2) avoid the need of changing the standard FCN training code and the architecture for Cityscapes. During test time, you need to synthesize 256x256 results. Our test code will automatically upsample your results to 1024x2048 before feeding them to the pre-trained FCN model. The output is at 1024x2048 resolution and will be compared to 1024x2048 ground truth labels. You do not need to resize the ground truth labels. The best way to verify whether everything is correct is to reproduce the numbers for real images in the paper first. To achieve it, you need to resize the original/real Cityscapes images (**not** labels) to 256x256 and feed them to the evaluation code.
|
environment.yml
ADDED
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: pytorch-CycleGAN-and-pix2pix
|
2 |
+
channels:
|
3 |
+
- pytorch
|
4 |
+
- defaults
|
5 |
+
dependencies:
|
6 |
+
- python=3.8
|
7 |
+
- pytorch=1.8.1
|
8 |
+
- scipy
|
9 |
+
- pip
|
10 |
+
- pip:
|
11 |
+
- dominate==2.6.0
|
12 |
+
- torchvision==0.9.1
|
13 |
+
- Pillow==8.0.1
|
14 |
+
- numpy==1.19.2
|
15 |
+
- visdom==0.1.8
|
16 |
+
- wandb==0.12.18
|
17 |
+
|
models/__init__.py
ADDED
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""This package contains modules related to objective functions, optimizations, and network architectures.
|
2 |
+
|
3 |
+
To add a custom model class called 'dummy', you need to add a file called 'dummy_model.py' and define a subclass DummyModel inherited from BaseModel.
|
4 |
+
You need to implement the following five functions:
|
5 |
+
-- <__init__>: initialize the class; first call BaseModel.__init__(self, opt).
|
6 |
+
-- <set_input>: unpack data from dataset and apply preprocessing.
|
7 |
+
-- <forward>: produce intermediate results.
|
8 |
+
-- <optimize_parameters>: calculate loss, gradients, and update network weights.
|
9 |
+
-- <modify_commandline_options>: (optionally) add model-specific options and set default options.
|
10 |
+
|
11 |
+
In the function <__init__>, you need to define four lists:
|
12 |
+
-- self.loss_names (str list): specify the training losses that you want to plot and save.
|
13 |
+
-- self.model_names (str list): define networks used in our training.
|
14 |
+
-- self.visual_names (str list): specify the images that you want to display and save.
|
15 |
+
-- self.optimizers (optimizer list): define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an usage.
|
16 |
+
|
17 |
+
Now you can use the model class by specifying flag '--model dummy'.
|
18 |
+
See our template model class 'template_model.py' for more details.
|
19 |
+
"""
|
20 |
+
|
21 |
+
import importlib
|
22 |
+
from models.base_model import BaseModel
|
23 |
+
|
24 |
+
|
25 |
+
def find_model_using_name(model_name):
|
26 |
+
"""Import the module "models/[model_name]_model.py".
|
27 |
+
|
28 |
+
In the file, the class called DatasetNameModel() will
|
29 |
+
be instantiated. It has to be a subclass of BaseModel,
|
30 |
+
and it is case-insensitive.
|
31 |
+
"""
|
32 |
+
model_filename = "models." + model_name + "_model"
|
33 |
+
modellib = importlib.import_module(model_filename)
|
34 |
+
model = None
|
35 |
+
target_model_name = model_name.replace('_', '') + 'model'
|
36 |
+
for name, cls in modellib.__dict__.items():
|
37 |
+
if name.lower() == target_model_name.lower() \
|
38 |
+
and issubclass(cls, BaseModel):
|
39 |
+
model = cls
|
40 |
+
|
41 |
+
if model is None:
|
42 |
+
print("In %s.py, there should be a subclass of BaseModel with class name that matches %s in lowercase." % (model_filename, target_model_name))
|
43 |
+
exit(0)
|
44 |
+
|
45 |
+
return model
|
46 |
+
|
47 |
+
|
48 |
+
def get_option_setter(model_name):
|
49 |
+
"""Return the static method <modify_commandline_options> of the model class."""
|
50 |
+
model_class = find_model_using_name(model_name)
|
51 |
+
return model_class.modify_commandline_options
|
52 |
+
|
53 |
+
|
54 |
+
def create_model(opt):
|
55 |
+
"""Create a model given the option.
|
56 |
+
|
57 |
+
This function warps the class CustomDatasetDataLoader.
|
58 |
+
This is the main interface between this package and 'train.py'/'test.py'
|
59 |
+
|
60 |
+
Example:
|
61 |
+
>>> from models import create_model
|
62 |
+
>>> model = create_model(opt)
|
63 |
+
"""
|
64 |
+
model = find_model_using_name(opt.model)
|
65 |
+
instance = model(opt)
|
66 |
+
print("model [%s] was created" % type(instance).__name__)
|
67 |
+
return instance
|
models/base_model.py
ADDED
@@ -0,0 +1,230 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
from collections import OrderedDict
|
4 |
+
from abc import ABC, abstractmethod
|
5 |
+
from . import networks
|
6 |
+
|
7 |
+
|
8 |
+
class BaseModel(ABC):
|
9 |
+
"""This class is an abstract base class (ABC) for models.
|
10 |
+
To create a subclass, you need to implement the following five functions:
|
11 |
+
-- <__init__>: initialize the class; first call BaseModel.__init__(self, opt).
|
12 |
+
-- <set_input>: unpack data from dataset and apply preprocessing.
|
13 |
+
-- <forward>: produce intermediate results.
|
14 |
+
-- <optimize_parameters>: calculate losses, gradients, and update network weights.
|
15 |
+
-- <modify_commandline_options>: (optionally) add model-specific options and set default options.
|
16 |
+
"""
|
17 |
+
|
18 |
+
def __init__(self, opt):
|
19 |
+
"""Initialize the BaseModel class.
|
20 |
+
|
21 |
+
Parameters:
|
22 |
+
opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
|
23 |
+
|
24 |
+
When creating your custom class, you need to implement your own initialization.
|
25 |
+
In this function, you should first call <BaseModel.__init__(self, opt)>
|
26 |
+
Then, you need to define four lists:
|
27 |
+
-- self.loss_names (str list): specify the training losses that you want to plot and save.
|
28 |
+
-- self.model_names (str list): define networks used in our training.
|
29 |
+
-- self.visual_names (str list): specify the images that you want to display and save.
|
30 |
+
-- self.optimizers (optimizer list): define and initialize optimizers. You can define one optimizer for each network. If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an example.
|
31 |
+
"""
|
32 |
+
self.opt = opt
|
33 |
+
self.gpu_ids = opt.gpu_ids
|
34 |
+
self.isTrain = opt.isTrain
|
35 |
+
self.device = torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu') # get device name: CPU or GPU
|
36 |
+
self.save_dir = os.path.join(opt.checkpoints_dir, opt.name) # save all the checkpoints to save_dir
|
37 |
+
if opt.preprocess != 'scale_width': # with [scale_width], input images might have different sizes, which hurts the performance of cudnn.benchmark.
|
38 |
+
torch.backends.cudnn.benchmark = True
|
39 |
+
self.loss_names = []
|
40 |
+
self.model_names = []
|
41 |
+
self.visual_names = []
|
42 |
+
self.optimizers = []
|
43 |
+
self.image_paths = []
|
44 |
+
self.metric = 0 # used for learning rate policy 'plateau'
|
45 |
+
|
46 |
+
@staticmethod
|
47 |
+
def modify_commandline_options(parser, is_train):
|
48 |
+
"""Add new model-specific options, and rewrite default values for existing options.
|
49 |
+
|
50 |
+
Parameters:
|
51 |
+
parser -- original option parser
|
52 |
+
is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.
|
53 |
+
|
54 |
+
Returns:
|
55 |
+
the modified parser.
|
56 |
+
"""
|
57 |
+
return parser
|
58 |
+
|
59 |
+
@abstractmethod
|
60 |
+
def set_input(self, input):
|
61 |
+
"""Unpack input data from the dataloader and perform necessary pre-processing steps.
|
62 |
+
|
63 |
+
Parameters:
|
64 |
+
input (dict): includes the data itself and its metadata information.
|
65 |
+
"""
|
66 |
+
pass
|
67 |
+
|
68 |
+
@abstractmethod
|
69 |
+
def forward(self):
|
70 |
+
"""Run forward pass; called by both functions <optimize_parameters> and <test>."""
|
71 |
+
pass
|
72 |
+
|
73 |
+
@abstractmethod
|
74 |
+
def optimize_parameters(self):
|
75 |
+
"""Calculate losses, gradients, and update network weights; called in every training iteration"""
|
76 |
+
pass
|
77 |
+
|
78 |
+
def setup(self, opt):
|
79 |
+
"""Load and print networks; create schedulers
|
80 |
+
|
81 |
+
Parameters:
|
82 |
+
opt (Option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions
|
83 |
+
"""
|
84 |
+
if self.isTrain:
|
85 |
+
self.schedulers = [networks.get_scheduler(optimizer, opt) for optimizer in self.optimizers]
|
86 |
+
if not self.isTrain or opt.continue_train:
|
87 |
+
load_suffix = 'iter_%d' % opt.load_iter if opt.load_iter > 0 else opt.epoch
|
88 |
+
self.load_networks(load_suffix)
|
89 |
+
self.print_networks(opt.verbose)
|
90 |
+
|
91 |
+
def eval(self):
|
92 |
+
"""Make models eval mode during test time"""
|
93 |
+
for name in self.model_names:
|
94 |
+
if isinstance(name, str):
|
95 |
+
net = getattr(self, 'net' + name)
|
96 |
+
net.eval()
|
97 |
+
|
98 |
+
def test(self):
|
99 |
+
"""Forward function used in test time.
|
100 |
+
|
101 |
+
This function wraps <forward> function in no_grad() so we don't save intermediate steps for backprop
|
102 |
+
It also calls <compute_visuals> to produce additional visualization results
|
103 |
+
"""
|
104 |
+
with torch.no_grad():
|
105 |
+
self.forward()
|
106 |
+
self.compute_visuals()
|
107 |
+
|
108 |
+
def compute_visuals(self):
|
109 |
+
"""Calculate additional output images for visdom and HTML visualization"""
|
110 |
+
pass
|
111 |
+
|
112 |
+
def get_image_paths(self):
|
113 |
+
""" Return image paths that are used to load current data"""
|
114 |
+
return self.image_paths
|
115 |
+
|
116 |
+
def update_learning_rate(self):
|
117 |
+
"""Update learning rates for all the networks; called at the end of every epoch"""
|
118 |
+
old_lr = self.optimizers[0].param_groups[0]['lr']
|
119 |
+
for scheduler in self.schedulers:
|
120 |
+
if self.opt.lr_policy == 'plateau':
|
121 |
+
scheduler.step(self.metric)
|
122 |
+
else:
|
123 |
+
scheduler.step()
|
124 |
+
|
125 |
+
lr = self.optimizers[0].param_groups[0]['lr']
|
126 |
+
print('learning rate %.7f -> %.7f' % (old_lr, lr))
|
127 |
+
|
128 |
+
def get_current_visuals(self):
|
129 |
+
"""Return visualization images. train.py will display these images with visdom, and save the images to a HTML"""
|
130 |
+
visual_ret = OrderedDict()
|
131 |
+
for name in self.visual_names:
|
132 |
+
if isinstance(name, str):
|
133 |
+
visual_ret[name] = getattr(self, name)
|
134 |
+
return visual_ret
|
135 |
+
|
136 |
+
def get_current_losses(self):
|
137 |
+
"""Return traning losses / errors. train.py will print out these errors on console, and save them to a file"""
|
138 |
+
errors_ret = OrderedDict()
|
139 |
+
for name in self.loss_names:
|
140 |
+
if isinstance(name, str):
|
141 |
+
errors_ret[name] = float(getattr(self, 'loss_' + name)) # float(...) works for both scalar tensor and float number
|
142 |
+
return errors_ret
|
143 |
+
|
144 |
+
def save_networks(self, epoch):
|
145 |
+
"""Save all the networks to the disk.
|
146 |
+
|
147 |
+
Parameters:
|
148 |
+
epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)
|
149 |
+
"""
|
150 |
+
for name in self.model_names:
|
151 |
+
if isinstance(name, str):
|
152 |
+
save_filename = '%s_net_%s.pth' % (epoch, name)
|
153 |
+
save_path = os.path.join(self.save_dir, save_filename)
|
154 |
+
net = getattr(self, 'net' + name)
|
155 |
+
|
156 |
+
if len(self.gpu_ids) > 0 and torch.cuda.is_available():
|
157 |
+
torch.save(net.module.cpu().state_dict(), save_path)
|
158 |
+
net.cuda(self.gpu_ids[0])
|
159 |
+
else:
|
160 |
+
torch.save(net.cpu().state_dict(), save_path)
|
161 |
+
|
162 |
+
def __patch_instance_norm_state_dict(self, state_dict, module, keys, i=0):
|
163 |
+
"""Fix InstanceNorm checkpoints incompatibility (prior to 0.4)"""
|
164 |
+
key = keys[i]
|
165 |
+
if i + 1 == len(keys): # at the end, pointing to a parameter/buffer
|
166 |
+
if module.__class__.__name__.startswith('InstanceNorm') and \
|
167 |
+
(key == 'running_mean' or key == 'running_var'):
|
168 |
+
if getattr(module, key) is None:
|
169 |
+
state_dict.pop('.'.join(keys))
|
170 |
+
if module.__class__.__name__.startswith('InstanceNorm') and \
|
171 |
+
(key == 'num_batches_tracked'):
|
172 |
+
state_dict.pop('.'.join(keys))
|
173 |
+
else:
|
174 |
+
self.__patch_instance_norm_state_dict(state_dict, getattr(module, key), keys, i + 1)
|
175 |
+
|
176 |
+
def load_networks(self, epoch):
|
177 |
+
"""Load all the networks from the disk.
|
178 |
+
|
179 |
+
Parameters:
|
180 |
+
epoch (int) -- current epoch; used in the file name '%s_net_%s.pth' % (epoch, name)
|
181 |
+
"""
|
182 |
+
for name in self.model_names:
|
183 |
+
if isinstance(name, str):
|
184 |
+
load_filename = '%s_net_%s.pth' % (epoch, name)
|
185 |
+
load_path = os.path.join(self.save_dir, load_filename)
|
186 |
+
net = getattr(self, 'net' + name)
|
187 |
+
if isinstance(net, torch.nn.DataParallel):
|
188 |
+
net = net.module
|
189 |
+
print('loading the model from %s' % load_path)
|
190 |
+
# if you are using PyTorch newer than 0.4 (e.g., built from
|
191 |
+
# GitHub source), you can remove str() on self.device
|
192 |
+
state_dict = torch.load(load_path, map_location=str(self.device))
|
193 |
+
if hasattr(state_dict, '_metadata'):
|
194 |
+
del state_dict._metadata
|
195 |
+
|
196 |
+
# patch InstanceNorm checkpoints prior to 0.4
|
197 |
+
for key in list(state_dict.keys()): # need to copy keys here because we mutate in loop
|
198 |
+
self.__patch_instance_norm_state_dict(state_dict, net, key.split('.'))
|
199 |
+
net.load_state_dict(state_dict)
|
200 |
+
|
201 |
+
def print_networks(self, verbose):
|
202 |
+
"""Print the total number of parameters in the network and (if verbose) network architecture
|
203 |
+
|
204 |
+
Parameters:
|
205 |
+
verbose (bool) -- if verbose: print the network architecture
|
206 |
+
"""
|
207 |
+
print('---------- Networks initialized -------------')
|
208 |
+
for name in self.model_names:
|
209 |
+
if isinstance(name, str):
|
210 |
+
net = getattr(self, 'net' + name)
|
211 |
+
num_params = 0
|
212 |
+
for param in net.parameters():
|
213 |
+
num_params += param.numel()
|
214 |
+
if verbose:
|
215 |
+
print(net)
|
216 |
+
print('[Network %s] Total number of parameters : %.3f M' % (name, num_params / 1e6))
|
217 |
+
print('-----------------------------------------------')
|
218 |
+
|
219 |
+
def set_requires_grad(self, nets, requires_grad=False):
|
220 |
+
"""Set requies_grad=Fasle for all the networks to avoid unnecessary computations
|
221 |
+
Parameters:
|
222 |
+
nets (network list) -- a list of networks
|
223 |
+
requires_grad (bool) -- whether the networks require gradients or not
|
224 |
+
"""
|
225 |
+
if not isinstance(nets, list):
|
226 |
+
nets = [nets]
|
227 |
+
for net in nets:
|
228 |
+
if net is not None:
|
229 |
+
for param in net.parameters():
|
230 |
+
param.requires_grad = requires_grad
|
models/colorization_model.py
ADDED
@@ -0,0 +1,68 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .pix2pix_model import Pix2PixModel
|
2 |
+
import torch
|
3 |
+
from skimage import color # used for lab2rgb
|
4 |
+
import numpy as np
|
5 |
+
|
6 |
+
|
7 |
+
class ColorizationModel(Pix2PixModel):
|
8 |
+
"""This is a subclass of Pix2PixModel for image colorization (black & white image -> colorful images).
|
9 |
+
|
10 |
+
The model training requires '-dataset_model colorization' dataset.
|
11 |
+
It trains a pix2pix model, mapping from L channel to ab channels in Lab color space.
|
12 |
+
By default, the colorization dataset will automatically set '--input_nc 1' and '--output_nc 2'.
|
13 |
+
"""
|
14 |
+
@staticmethod
|
15 |
+
def modify_commandline_options(parser, is_train=True):
|
16 |
+
"""Add new dataset-specific options, and rewrite default values for existing options.
|
17 |
+
|
18 |
+
Parameters:
|
19 |
+
parser -- original option parser
|
20 |
+
is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.
|
21 |
+
|
22 |
+
Returns:
|
23 |
+
the modified parser.
|
24 |
+
|
25 |
+
By default, we use 'colorization' dataset for this model.
|
26 |
+
See the original pix2pix paper (https://arxiv.org/pdf/1611.07004.pdf) and colorization results (Figure 9 in the paper)
|
27 |
+
"""
|
28 |
+
Pix2PixModel.modify_commandline_options(parser, is_train)
|
29 |
+
parser.set_defaults(dataset_mode='colorization')
|
30 |
+
return parser
|
31 |
+
|
32 |
+
def __init__(self, opt):
|
33 |
+
"""Initialize the class.
|
34 |
+
|
35 |
+
Parameters:
|
36 |
+
opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
|
37 |
+
|
38 |
+
For visualization, we set 'visual_names' as 'real_A' (input real image),
|
39 |
+
'real_B_rgb' (ground truth RGB image), and 'fake_B_rgb' (predicted RGB image)
|
40 |
+
We convert the Lab image 'real_B' (inherited from Pix2pixModel) to a RGB image 'real_B_rgb'.
|
41 |
+
we convert the Lab image 'fake_B' (inherited from Pix2pixModel) to a RGB image 'fake_B_rgb'.
|
42 |
+
"""
|
43 |
+
# reuse the pix2pix model
|
44 |
+
Pix2PixModel.__init__(self, opt)
|
45 |
+
# specify the images to be visualized.
|
46 |
+
self.visual_names = ['real_A', 'real_B_rgb', 'fake_B_rgb']
|
47 |
+
|
48 |
+
def lab2rgb(self, L, AB):
|
49 |
+
"""Convert an Lab tensor image to a RGB numpy output
|
50 |
+
Parameters:
|
51 |
+
L (1-channel tensor array): L channel images (range: [-1, 1], torch tensor array)
|
52 |
+
AB (2-channel tensor array): ab channel images (range: [-1, 1], torch tensor array)
|
53 |
+
|
54 |
+
Returns:
|
55 |
+
rgb (RGB numpy image): rgb output images (range: [0, 255], numpy array)
|
56 |
+
"""
|
57 |
+
AB2 = AB * 110.0
|
58 |
+
L2 = (L + 1.0) * 50.0
|
59 |
+
Lab = torch.cat([L2, AB2], dim=1)
|
60 |
+
Lab = Lab[0].data.cpu().float().numpy()
|
61 |
+
Lab = np.transpose(Lab.astype(np.float64), (1, 2, 0))
|
62 |
+
rgb = color.lab2rgb(Lab) * 255
|
63 |
+
return rgb
|
64 |
+
|
65 |
+
def compute_visuals(self):
|
66 |
+
"""Calculate additional output images for visdom and HTML visualization"""
|
67 |
+
self.real_B_rgb = self.lab2rgb(self.real_A, self.real_B)
|
68 |
+
self.fake_B_rgb = self.lab2rgb(self.real_A, self.fake_B)
|
models/cycle_gan_model.py
ADDED
@@ -0,0 +1,194 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import itertools
|
3 |
+
from util.image_pool import ImagePool
|
4 |
+
from .base_model import BaseModel
|
5 |
+
from . import networks
|
6 |
+
|
7 |
+
|
8 |
+
class CycleGANModel(BaseModel):
|
9 |
+
"""
|
10 |
+
This class implements the CycleGAN model, for learning image-to-image translation without paired data.
|
11 |
+
|
12 |
+
The model training requires '--dataset_mode unaligned' dataset.
|
13 |
+
By default, it uses a '--netG resnet_9blocks' ResNet generator,
|
14 |
+
a '--netD basic' discriminator (PatchGAN introduced by pix2pix),
|
15 |
+
and a least-square GANs objective ('--gan_mode lsgan').
|
16 |
+
|
17 |
+
CycleGAN paper: https://arxiv.org/pdf/1703.10593.pdf
|
18 |
+
"""
|
19 |
+
@staticmethod
|
20 |
+
def modify_commandline_options(parser, is_train=True):
|
21 |
+
"""Add new dataset-specific options, and rewrite default values for existing options.
|
22 |
+
|
23 |
+
Parameters:
|
24 |
+
parser -- original option parser
|
25 |
+
is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.
|
26 |
+
|
27 |
+
Returns:
|
28 |
+
the modified parser.
|
29 |
+
|
30 |
+
For CycleGAN, in addition to GAN losses, we introduce lambda_A, lambda_B, and lambda_identity for the following losses.
|
31 |
+
A (source domain), B (target domain).
|
32 |
+
Generators: G_A: A -> B; G_B: B -> A.
|
33 |
+
Discriminators: D_A: G_A(A) vs. B; D_B: G_B(B) vs. A.
|
34 |
+
Forward cycle loss: lambda_A * ||G_B(G_A(A)) - A|| (Eqn. (2) in the paper)
|
35 |
+
Backward cycle loss: lambda_B * ||G_A(G_B(B)) - B|| (Eqn. (2) in the paper)
|
36 |
+
Identity loss (optional): lambda_identity * (||G_A(B) - B|| * lambda_B + ||G_B(A) - A|| * lambda_A) (Sec 5.2 "Photo generation from paintings" in the paper)
|
37 |
+
Dropout is not used in the original CycleGAN paper.
|
38 |
+
"""
|
39 |
+
parser.set_defaults(no_dropout=True) # default CycleGAN did not use dropout
|
40 |
+
if is_train:
|
41 |
+
parser.add_argument('--lambda_A', type=float, default=10.0, help='weight for cycle loss (A -> B -> A)')
|
42 |
+
parser.add_argument('--lambda_B', type=float, default=10.0, help='weight for cycle loss (B -> A -> B)')
|
43 |
+
parser.add_argument('--lambda_identity', type=float, default=0.5, help='use identity mapping. Setting lambda_identity other than 0 has an effect of scaling the weight of the identity mapping loss. For example, if the weight of the identity loss should be 10 times smaller than the weight of the reconstruction loss, please set lambda_identity = 0.1')
|
44 |
+
|
45 |
+
return parser
|
46 |
+
|
47 |
+
def __init__(self, opt):
|
48 |
+
"""Initialize the CycleGAN class.
|
49 |
+
|
50 |
+
Parameters:
|
51 |
+
opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
|
52 |
+
"""
|
53 |
+
BaseModel.__init__(self, opt)
|
54 |
+
# specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses>
|
55 |
+
self.loss_names = ['D_A', 'G_A', 'cycle_A', 'idt_A', 'D_B', 'G_B', 'cycle_B', 'idt_B']
|
56 |
+
# specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals>
|
57 |
+
visual_names_A = ['real_A', 'fake_B', 'rec_A']
|
58 |
+
visual_names_B = ['real_B', 'fake_A', 'rec_B']
|
59 |
+
if self.isTrain and self.opt.lambda_identity > 0.0: # if identity loss is used, we also visualize idt_B=G_A(B) ad idt_A=G_A(B)
|
60 |
+
visual_names_A.append('idt_B')
|
61 |
+
visual_names_B.append('idt_A')
|
62 |
+
|
63 |
+
self.visual_names = visual_names_A + visual_names_B # combine visualizations for A and B
|
64 |
+
# specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>.
|
65 |
+
if self.isTrain:
|
66 |
+
self.model_names = ['G_A', 'G_B', 'D_A', 'D_B']
|
67 |
+
else: # during test time, only load Gs
|
68 |
+
self.model_names = ['G_A', 'G_B']
|
69 |
+
|
70 |
+
# define networks (both Generators and discriminators)
|
71 |
+
# The naming is different from those used in the paper.
|
72 |
+
# Code (vs. paper): G_A (G), G_B (F), D_A (D_Y), D_B (D_X)
|
73 |
+
self.netG_A = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, opt.norm,
|
74 |
+
not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids)
|
75 |
+
self.netG_B = networks.define_G(opt.output_nc, opt.input_nc, opt.ngf, opt.netG, opt.norm,
|
76 |
+
not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids)
|
77 |
+
|
78 |
+
if self.isTrain: # define discriminators
|
79 |
+
self.netD_A = networks.define_D(opt.output_nc, opt.ndf, opt.netD,
|
80 |
+
opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids)
|
81 |
+
self.netD_B = networks.define_D(opt.input_nc, opt.ndf, opt.netD,
|
82 |
+
opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids)
|
83 |
+
|
84 |
+
if self.isTrain:
|
85 |
+
if opt.lambda_identity > 0.0: # only works when input and output images have the same number of channels
|
86 |
+
assert(opt.input_nc == opt.output_nc)
|
87 |
+
self.fake_A_pool = ImagePool(opt.pool_size) # create image buffer to store previously generated images
|
88 |
+
self.fake_B_pool = ImagePool(opt.pool_size) # create image buffer to store previously generated images
|
89 |
+
# define loss functions
|
90 |
+
self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device) # define GAN loss.
|
91 |
+
self.criterionCycle = torch.nn.L1Loss()
|
92 |
+
self.criterionIdt = torch.nn.L1Loss()
|
93 |
+
# initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>.
|
94 |
+
self.optimizer_G = torch.optim.Adam(itertools.chain(self.netG_A.parameters(), self.netG_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999))
|
95 |
+
self.optimizer_D = torch.optim.Adam(itertools.chain(self.netD_A.parameters(), self.netD_B.parameters()), lr=opt.lr, betas=(opt.beta1, 0.999))
|
96 |
+
self.optimizers.append(self.optimizer_G)
|
97 |
+
self.optimizers.append(self.optimizer_D)
|
98 |
+
|
99 |
+
def set_input(self, input):
|
100 |
+
"""Unpack input data from the dataloader and perform necessary pre-processing steps.
|
101 |
+
|
102 |
+
Parameters:
|
103 |
+
input (dict): include the data itself and its metadata information.
|
104 |
+
|
105 |
+
The option 'direction' can be used to swap domain A and domain B.
|
106 |
+
"""
|
107 |
+
AtoB = self.opt.direction == 'AtoB'
|
108 |
+
self.real_A = input['A' if AtoB else 'B'].to(self.device)
|
109 |
+
self.real_B = input['B' if AtoB else 'A'].to(self.device)
|
110 |
+
self.image_paths = input['A_paths' if AtoB else 'B_paths']
|
111 |
+
|
112 |
+
def forward(self):
|
113 |
+
"""Run forward pass; called by both functions <optimize_parameters> and <test>."""
|
114 |
+
self.fake_B = self.netG_A(self.real_A) # G_A(A)
|
115 |
+
self.rec_A = self.netG_B(self.fake_B) # G_B(G_A(A))
|
116 |
+
self.fake_A = self.netG_B(self.real_B) # G_B(B)
|
117 |
+
self.rec_B = self.netG_A(self.fake_A) # G_A(G_B(B))
|
118 |
+
|
119 |
+
def backward_D_basic(self, netD, real, fake):
|
120 |
+
"""Calculate GAN loss for the discriminator
|
121 |
+
|
122 |
+
Parameters:
|
123 |
+
netD (network) -- the discriminator D
|
124 |
+
real (tensor array) -- real images
|
125 |
+
fake (tensor array) -- images generated by a generator
|
126 |
+
|
127 |
+
Return the discriminator loss.
|
128 |
+
We also call loss_D.backward() to calculate the gradients.
|
129 |
+
"""
|
130 |
+
# Real
|
131 |
+
pred_real = netD(real)
|
132 |
+
loss_D_real = self.criterionGAN(pred_real, True)
|
133 |
+
# Fake
|
134 |
+
pred_fake = netD(fake.detach())
|
135 |
+
loss_D_fake = self.criterionGAN(pred_fake, False)
|
136 |
+
# Combined loss and calculate gradients
|
137 |
+
loss_D = (loss_D_real + loss_D_fake) * 0.5
|
138 |
+
loss_D.backward()
|
139 |
+
return loss_D
|
140 |
+
|
141 |
+
def backward_D_A(self):
|
142 |
+
"""Calculate GAN loss for discriminator D_A"""
|
143 |
+
fake_B = self.fake_B_pool.query(self.fake_B)
|
144 |
+
self.loss_D_A = self.backward_D_basic(self.netD_A, self.real_B, fake_B)
|
145 |
+
|
146 |
+
def backward_D_B(self):
|
147 |
+
"""Calculate GAN loss for discriminator D_B"""
|
148 |
+
fake_A = self.fake_A_pool.query(self.fake_A)
|
149 |
+
self.loss_D_B = self.backward_D_basic(self.netD_B, self.real_A, fake_A)
|
150 |
+
|
151 |
+
def backward_G(self):
|
152 |
+
"""Calculate the loss for generators G_A and G_B"""
|
153 |
+
lambda_idt = self.opt.lambda_identity
|
154 |
+
lambda_A = self.opt.lambda_A
|
155 |
+
lambda_B = self.opt.lambda_B
|
156 |
+
# Identity loss
|
157 |
+
if lambda_idt > 0:
|
158 |
+
# G_A should be identity if real_B is fed: ||G_A(B) - B||
|
159 |
+
self.idt_A = self.netG_A(self.real_B)
|
160 |
+
self.loss_idt_A = self.criterionIdt(self.idt_A, self.real_B) * lambda_B * lambda_idt
|
161 |
+
# G_B should be identity if real_A is fed: ||G_B(A) - A||
|
162 |
+
self.idt_B = self.netG_B(self.real_A)
|
163 |
+
self.loss_idt_B = self.criterionIdt(self.idt_B, self.real_A) * lambda_A * lambda_idt
|
164 |
+
else:
|
165 |
+
self.loss_idt_A = 0
|
166 |
+
self.loss_idt_B = 0
|
167 |
+
|
168 |
+
# GAN loss D_A(G_A(A))
|
169 |
+
self.loss_G_A = self.criterionGAN(self.netD_A(self.fake_B), True)
|
170 |
+
# GAN loss D_B(G_B(B))
|
171 |
+
self.loss_G_B = self.criterionGAN(self.netD_B(self.fake_A), True)
|
172 |
+
# Forward cycle loss || G_B(G_A(A)) - A||
|
173 |
+
self.loss_cycle_A = self.criterionCycle(self.rec_A, self.real_A) * lambda_A
|
174 |
+
# Backward cycle loss || G_A(G_B(B)) - B||
|
175 |
+
self.loss_cycle_B = self.criterionCycle(self.rec_B, self.real_B) * lambda_B
|
176 |
+
# combined loss and calculate gradients
|
177 |
+
self.loss_G = self.loss_G_A + self.loss_G_B + self.loss_cycle_A + self.loss_cycle_B + self.loss_idt_A + self.loss_idt_B
|
178 |
+
self.loss_G.backward()
|
179 |
+
|
180 |
+
def optimize_parameters(self):
|
181 |
+
"""Calculate losses, gradients, and update network weights; called in every training iteration"""
|
182 |
+
# forward
|
183 |
+
self.forward() # compute fake images and reconstruction images.
|
184 |
+
# G_A and G_B
|
185 |
+
self.set_requires_grad([self.netD_A, self.netD_B], False) # Ds require no gradients when optimizing Gs
|
186 |
+
self.optimizer_G.zero_grad() # set G_A and G_B's gradients to zero
|
187 |
+
self.backward_G() # calculate gradients for G_A and G_B
|
188 |
+
self.optimizer_G.step() # update G_A and G_B's weights
|
189 |
+
# D_A and D_B
|
190 |
+
self.set_requires_grad([self.netD_A, self.netD_B], True)
|
191 |
+
self.optimizer_D.zero_grad() # set D_A and D_B's gradients to zero
|
192 |
+
self.backward_D_A() # calculate gradients for D_A
|
193 |
+
self.backward_D_B() # calculate graidents for D_B
|
194 |
+
self.optimizer_D.step() # update D_A and D_B's weights
|
models/networks.py
ADDED
@@ -0,0 +1,616 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn as nn
|
3 |
+
from torch.nn import init
|
4 |
+
import functools
|
5 |
+
from torch.optim import lr_scheduler
|
6 |
+
|
7 |
+
|
8 |
+
###############################################################################
|
9 |
+
# Helper Functions
|
10 |
+
###############################################################################
|
11 |
+
|
12 |
+
|
13 |
+
class Identity(nn.Module):
|
14 |
+
def forward(self, x):
|
15 |
+
return x
|
16 |
+
|
17 |
+
|
18 |
+
def get_norm_layer(norm_type='instance'):
|
19 |
+
"""Return a normalization layer
|
20 |
+
|
21 |
+
Parameters:
|
22 |
+
norm_type (str) -- the name of the normalization layer: batch | instance | none
|
23 |
+
|
24 |
+
For BatchNorm, we use learnable affine parameters and track running statistics (mean/stddev).
|
25 |
+
For InstanceNorm, we do not use learnable affine parameters. We do not track running statistics.
|
26 |
+
"""
|
27 |
+
if norm_type == 'batch':
|
28 |
+
norm_layer = functools.partial(nn.BatchNorm2d, affine=True, track_running_stats=True)
|
29 |
+
elif norm_type == 'instance':
|
30 |
+
norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False)
|
31 |
+
elif norm_type == 'none':
|
32 |
+
def norm_layer(x):
|
33 |
+
return Identity()
|
34 |
+
else:
|
35 |
+
raise NotImplementedError('normalization layer [%s] is not found' % norm_type)
|
36 |
+
return norm_layer
|
37 |
+
|
38 |
+
|
39 |
+
def get_scheduler(optimizer, opt):
|
40 |
+
"""Return a learning rate scheduler
|
41 |
+
|
42 |
+
Parameters:
|
43 |
+
optimizer -- the optimizer of the network
|
44 |
+
opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions.
|
45 |
+
opt.lr_policy is the name of learning rate policy: linear | step | plateau | cosine
|
46 |
+
|
47 |
+
For 'linear', we keep the same learning rate for the first <opt.n_epochs> epochs
|
48 |
+
and linearly decay the rate to zero over the next <opt.n_epochs_decay> epochs.
|
49 |
+
For other schedulers (step, plateau, and cosine), we use the default PyTorch schedulers.
|
50 |
+
See https://pytorch.org/docs/stable/optim.html for more details.
|
51 |
+
"""
|
52 |
+
if opt.lr_policy == 'linear':
|
53 |
+
def lambda_rule(epoch):
|
54 |
+
lr_l = 1.0 - max(0, epoch + opt.epoch_count - opt.n_epochs) / float(opt.n_epochs_decay + 1)
|
55 |
+
return lr_l
|
56 |
+
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)
|
57 |
+
elif opt.lr_policy == 'step':
|
58 |
+
scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1)
|
59 |
+
elif opt.lr_policy == 'plateau':
|
60 |
+
scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5)
|
61 |
+
elif opt.lr_policy == 'cosine':
|
62 |
+
scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.n_epochs, eta_min=0)
|
63 |
+
else:
|
64 |
+
return NotImplementedError('learning rate policy [%s] is not implemented', opt.lr_policy)
|
65 |
+
return scheduler
|
66 |
+
|
67 |
+
|
68 |
+
def init_weights(net, init_type='normal', init_gain=0.02):
|
69 |
+
"""Initialize network weights.
|
70 |
+
|
71 |
+
Parameters:
|
72 |
+
net (network) -- network to be initialized
|
73 |
+
init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal
|
74 |
+
init_gain (float) -- scaling factor for normal, xavier and orthogonal.
|
75 |
+
|
76 |
+
We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might
|
77 |
+
work better for some applications. Feel free to try yourself.
|
78 |
+
"""
|
79 |
+
def init_func(m): # define the initialization function
|
80 |
+
classname = m.__class__.__name__
|
81 |
+
if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
|
82 |
+
if init_type == 'normal':
|
83 |
+
init.normal_(m.weight.data, 0.0, init_gain)
|
84 |
+
elif init_type == 'xavier':
|
85 |
+
init.xavier_normal_(m.weight.data, gain=init_gain)
|
86 |
+
elif init_type == 'kaiming':
|
87 |
+
init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
|
88 |
+
elif init_type == 'orthogonal':
|
89 |
+
init.orthogonal_(m.weight.data, gain=init_gain)
|
90 |
+
else:
|
91 |
+
raise NotImplementedError('initialization method [%s] is not implemented' % init_type)
|
92 |
+
if hasattr(m, 'bias') and m.bias is not None:
|
93 |
+
init.constant_(m.bias.data, 0.0)
|
94 |
+
elif classname.find('BatchNorm2d') != -1: # BatchNorm Layer's weight is not a matrix; only normal distribution applies.
|
95 |
+
init.normal_(m.weight.data, 1.0, init_gain)
|
96 |
+
init.constant_(m.bias.data, 0.0)
|
97 |
+
|
98 |
+
print('initialize network with %s' % init_type)
|
99 |
+
net.apply(init_func) # apply the initialization function <init_func>
|
100 |
+
|
101 |
+
|
102 |
+
def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]):
|
103 |
+
"""Initialize a network: 1. register CPU/GPU device (with multi-GPU support); 2. initialize the network weights
|
104 |
+
Parameters:
|
105 |
+
net (network) -- the network to be initialized
|
106 |
+
init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal
|
107 |
+
gain (float) -- scaling factor for normal, xavier and orthogonal.
|
108 |
+
gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2
|
109 |
+
|
110 |
+
Return an initialized network.
|
111 |
+
"""
|
112 |
+
if len(gpu_ids) > 0:
|
113 |
+
assert(torch.cuda.is_available())
|
114 |
+
net.to(gpu_ids[0])
|
115 |
+
net = torch.nn.DataParallel(net, gpu_ids) # multi-GPUs
|
116 |
+
init_weights(net, init_type, init_gain=init_gain)
|
117 |
+
return net
|
118 |
+
|
119 |
+
|
120 |
+
def define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]):
|
121 |
+
"""Create a generator
|
122 |
+
|
123 |
+
Parameters:
|
124 |
+
input_nc (int) -- the number of channels in input images
|
125 |
+
output_nc (int) -- the number of channels in output images
|
126 |
+
ngf (int) -- the number of filters in the last conv layer
|
127 |
+
netG (str) -- the architecture's name: resnet_9blocks | resnet_6blocks | unet_256 | unet_128
|
128 |
+
norm (str) -- the name of normalization layers used in the network: batch | instance | none
|
129 |
+
use_dropout (bool) -- if use dropout layers.
|
130 |
+
init_type (str) -- the name of our initialization method.
|
131 |
+
init_gain (float) -- scaling factor for normal, xavier and orthogonal.
|
132 |
+
gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2
|
133 |
+
|
134 |
+
Returns a generator
|
135 |
+
|
136 |
+
Our current implementation provides two types of generators:
|
137 |
+
U-Net: [unet_128] (for 128x128 input images) and [unet_256] (for 256x256 input images)
|
138 |
+
The original U-Net paper: https://arxiv.org/abs/1505.04597
|
139 |
+
|
140 |
+
Resnet-based generator: [resnet_6blocks] (with 6 Resnet blocks) and [resnet_9blocks] (with 9 Resnet blocks)
|
141 |
+
Resnet-based generator consists of several Resnet blocks between a few downsampling/upsampling operations.
|
142 |
+
We adapt Torch code from Justin Johnson's neural style transfer project (https://github.com/jcjohnson/fast-neural-style).
|
143 |
+
|
144 |
+
|
145 |
+
The generator has been initialized by <init_net>. It uses RELU for non-linearity.
|
146 |
+
"""
|
147 |
+
net = None
|
148 |
+
norm_layer = get_norm_layer(norm_type=norm)
|
149 |
+
|
150 |
+
if netG == 'resnet_9blocks':
|
151 |
+
net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)
|
152 |
+
elif netG == 'resnet_6blocks':
|
153 |
+
net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6)
|
154 |
+
elif netG == 'unet_128':
|
155 |
+
net = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout)
|
156 |
+
elif netG == 'unet_256':
|
157 |
+
net = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout)
|
158 |
+
else:
|
159 |
+
raise NotImplementedError('Generator model name [%s] is not recognized' % netG)
|
160 |
+
return init_net(net, init_type, init_gain, gpu_ids)
|
161 |
+
|
162 |
+
|
163 |
+
def define_D(input_nc, ndf, netD, n_layers_D=3, norm='batch', init_type='normal', init_gain=0.02, gpu_ids=[]):
|
164 |
+
"""Create a discriminator
|
165 |
+
|
166 |
+
Parameters:
|
167 |
+
input_nc (int) -- the number of channels in input images
|
168 |
+
ndf (int) -- the number of filters in the first conv layer
|
169 |
+
netD (str) -- the architecture's name: basic | n_layers | pixel
|
170 |
+
n_layers_D (int) -- the number of conv layers in the discriminator; effective when netD=='n_layers'
|
171 |
+
norm (str) -- the type of normalization layers used in the network.
|
172 |
+
init_type (str) -- the name of the initialization method.
|
173 |
+
init_gain (float) -- scaling factor for normal, xavier and orthogonal.
|
174 |
+
gpu_ids (int list) -- which GPUs the network runs on: e.g., 0,1,2
|
175 |
+
|
176 |
+
Returns a discriminator
|
177 |
+
|
178 |
+
Our current implementation provides three types of discriminators:
|
179 |
+
[basic]: 'PatchGAN' classifier described in the original pix2pix paper.
|
180 |
+
It can classify whether 70×70 overlapping patches are real or fake.
|
181 |
+
Such a patch-level discriminator architecture has fewer parameters
|
182 |
+
than a full-image discriminator and can work on arbitrarily-sized images
|
183 |
+
in a fully convolutional fashion.
|
184 |
+
|
185 |
+
[n_layers]: With this mode, you can specify the number of conv layers in the discriminator
|
186 |
+
with the parameter <n_layers_D> (default=3 as used in [basic] (PatchGAN).)
|
187 |
+
|
188 |
+
[pixel]: 1x1 PixelGAN discriminator can classify whether a pixel is real or not.
|
189 |
+
It encourages greater color diversity but has no effect on spatial statistics.
|
190 |
+
|
191 |
+
The discriminator has been initialized by <init_net>. It uses Leakly RELU for non-linearity.
|
192 |
+
"""
|
193 |
+
net = None
|
194 |
+
norm_layer = get_norm_layer(norm_type=norm)
|
195 |
+
|
196 |
+
if netD == 'basic': # default PatchGAN classifier
|
197 |
+
net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer)
|
198 |
+
elif netD == 'n_layers': # more options
|
199 |
+
net = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer)
|
200 |
+
elif netD == 'pixel': # classify if each pixel is real or fake
|
201 |
+
net = PixelDiscriminator(input_nc, ndf, norm_layer=norm_layer)
|
202 |
+
else:
|
203 |
+
raise NotImplementedError('Discriminator model name [%s] is not recognized' % netD)
|
204 |
+
return init_net(net, init_type, init_gain, gpu_ids)
|
205 |
+
|
206 |
+
|
207 |
+
##############################################################################
|
208 |
+
# Classes
|
209 |
+
##############################################################################
|
210 |
+
class GANLoss(nn.Module):
|
211 |
+
"""Define different GAN objectives.
|
212 |
+
|
213 |
+
The GANLoss class abstracts away the need to create the target label tensor
|
214 |
+
that has the same size as the input.
|
215 |
+
"""
|
216 |
+
|
217 |
+
def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
|
218 |
+
""" Initialize the GANLoss class.
|
219 |
+
|
220 |
+
Parameters:
|
221 |
+
gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.
|
222 |
+
target_real_label (bool) - - label for a real image
|
223 |
+
target_fake_label (bool) - - label of a fake image
|
224 |
+
|
225 |
+
Note: Do not use sigmoid as the last layer of Discriminator.
|
226 |
+
LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.
|
227 |
+
"""
|
228 |
+
super(GANLoss, self).__init__()
|
229 |
+
self.register_buffer('real_label', torch.tensor(target_real_label))
|
230 |
+
self.register_buffer('fake_label', torch.tensor(target_fake_label))
|
231 |
+
self.gan_mode = gan_mode
|
232 |
+
if gan_mode == 'lsgan':
|
233 |
+
self.loss = nn.MSELoss()
|
234 |
+
elif gan_mode == 'vanilla':
|
235 |
+
self.loss = nn.BCEWithLogitsLoss()
|
236 |
+
elif gan_mode in ['wgangp']:
|
237 |
+
self.loss = None
|
238 |
+
else:
|
239 |
+
raise NotImplementedError('gan mode %s not implemented' % gan_mode)
|
240 |
+
|
241 |
+
def get_target_tensor(self, prediction, target_is_real):
|
242 |
+
"""Create label tensors with the same size as the input.
|
243 |
+
|
244 |
+
Parameters:
|
245 |
+
prediction (tensor) - - tpyically the prediction from a discriminator
|
246 |
+
target_is_real (bool) - - if the ground truth label is for real images or fake images
|
247 |
+
|
248 |
+
Returns:
|
249 |
+
A label tensor filled with ground truth label, and with the size of the input
|
250 |
+
"""
|
251 |
+
|
252 |
+
if target_is_real:
|
253 |
+
target_tensor = self.real_label
|
254 |
+
else:
|
255 |
+
target_tensor = self.fake_label
|
256 |
+
return target_tensor.expand_as(prediction)
|
257 |
+
|
258 |
+
def __call__(self, prediction, target_is_real):
|
259 |
+
"""Calculate loss given Discriminator's output and grount truth labels.
|
260 |
+
|
261 |
+
Parameters:
|
262 |
+
prediction (tensor) - - tpyically the prediction output from a discriminator
|
263 |
+
target_is_real (bool) - - if the ground truth label is for real images or fake images
|
264 |
+
|
265 |
+
Returns:
|
266 |
+
the calculated loss.
|
267 |
+
"""
|
268 |
+
if self.gan_mode in ['lsgan', 'vanilla']:
|
269 |
+
target_tensor = self.get_target_tensor(prediction, target_is_real)
|
270 |
+
loss = self.loss(prediction, target_tensor)
|
271 |
+
elif self.gan_mode == 'wgangp':
|
272 |
+
if target_is_real:
|
273 |
+
loss = -prediction.mean()
|
274 |
+
else:
|
275 |
+
loss = prediction.mean()
|
276 |
+
return loss
|
277 |
+
|
278 |
+
|
279 |
+
def cal_gradient_penalty(netD, real_data, fake_data, device, type='mixed', constant=1.0, lambda_gp=10.0):
|
280 |
+
"""Calculate the gradient penalty loss, used in WGAN-GP paper https://arxiv.org/abs/1704.00028
|
281 |
+
|
282 |
+
Arguments:
|
283 |
+
netD (network) -- discriminator network
|
284 |
+
real_data (tensor array) -- real images
|
285 |
+
fake_data (tensor array) -- generated images from the generator
|
286 |
+
device (str) -- GPU / CPU: from torch.device('cuda:{}'.format(self.gpu_ids[0])) if self.gpu_ids else torch.device('cpu')
|
287 |
+
type (str) -- if we mix real and fake data or not [real | fake | mixed].
|
288 |
+
constant (float) -- the constant used in formula ( ||gradient||_2 - constant)^2
|
289 |
+
lambda_gp (float) -- weight for this loss
|
290 |
+
|
291 |
+
Returns the gradient penalty loss
|
292 |
+
"""
|
293 |
+
if lambda_gp > 0.0:
|
294 |
+
if type == 'real': # either use real images, fake images, or a linear interpolation of two.
|
295 |
+
interpolatesv = real_data
|
296 |
+
elif type == 'fake':
|
297 |
+
interpolatesv = fake_data
|
298 |
+
elif type == 'mixed':
|
299 |
+
alpha = torch.rand(real_data.shape[0], 1, device=device)
|
300 |
+
alpha = alpha.expand(real_data.shape[0], real_data.nelement() // real_data.shape[0]).contiguous().view(*real_data.shape)
|
301 |
+
interpolatesv = alpha * real_data + ((1 - alpha) * fake_data)
|
302 |
+
else:
|
303 |
+
raise NotImplementedError('{} not implemented'.format(type))
|
304 |
+
interpolatesv.requires_grad_(True)
|
305 |
+
disc_interpolates = netD(interpolatesv)
|
306 |
+
gradients = torch.autograd.grad(outputs=disc_interpolates, inputs=interpolatesv,
|
307 |
+
grad_outputs=torch.ones(disc_interpolates.size()).to(device),
|
308 |
+
create_graph=True, retain_graph=True, only_inputs=True)
|
309 |
+
gradients = gradients[0].view(real_data.size(0), -1) # flat the data
|
310 |
+
gradient_penalty = (((gradients + 1e-16).norm(2, dim=1) - constant) ** 2).mean() * lambda_gp # added eps
|
311 |
+
return gradient_penalty, gradients
|
312 |
+
else:
|
313 |
+
return 0.0, None
|
314 |
+
|
315 |
+
|
316 |
+
class ResnetGenerator(nn.Module):
|
317 |
+
"""Resnet-based generator that consists of Resnet blocks between a few downsampling/upsampling operations.
|
318 |
+
|
319 |
+
We adapt Torch code and idea from Justin Johnson's neural style transfer project(https://github.com/jcjohnson/fast-neural-style)
|
320 |
+
"""
|
321 |
+
|
322 |
+
def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'):
|
323 |
+
"""Construct a Resnet-based generator
|
324 |
+
|
325 |
+
Parameters:
|
326 |
+
input_nc (int) -- the number of channels in input images
|
327 |
+
output_nc (int) -- the number of channels in output images
|
328 |
+
ngf (int) -- the number of filters in the last conv layer
|
329 |
+
norm_layer -- normalization layer
|
330 |
+
use_dropout (bool) -- if use dropout layers
|
331 |
+
n_blocks (int) -- the number of ResNet blocks
|
332 |
+
padding_type (str) -- the name of padding layer in conv layers: reflect | replicate | zero
|
333 |
+
"""
|
334 |
+
assert(n_blocks >= 0)
|
335 |
+
super(ResnetGenerator, self).__init__()
|
336 |
+
if type(norm_layer) == functools.partial:
|
337 |
+
use_bias = norm_layer.func == nn.InstanceNorm2d
|
338 |
+
else:
|
339 |
+
use_bias = norm_layer == nn.InstanceNorm2d
|
340 |
+
|
341 |
+
model = [nn.ReflectionPad2d(3),
|
342 |
+
nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0, bias=use_bias),
|
343 |
+
norm_layer(ngf),
|
344 |
+
nn.ReLU(True)]
|
345 |
+
|
346 |
+
n_downsampling = 2
|
347 |
+
for i in range(n_downsampling): # add downsampling layers
|
348 |
+
mult = 2 ** i
|
349 |
+
model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3, stride=2, padding=1, bias=use_bias),
|
350 |
+
norm_layer(ngf * mult * 2),
|
351 |
+
nn.ReLU(True)]
|
352 |
+
|
353 |
+
mult = 2 ** n_downsampling
|
354 |
+
for i in range(n_blocks): # add ResNet blocks
|
355 |
+
|
356 |
+
model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]
|
357 |
+
|
358 |
+
for i in range(n_downsampling): # add upsampling layers
|
359 |
+
mult = 2 ** (n_downsampling - i)
|
360 |
+
model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),
|
361 |
+
kernel_size=3, stride=2,
|
362 |
+
padding=1, output_padding=1,
|
363 |
+
bias=use_bias),
|
364 |
+
norm_layer(int(ngf * mult / 2)),
|
365 |
+
nn.ReLU(True)]
|
366 |
+
model += [nn.ReflectionPad2d(3)]
|
367 |
+
model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]
|
368 |
+
model += [nn.Tanh()]
|
369 |
+
|
370 |
+
self.model = nn.Sequential(*model)
|
371 |
+
|
372 |
+
def forward(self, input):
|
373 |
+
"""Standard forward"""
|
374 |
+
return self.model(input)
|
375 |
+
|
376 |
+
|
377 |
+
class ResnetBlock(nn.Module):
|
378 |
+
"""Define a Resnet block"""
|
379 |
+
|
380 |
+
def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):
|
381 |
+
"""Initialize the Resnet block
|
382 |
+
|
383 |
+
A resnet block is a conv block with skip connections
|
384 |
+
We construct a conv block with build_conv_block function,
|
385 |
+
and implement skip connections in <forward> function.
|
386 |
+
Original Resnet paper: https://arxiv.org/pdf/1512.03385.pdf
|
387 |
+
"""
|
388 |
+
super(ResnetBlock, self).__init__()
|
389 |
+
self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)
|
390 |
+
|
391 |
+
def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias):
|
392 |
+
"""Construct a convolutional block.
|
393 |
+
|
394 |
+
Parameters:
|
395 |
+
dim (int) -- the number of channels in the conv layer.
|
396 |
+
padding_type (str) -- the name of padding layer: reflect | replicate | zero
|
397 |
+
norm_layer -- normalization layer
|
398 |
+
use_dropout (bool) -- if use dropout layers.
|
399 |
+
use_bias (bool) -- if the conv layer uses bias or not
|
400 |
+
|
401 |
+
Returns a conv block (with a conv layer, a normalization layer, and a non-linearity layer (ReLU))
|
402 |
+
"""
|
403 |
+
conv_block = []
|
404 |
+
p = 0
|
405 |
+
if padding_type == 'reflect':
|
406 |
+
conv_block += [nn.ReflectionPad2d(1)]
|
407 |
+
elif padding_type == 'replicate':
|
408 |
+
conv_block += [nn.ReplicationPad2d(1)]
|
409 |
+
elif padding_type == 'zero':
|
410 |
+
p = 1
|
411 |
+
else:
|
412 |
+
raise NotImplementedError('padding [%s] is not implemented' % padding_type)
|
413 |
+
|
414 |
+
conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim), nn.ReLU(True)]
|
415 |
+
if use_dropout:
|
416 |
+
conv_block += [nn.Dropout(0.5)]
|
417 |
+
|
418 |
+
p = 0
|
419 |
+
if padding_type == 'reflect':
|
420 |
+
conv_block += [nn.ReflectionPad2d(1)]
|
421 |
+
elif padding_type == 'replicate':
|
422 |
+
conv_block += [nn.ReplicationPad2d(1)]
|
423 |
+
elif padding_type == 'zero':
|
424 |
+
p = 1
|
425 |
+
else:
|
426 |
+
raise NotImplementedError('padding [%s] is not implemented' % padding_type)
|
427 |
+
conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias), norm_layer(dim)]
|
428 |
+
|
429 |
+
return nn.Sequential(*conv_block)
|
430 |
+
|
431 |
+
def forward(self, x):
|
432 |
+
"""Forward function (with skip connections)"""
|
433 |
+
out = x + self.conv_block(x) # add skip connections
|
434 |
+
return out
|
435 |
+
|
436 |
+
|
437 |
+
class UnetGenerator(nn.Module):
|
438 |
+
"""Create a Unet-based generator"""
|
439 |
+
|
440 |
+
def __init__(self, input_nc, output_nc, num_downs, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False):
|
441 |
+
"""Construct a Unet generator
|
442 |
+
Parameters:
|
443 |
+
input_nc (int) -- the number of channels in input images
|
444 |
+
output_nc (int) -- the number of channels in output images
|
445 |
+
num_downs (int) -- the number of downsamplings in UNet. For example, # if |num_downs| == 7,
|
446 |
+
image of size 128x128 will become of size 1x1 # at the bottleneck
|
447 |
+
ngf (int) -- the number of filters in the last conv layer
|
448 |
+
norm_layer -- normalization layer
|
449 |
+
|
450 |
+
We construct the U-Net from the innermost layer to the outermost layer.
|
451 |
+
It is a recursive process.
|
452 |
+
"""
|
453 |
+
super(UnetGenerator, self).__init__()
|
454 |
+
# construct unet structure
|
455 |
+
unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True) # add the innermost layer
|
456 |
+
for i in range(num_downs - 5): # add intermediate layers with ngf * 8 filters
|
457 |
+
unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout)
|
458 |
+
# gradually reduce the number of filters from ngf * 8 to ngf
|
459 |
+
unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer)
|
460 |
+
unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer)
|
461 |
+
unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)
|
462 |
+
self.model = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer) # add the outermost layer
|
463 |
+
|
464 |
+
def forward(self, input):
|
465 |
+
"""Standard forward"""
|
466 |
+
return self.model(input)
|
467 |
+
|
468 |
+
|
469 |
+
class UnetSkipConnectionBlock(nn.Module):
|
470 |
+
"""Defines the Unet submodule with skip connection.
|
471 |
+
X -------------------identity----------------------
|
472 |
+
|-- downsampling -- |submodule| -- upsampling --|
|
473 |
+
"""
|
474 |
+
|
475 |
+
def __init__(self, outer_nc, inner_nc, input_nc=None,
|
476 |
+
submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):
|
477 |
+
"""Construct a Unet submodule with skip connections.
|
478 |
+
|
479 |
+
Parameters:
|
480 |
+
outer_nc (int) -- the number of filters in the outer conv layer
|
481 |
+
inner_nc (int) -- the number of filters in the inner conv layer
|
482 |
+
input_nc (int) -- the number of channels in input images/features
|
483 |
+
submodule (UnetSkipConnectionBlock) -- previously defined submodules
|
484 |
+
outermost (bool) -- if this module is the outermost module
|
485 |
+
innermost (bool) -- if this module is the innermost module
|
486 |
+
norm_layer -- normalization layer
|
487 |
+
use_dropout (bool) -- if use dropout layers.
|
488 |
+
"""
|
489 |
+
super(UnetSkipConnectionBlock, self).__init__()
|
490 |
+
self.outermost = outermost
|
491 |
+
if type(norm_layer) == functools.partial:
|
492 |
+
use_bias = norm_layer.func == nn.InstanceNorm2d
|
493 |
+
else:
|
494 |
+
use_bias = norm_layer == nn.InstanceNorm2d
|
495 |
+
if input_nc is None:
|
496 |
+
input_nc = outer_nc
|
497 |
+
downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,
|
498 |
+
stride=2, padding=1, bias=use_bias)
|
499 |
+
downrelu = nn.LeakyReLU(0.2, True)
|
500 |
+
downnorm = norm_layer(inner_nc)
|
501 |
+
uprelu = nn.ReLU(True)
|
502 |
+
upnorm = norm_layer(outer_nc)
|
503 |
+
|
504 |
+
if outermost:
|
505 |
+
upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,
|
506 |
+
kernel_size=4, stride=2,
|
507 |
+
padding=1)
|
508 |
+
down = [downconv]
|
509 |
+
up = [uprelu, upconv, nn.Tanh()]
|
510 |
+
model = down + [submodule] + up
|
511 |
+
elif innermost:
|
512 |
+
upconv = nn.ConvTranspose2d(inner_nc, outer_nc,
|
513 |
+
kernel_size=4, stride=2,
|
514 |
+
padding=1, bias=use_bias)
|
515 |
+
down = [downrelu, downconv]
|
516 |
+
up = [uprelu, upconv, upnorm]
|
517 |
+
model = down + up
|
518 |
+
else:
|
519 |
+
upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,
|
520 |
+
kernel_size=4, stride=2,
|
521 |
+
padding=1, bias=use_bias)
|
522 |
+
down = [downrelu, downconv, downnorm]
|
523 |
+
up = [uprelu, upconv, upnorm]
|
524 |
+
|
525 |
+
if use_dropout:
|
526 |
+
model = down + [submodule] + up + [nn.Dropout(0.5)]
|
527 |
+
else:
|
528 |
+
model = down + [submodule] + up
|
529 |
+
|
530 |
+
self.model = nn.Sequential(*model)
|
531 |
+
|
532 |
+
def forward(self, x):
|
533 |
+
if self.outermost:
|
534 |
+
return self.model(x)
|
535 |
+
else: # add skip connections
|
536 |
+
return torch.cat([x, self.model(x)], 1)
|
537 |
+
|
538 |
+
|
539 |
+
class NLayerDiscriminator(nn.Module):
|
540 |
+
"""Defines a PatchGAN discriminator"""
|
541 |
+
|
542 |
+
def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):
|
543 |
+
"""Construct a PatchGAN discriminator
|
544 |
+
|
545 |
+
Parameters:
|
546 |
+
input_nc (int) -- the number of channels in input images
|
547 |
+
ndf (int) -- the number of filters in the last conv layer
|
548 |
+
n_layers (int) -- the number of conv layers in the discriminator
|
549 |
+
norm_layer -- normalization layer
|
550 |
+
"""
|
551 |
+
super(NLayerDiscriminator, self).__init__()
|
552 |
+
if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters
|
553 |
+
use_bias = norm_layer.func == nn.InstanceNorm2d
|
554 |
+
else:
|
555 |
+
use_bias = norm_layer == nn.InstanceNorm2d
|
556 |
+
|
557 |
+
kw = 4
|
558 |
+
padw = 1
|
559 |
+
sequence = [nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]
|
560 |
+
nf_mult = 1
|
561 |
+
nf_mult_prev = 1
|
562 |
+
for n in range(1, n_layers): # gradually increase the number of filters
|
563 |
+
nf_mult_prev = nf_mult
|
564 |
+
nf_mult = min(2 ** n, 8)
|
565 |
+
sequence += [
|
566 |
+
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),
|
567 |
+
norm_layer(ndf * nf_mult),
|
568 |
+
nn.LeakyReLU(0.2, True)
|
569 |
+
]
|
570 |
+
|
571 |
+
nf_mult_prev = nf_mult
|
572 |
+
nf_mult = min(2 ** n_layers, 8)
|
573 |
+
sequence += [
|
574 |
+
nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),
|
575 |
+
norm_layer(ndf * nf_mult),
|
576 |
+
nn.LeakyReLU(0.2, True)
|
577 |
+
]
|
578 |
+
|
579 |
+
sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)] # output 1 channel prediction map
|
580 |
+
self.model = nn.Sequential(*sequence)
|
581 |
+
|
582 |
+
def forward(self, input):
|
583 |
+
"""Standard forward."""
|
584 |
+
return self.model(input)
|
585 |
+
|
586 |
+
|
587 |
+
class PixelDiscriminator(nn.Module):
|
588 |
+
"""Defines a 1x1 PatchGAN discriminator (pixelGAN)"""
|
589 |
+
|
590 |
+
def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d):
|
591 |
+
"""Construct a 1x1 PatchGAN discriminator
|
592 |
+
|
593 |
+
Parameters:
|
594 |
+
input_nc (int) -- the number of channels in input images
|
595 |
+
ndf (int) -- the number of filters in the last conv layer
|
596 |
+
norm_layer -- normalization layer
|
597 |
+
"""
|
598 |
+
super(PixelDiscriminator, self).__init__()
|
599 |
+
if type(norm_layer) == functools.partial: # no need to use bias as BatchNorm2d has affine parameters
|
600 |
+
use_bias = norm_layer.func == nn.InstanceNorm2d
|
601 |
+
else:
|
602 |
+
use_bias = norm_layer == nn.InstanceNorm2d
|
603 |
+
|
604 |
+
self.net = [
|
605 |
+
nn.Conv2d(input_nc, ndf, kernel_size=1, stride=1, padding=0),
|
606 |
+
nn.LeakyReLU(0.2, True),
|
607 |
+
nn.Conv2d(ndf, ndf * 2, kernel_size=1, stride=1, padding=0, bias=use_bias),
|
608 |
+
norm_layer(ndf * 2),
|
609 |
+
nn.LeakyReLU(0.2, True),
|
610 |
+
nn.Conv2d(ndf * 2, 1, kernel_size=1, stride=1, padding=0, bias=use_bias)]
|
611 |
+
|
612 |
+
self.net = nn.Sequential(*self.net)
|
613 |
+
|
614 |
+
def forward(self, input):
|
615 |
+
"""Standard forward."""
|
616 |
+
return self.net(input)
|
models/pix2pix_model.py
ADDED
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from .base_model import BaseModel
|
3 |
+
from . import networks
|
4 |
+
|
5 |
+
|
6 |
+
class Pix2PixModel(BaseModel):
|
7 |
+
""" This class implements the pix2pix model, for learning a mapping from input images to output images given paired data.
|
8 |
+
|
9 |
+
The model training requires '--dataset_mode aligned' dataset.
|
10 |
+
By default, it uses a '--netG unet256' U-Net generator,
|
11 |
+
a '--netD basic' discriminator (PatchGAN),
|
12 |
+
and a '--gan_mode' vanilla GAN loss (the cross-entropy objective used in the orignal GAN paper).
|
13 |
+
|
14 |
+
pix2pix paper: https://arxiv.org/pdf/1611.07004.pdf
|
15 |
+
"""
|
16 |
+
@staticmethod
|
17 |
+
def modify_commandline_options(parser, is_train=True):
|
18 |
+
"""Add new dataset-specific options, and rewrite default values for existing options.
|
19 |
+
|
20 |
+
Parameters:
|
21 |
+
parser -- original option parser
|
22 |
+
is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.
|
23 |
+
|
24 |
+
Returns:
|
25 |
+
the modified parser.
|
26 |
+
|
27 |
+
For pix2pix, we do not use image buffer
|
28 |
+
The training objective is: GAN Loss + lambda_L1 * ||G(A)-B||_1
|
29 |
+
By default, we use vanilla GAN loss, UNet with batchnorm, and aligned datasets.
|
30 |
+
"""
|
31 |
+
# changing the default values to match the pix2pix paper (https://phillipi.github.io/pix2pix/)
|
32 |
+
parser.set_defaults(norm='batch', netG='unet_256', dataset_mode='aligned')
|
33 |
+
if is_train:
|
34 |
+
parser.set_defaults(pool_size=0, gan_mode='vanilla')
|
35 |
+
parser.add_argument('--lambda_L1', type=float, default=100.0, help='weight for L1 loss')
|
36 |
+
|
37 |
+
return parser
|
38 |
+
|
39 |
+
def __init__(self, opt):
|
40 |
+
"""Initialize the pix2pix class.
|
41 |
+
|
42 |
+
Parameters:
|
43 |
+
opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
|
44 |
+
"""
|
45 |
+
BaseModel.__init__(self, opt)
|
46 |
+
# specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses>
|
47 |
+
self.loss_names = ['G_GAN', 'G_L1', 'D_real', 'D_fake']
|
48 |
+
# specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals>
|
49 |
+
self.visual_names = ['real_A', 'fake_B', 'real_B']
|
50 |
+
# specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>
|
51 |
+
if self.isTrain:
|
52 |
+
self.model_names = ['G', 'D']
|
53 |
+
else: # during test time, only load G
|
54 |
+
self.model_names = ['G']
|
55 |
+
# define networks (both generator and discriminator)
|
56 |
+
self.netG = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, opt.norm,
|
57 |
+
not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids)
|
58 |
+
|
59 |
+
if self.isTrain: # define a discriminator; conditional GANs need to take both input and output images; Therefore, #channels for D is input_nc + output_nc
|
60 |
+
self.netD = networks.define_D(opt.input_nc + opt.output_nc, opt.ndf, opt.netD,
|
61 |
+
opt.n_layers_D, opt.norm, opt.init_type, opt.init_gain, self.gpu_ids)
|
62 |
+
|
63 |
+
if self.isTrain:
|
64 |
+
# define loss functions
|
65 |
+
self.criterionGAN = networks.GANLoss(opt.gan_mode).to(self.device)
|
66 |
+
self.criterionL1 = torch.nn.L1Loss()
|
67 |
+
# initialize optimizers; schedulers will be automatically created by function <BaseModel.setup>.
|
68 |
+
self.optimizer_G = torch.optim.Adam(self.netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))
|
69 |
+
self.optimizer_D = torch.optim.Adam(self.netD.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))
|
70 |
+
self.optimizers.append(self.optimizer_G)
|
71 |
+
self.optimizers.append(self.optimizer_D)
|
72 |
+
|
73 |
+
def set_input(self, input):
|
74 |
+
"""Unpack input data from the dataloader and perform necessary pre-processing steps.
|
75 |
+
|
76 |
+
Parameters:
|
77 |
+
input (dict): include the data itself and its metadata information.
|
78 |
+
|
79 |
+
The option 'direction' can be used to swap images in domain A and domain B.
|
80 |
+
"""
|
81 |
+
AtoB = self.opt.direction == 'AtoB'
|
82 |
+
self.real_A = input['A' if AtoB else 'B'].to(self.device)
|
83 |
+
self.real_B = input['B' if AtoB else 'A'].to(self.device)
|
84 |
+
self.image_paths = input['A_paths' if AtoB else 'B_paths']
|
85 |
+
|
86 |
+
def forward(self):
|
87 |
+
"""Run forward pass; called by both functions <optimize_parameters> and <test>."""
|
88 |
+
self.fake_B = self.netG(self.real_A) # G(A)
|
89 |
+
|
90 |
+
def backward_D(self):
|
91 |
+
"""Calculate GAN loss for the discriminator"""
|
92 |
+
# Fake; stop backprop to the generator by detaching fake_B
|
93 |
+
fake_AB = torch.cat((self.real_A, self.fake_B), 1) # we use conditional GANs; we need to feed both input and output to the discriminator
|
94 |
+
pred_fake = self.netD(fake_AB.detach())
|
95 |
+
self.loss_D_fake = self.criterionGAN(pred_fake, False)
|
96 |
+
# Real
|
97 |
+
real_AB = torch.cat((self.real_A, self.real_B), 1)
|
98 |
+
pred_real = self.netD(real_AB)
|
99 |
+
self.loss_D_real = self.criterionGAN(pred_real, True)
|
100 |
+
# combine loss and calculate gradients
|
101 |
+
self.loss_D = (self.loss_D_fake + self.loss_D_real) * 0.5
|
102 |
+
self.loss_D.backward()
|
103 |
+
|
104 |
+
def backward_G(self):
|
105 |
+
"""Calculate GAN and L1 loss for the generator"""
|
106 |
+
# First, G(A) should fake the discriminator
|
107 |
+
fake_AB = torch.cat((self.real_A, self.fake_B), 1)
|
108 |
+
pred_fake = self.netD(fake_AB)
|
109 |
+
self.loss_G_GAN = self.criterionGAN(pred_fake, True)
|
110 |
+
# Second, G(A) = B
|
111 |
+
self.loss_G_L1 = self.criterionL1(self.fake_B, self.real_B) * self.opt.lambda_L1
|
112 |
+
# combine loss and calculate gradients
|
113 |
+
self.loss_G = self.loss_G_GAN + self.loss_G_L1
|
114 |
+
self.loss_G.backward()
|
115 |
+
|
116 |
+
def optimize_parameters(self):
|
117 |
+
self.forward() # compute fake images: G(A)
|
118 |
+
# update D
|
119 |
+
self.set_requires_grad(self.netD, True) # enable backprop for D
|
120 |
+
self.optimizer_D.zero_grad() # set D's gradients to zero
|
121 |
+
self.backward_D() # calculate gradients for D
|
122 |
+
self.optimizer_D.step() # update D's weights
|
123 |
+
# update G
|
124 |
+
self.set_requires_grad(self.netD, False) # D requires no gradients when optimizing G
|
125 |
+
self.optimizer_G.zero_grad() # set G's gradients to zero
|
126 |
+
self.backward_G() # calculate graidents for G
|
127 |
+
self.optimizer_G.step() # update G's weights
|
models/template_model.py
ADDED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""Model class template
|
2 |
+
|
3 |
+
This module provides a template for users to implement custom models.
|
4 |
+
You can specify '--model template' to use this model.
|
5 |
+
The class name should be consistent with both the filename and its model option.
|
6 |
+
The filename should be <model>_dataset.py
|
7 |
+
The class name should be <Model>Dataset.py
|
8 |
+
It implements a simple image-to-image translation baseline based on regression loss.
|
9 |
+
Given input-output pairs (data_A, data_B), it learns a network netG that can minimize the following L1 loss:
|
10 |
+
min_<netG> ||netG(data_A) - data_B||_1
|
11 |
+
You need to implement the following functions:
|
12 |
+
<modify_commandline_options>: Add model-specific options and rewrite default values for existing options.
|
13 |
+
<__init__>: Initialize this model class.
|
14 |
+
<set_input>: Unpack input data and perform data pre-processing.
|
15 |
+
<forward>: Run forward pass. This will be called by both <optimize_parameters> and <test>.
|
16 |
+
<optimize_parameters>: Update network weights; it will be called in every training iteration.
|
17 |
+
"""
|
18 |
+
import torch
|
19 |
+
from .base_model import BaseModel
|
20 |
+
from . import networks
|
21 |
+
|
22 |
+
|
23 |
+
class TemplateModel(BaseModel):
|
24 |
+
@staticmethod
|
25 |
+
def modify_commandline_options(parser, is_train=True):
|
26 |
+
"""Add new model-specific options and rewrite default values for existing options.
|
27 |
+
|
28 |
+
Parameters:
|
29 |
+
parser -- the option parser
|
30 |
+
is_train -- if it is training phase or test phase. You can use this flag to add training-specific or test-specific options.
|
31 |
+
|
32 |
+
Returns:
|
33 |
+
the modified parser.
|
34 |
+
"""
|
35 |
+
parser.set_defaults(dataset_mode='aligned') # You can rewrite default values for this model. For example, this model usually uses aligned dataset as its dataset.
|
36 |
+
if is_train:
|
37 |
+
parser.add_argument('--lambda_regression', type=float, default=1.0, help='weight for the regression loss') # You can define new arguments for this model.
|
38 |
+
|
39 |
+
return parser
|
40 |
+
|
41 |
+
def __init__(self, opt):
|
42 |
+
"""Initialize this model class.
|
43 |
+
|
44 |
+
Parameters:
|
45 |
+
opt -- training/test options
|
46 |
+
|
47 |
+
A few things can be done here.
|
48 |
+
- (required) call the initialization function of BaseModel
|
49 |
+
- define loss function, visualization images, model names, and optimizers
|
50 |
+
"""
|
51 |
+
BaseModel.__init__(self, opt) # call the initialization method of BaseModel
|
52 |
+
# specify the training losses you want to print out. The program will call base_model.get_current_losses to plot the losses to the console and save them to the disk.
|
53 |
+
self.loss_names = ['loss_G']
|
54 |
+
# specify the images you want to save and display. The program will call base_model.get_current_visuals to save and display these images.
|
55 |
+
self.visual_names = ['data_A', 'data_B', 'output']
|
56 |
+
# specify the models you want to save to the disk. The program will call base_model.save_networks and base_model.load_networks to save and load networks.
|
57 |
+
# you can use opt.isTrain to specify different behaviors for training and test. For example, some networks will not be used during test, and you don't need to load them.
|
58 |
+
self.model_names = ['G']
|
59 |
+
# define networks; you can use opt.isTrain to specify different behaviors for training and test.
|
60 |
+
self.netG = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG, gpu_ids=self.gpu_ids)
|
61 |
+
if self.isTrain: # only defined during training time
|
62 |
+
# define your loss functions. You can use losses provided by torch.nn such as torch.nn.L1Loss.
|
63 |
+
# We also provide a GANLoss class "networks.GANLoss". self.criterionGAN = networks.GANLoss().to(self.device)
|
64 |
+
self.criterionLoss = torch.nn.L1Loss()
|
65 |
+
# define and initialize optimizers. You can define one optimizer for each network.
|
66 |
+
# If two networks are updated at the same time, you can use itertools.chain to group them. See cycle_gan_model.py for an example.
|
67 |
+
self.optimizer = torch.optim.Adam(self.netG.parameters(), lr=opt.lr, betas=(opt.beta1, 0.999))
|
68 |
+
self.optimizers = [self.optimizer]
|
69 |
+
|
70 |
+
# Our program will automatically call <model.setup> to define schedulers, load networks, and print networks
|
71 |
+
|
72 |
+
def set_input(self, input):
|
73 |
+
"""Unpack input data from the dataloader and perform necessary pre-processing steps.
|
74 |
+
|
75 |
+
Parameters:
|
76 |
+
input: a dictionary that contains the data itself and its metadata information.
|
77 |
+
"""
|
78 |
+
AtoB = self.opt.direction == 'AtoB' # use <direction> to swap data_A and data_B
|
79 |
+
self.data_A = input['A' if AtoB else 'B'].to(self.device) # get image data A
|
80 |
+
self.data_B = input['B' if AtoB else 'A'].to(self.device) # get image data B
|
81 |
+
self.image_paths = input['A_paths' if AtoB else 'B_paths'] # get image paths
|
82 |
+
|
83 |
+
def forward(self):
|
84 |
+
"""Run forward pass. This will be called by both functions <optimize_parameters> and <test>."""
|
85 |
+
self.output = self.netG(self.data_A) # generate output image given the input data_A
|
86 |
+
|
87 |
+
def backward(self):
|
88 |
+
"""Calculate losses, gradients, and update network weights; called in every training iteration"""
|
89 |
+
# caculate the intermediate results if necessary; here self.output has been computed during function <forward>
|
90 |
+
# calculate loss given the input and intermediate results
|
91 |
+
self.loss_G = self.criterionLoss(self.output, self.data_B) * self.opt.lambda_regression
|
92 |
+
self.loss_G.backward() # calculate gradients of network G w.r.t. loss_G
|
93 |
+
|
94 |
+
def optimize_parameters(self):
|
95 |
+
"""Update network weights; it will be called in every training iteration."""
|
96 |
+
self.forward() # first call forward to calculate intermediate results
|
97 |
+
self.optimizer.zero_grad() # clear network G's existing gradients
|
98 |
+
self.backward() # calculate gradients for network G
|
99 |
+
self.optimizer.step() # update gradients for network G
|
models/test_model.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .base_model import BaseModel
|
2 |
+
from . import networks
|
3 |
+
|
4 |
+
|
5 |
+
class TestModel(BaseModel):
|
6 |
+
""" This TesteModel can be used to generate CycleGAN results for only one direction.
|
7 |
+
This model will automatically set '--dataset_mode single', which only loads the images from one collection.
|
8 |
+
|
9 |
+
See the test instruction for more details.
|
10 |
+
"""
|
11 |
+
@staticmethod
|
12 |
+
def modify_commandline_options(parser, is_train=True):
|
13 |
+
"""Add new dataset-specific options, and rewrite default values for existing options.
|
14 |
+
|
15 |
+
Parameters:
|
16 |
+
parser -- original option parser
|
17 |
+
is_train (bool) -- whether training phase or test phase. You can use this flag to add training-specific or test-specific options.
|
18 |
+
|
19 |
+
Returns:
|
20 |
+
the modified parser.
|
21 |
+
|
22 |
+
The model can only be used during test time. It requires '--dataset_mode single'.
|
23 |
+
You need to specify the network using the option '--model_suffix'.
|
24 |
+
"""
|
25 |
+
assert not is_train, 'TestModel cannot be used during training time'
|
26 |
+
parser.set_defaults(dataset_mode='single')
|
27 |
+
parser.add_argument('--model_suffix', type=str, default='', help='In checkpoints_dir, [epoch]_net_G[model_suffix].pth will be loaded as the generator.')
|
28 |
+
|
29 |
+
return parser
|
30 |
+
|
31 |
+
def __init__(self, opt):
|
32 |
+
"""Initialize the pix2pix class.
|
33 |
+
|
34 |
+
Parameters:
|
35 |
+
opt (Option class)-- stores all the experiment flags; needs to be a subclass of BaseOptions
|
36 |
+
"""
|
37 |
+
assert(not opt.isTrain)
|
38 |
+
BaseModel.__init__(self, opt)
|
39 |
+
# specify the training losses you want to print out. The training/test scripts will call <BaseModel.get_current_losses>
|
40 |
+
self.loss_names = []
|
41 |
+
# specify the images you want to save/display. The training/test scripts will call <BaseModel.get_current_visuals>
|
42 |
+
self.visual_names = ['real', 'fake']
|
43 |
+
# specify the models you want to save to the disk. The training/test scripts will call <BaseModel.save_networks> and <BaseModel.load_networks>
|
44 |
+
self.model_names = ['G' + opt.model_suffix] # only generator is needed.
|
45 |
+
self.netG = networks.define_G(opt.input_nc, opt.output_nc, opt.ngf, opt.netG,
|
46 |
+
opt.norm, not opt.no_dropout, opt.init_type, opt.init_gain, self.gpu_ids)
|
47 |
+
|
48 |
+
# assigns the model to self.netG_[suffix] so that it can be loaded
|
49 |
+
# please see <BaseModel.load_networks>
|
50 |
+
setattr(self, 'netG' + opt.model_suffix, self.netG) # store netG in self.
|
51 |
+
|
52 |
+
def set_input(self, input):
|
53 |
+
"""Unpack input data from the dataloader and perform necessary pre-processing steps.
|
54 |
+
|
55 |
+
Parameters:
|
56 |
+
input: a dictionary that contains the data itself and its metadata information.
|
57 |
+
|
58 |
+
We need to use 'single_dataset' dataset mode. It only load images from one domain.
|
59 |
+
"""
|
60 |
+
self.real = input['A'].to(self.device)
|
61 |
+
self.image_paths = input['A_paths']
|
62 |
+
|
63 |
+
def forward(self):
|
64 |
+
"""Run forward pass."""
|
65 |
+
self.fake = self.netG(self.real) # G(real)
|
66 |
+
|
67 |
+
def optimize_parameters(self):
|
68 |
+
"""No optimization for test model."""
|
69 |
+
pass
|
options/__init__.py
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
"""This package options includes option modules: training options, test options, and basic options (used in both training and test)."""
|
options/base_options.py
ADDED
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
from util import util
|
4 |
+
import torch
|
5 |
+
import models
|
6 |
+
import data
|
7 |
+
|
8 |
+
|
9 |
+
class BaseOptions():
|
10 |
+
"""This class defines options used during both training and test time.
|
11 |
+
|
12 |
+
It also implements several helper functions such as parsing, printing, and saving the options.
|
13 |
+
It also gathers additional options defined in <modify_commandline_options> functions in both dataset class and model class.
|
14 |
+
"""
|
15 |
+
|
16 |
+
def __init__(self):
|
17 |
+
"""Reset the class; indicates the class hasn't been initailized"""
|
18 |
+
self.initialized = False
|
19 |
+
|
20 |
+
def initialize(self, parser):
|
21 |
+
"""Define the common options that are used in both training and test."""
|
22 |
+
# basic parameters
|
23 |
+
parser.add_argument('--dataroot', required=True, help='path to images (should have subfolders trainA, trainB, valA, valB, etc)')
|
24 |
+
parser.add_argument('--name', type=str, default='experiment_name', help='name of the experiment. It decides where to store samples and models')
|
25 |
+
parser.add_argument('--gpu_ids', type=str, default='0', help='gpu ids: e.g. 0 0,1,2, 0,2. use -1 for CPU')
|
26 |
+
parser.add_argument('--checkpoints_dir', type=str, default='./checkpoints', help='models are saved here')
|
27 |
+
# model parameters
|
28 |
+
parser.add_argument('--model', type=str, default='cycle_gan', help='chooses which model to use. [cycle_gan | pix2pix | test | colorization]')
|
29 |
+
parser.add_argument('--input_nc', type=int, default=3, help='# of input image channels: 3 for RGB and 1 for grayscale')
|
30 |
+
parser.add_argument('--output_nc', type=int, default=3, help='# of output image channels: 3 for RGB and 1 for grayscale')
|
31 |
+
parser.add_argument('--ngf', type=int, default=64, help='# of gen filters in the last conv layer')
|
32 |
+
parser.add_argument('--ndf', type=int, default=64, help='# of discrim filters in the first conv layer')
|
33 |
+
parser.add_argument('--netD', type=str, default='basic', help='specify discriminator architecture [basic | n_layers | pixel]. The basic model is a 70x70 PatchGAN. n_layers allows you to specify the layers in the discriminator')
|
34 |
+
parser.add_argument('--netG', type=str, default='resnet_9blocks', help='specify generator architecture [resnet_9blocks | resnet_6blocks | unet_256 | unet_128]')
|
35 |
+
parser.add_argument('--n_layers_D', type=int, default=3, help='only used if netD==n_layers')
|
36 |
+
parser.add_argument('--norm', type=str, default='instance', help='instance normalization or batch normalization [instance | batch | none]')
|
37 |
+
parser.add_argument('--init_type', type=str, default='normal', help='network initialization [normal | xavier | kaiming | orthogonal]')
|
38 |
+
parser.add_argument('--init_gain', type=float, default=0.02, help='scaling factor for normal, xavier and orthogonal.')
|
39 |
+
parser.add_argument('--no_dropout', action='store_true', help='no dropout for the generator')
|
40 |
+
# dataset parameters
|
41 |
+
parser.add_argument('--dataset_mode', type=str, default='unaligned', help='chooses how datasets are loaded. [unaligned | aligned | single | colorization]')
|
42 |
+
parser.add_argument('--direction', type=str, default='AtoB', help='AtoB or BtoA')
|
43 |
+
parser.add_argument('--serial_batches', action='store_true', help='if true, takes images in order to make batches, otherwise takes them randomly')
|
44 |
+
parser.add_argument('--num_threads', default=4, type=int, help='# threads for loading data')
|
45 |
+
parser.add_argument('--batch_size', type=int, default=1, help='input batch size')
|
46 |
+
parser.add_argument('--load_size', type=int, default=286, help='scale images to this size')
|
47 |
+
parser.add_argument('--crop_size', type=int, default=256, help='then crop to this size')
|
48 |
+
parser.add_argument('--max_dataset_size', type=int, default=float("inf"), help='Maximum number of samples allowed per dataset. If the dataset directory contains more than max_dataset_size, only a subset is loaded.')
|
49 |
+
parser.add_argument('--preprocess', type=str, default='resize_and_crop', help='scaling and cropping of images at load time [resize_and_crop | crop | scale_width | scale_width_and_crop | none]')
|
50 |
+
parser.add_argument('--no_flip', action='store_true', help='if specified, do not flip the images for data augmentation')
|
51 |
+
parser.add_argument('--display_winsize', type=int, default=256, help='display window size for both visdom and HTML')
|
52 |
+
# additional parameters
|
53 |
+
parser.add_argument('--epoch', type=str, default='latest', help='which epoch to load? set to latest to use latest cached model')
|
54 |
+
parser.add_argument('--load_iter', type=int, default='0', help='which iteration to load? if load_iter > 0, the code will load models by iter_[load_iter]; otherwise, the code will load models by [epoch]')
|
55 |
+
parser.add_argument('--verbose', action='store_true', help='if specified, print more debugging information')
|
56 |
+
parser.add_argument('--suffix', default='', type=str, help='customized suffix: opt.name = opt.name + suffix: e.g., {model}_{netG}_size{load_size}')
|
57 |
+
# wandb parameters
|
58 |
+
parser.add_argument('--use_wandb', action='store_true', help='if specified, then init wandb logging')
|
59 |
+
parser.add_argument('--wandb_project_name', type=str, default='CycleGAN-and-pix2pix', help='specify wandb project name')
|
60 |
+
self.initialized = True
|
61 |
+
return parser
|
62 |
+
|
63 |
+
def gather_options(self):
|
64 |
+
"""Initialize our parser with basic options(only once).
|
65 |
+
Add additional model-specific and dataset-specific options.
|
66 |
+
These options are defined in the <modify_commandline_options> function
|
67 |
+
in model and dataset classes.
|
68 |
+
"""
|
69 |
+
if not self.initialized: # check if it has been initialized
|
70 |
+
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
|
71 |
+
parser = self.initialize(parser)
|
72 |
+
|
73 |
+
# get the basic options
|
74 |
+
opt, _ = parser.parse_known_args()
|
75 |
+
|
76 |
+
# modify model-related parser options
|
77 |
+
model_name = opt.model
|
78 |
+
model_option_setter = models.get_option_setter(model_name)
|
79 |
+
parser = model_option_setter(parser, self.isTrain)
|
80 |
+
opt, _ = parser.parse_known_args() # parse again with new defaults
|
81 |
+
|
82 |
+
# modify dataset-related parser options
|
83 |
+
dataset_name = opt.dataset_mode
|
84 |
+
dataset_option_setter = data.get_option_setter(dataset_name)
|
85 |
+
parser = dataset_option_setter(parser, self.isTrain)
|
86 |
+
|
87 |
+
# save and return the parser
|
88 |
+
self.parser = parser
|
89 |
+
return parser.parse_args()
|
90 |
+
|
91 |
+
def print_options(self, opt):
|
92 |
+
"""Print and save options
|
93 |
+
|
94 |
+
It will print both current options and default values(if different).
|
95 |
+
It will save options into a text file / [checkpoints_dir] / opt.txt
|
96 |
+
"""
|
97 |
+
message = ''
|
98 |
+
message += '----------------- Options ---------------\n'
|
99 |
+
for k, v in sorted(vars(opt).items()):
|
100 |
+
comment = ''
|
101 |
+
default = self.parser.get_default(k)
|
102 |
+
if v != default:
|
103 |
+
comment = '\t[default: %s]' % str(default)
|
104 |
+
message += '{:>25}: {:<30}{}\n'.format(str(k), str(v), comment)
|
105 |
+
message += '----------------- End -------------------'
|
106 |
+
print(message)
|
107 |
+
|
108 |
+
# save to the disk
|
109 |
+
expr_dir = os.path.join(opt.checkpoints_dir, opt.name)
|
110 |
+
util.mkdirs(expr_dir)
|
111 |
+
file_name = os.path.join(expr_dir, '{}_opt.txt'.format(opt.phase))
|
112 |
+
with open(file_name, 'wt') as opt_file:
|
113 |
+
opt_file.write(message)
|
114 |
+
opt_file.write('\n')
|
115 |
+
|
116 |
+
def parse(self):
|
117 |
+
"""Parse our options, create checkpoints directory suffix, and set up gpu device."""
|
118 |
+
opt = self.gather_options()
|
119 |
+
opt.isTrain = self.isTrain # train or test
|
120 |
+
|
121 |
+
# process opt.suffix
|
122 |
+
if opt.suffix:
|
123 |
+
suffix = ('_' + opt.suffix.format(**vars(opt))) if opt.suffix != '' else ''
|
124 |
+
opt.name = opt.name + suffix
|
125 |
+
|
126 |
+
self.print_options(opt)
|
127 |
+
|
128 |
+
# set gpu ids
|
129 |
+
str_ids = opt.gpu_ids.split(',')
|
130 |
+
opt.gpu_ids = []
|
131 |
+
for str_id in str_ids:
|
132 |
+
id = int(str_id)
|
133 |
+
if id >= 0:
|
134 |
+
opt.gpu_ids.append(id)
|
135 |
+
if len(opt.gpu_ids) > 0:
|
136 |
+
torch.cuda.set_device(opt.gpu_ids[0])
|
137 |
+
|
138 |
+
self.opt = opt
|
139 |
+
return self.opt
|
options/test_options.py
ADDED
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .base_options import BaseOptions
|
2 |
+
|
3 |
+
|
4 |
+
class TestOptions(BaseOptions):
|
5 |
+
"""This class includes test options.
|
6 |
+
|
7 |
+
It also includes shared options defined in BaseOptions.
|
8 |
+
"""
|
9 |
+
|
10 |
+
def initialize(self, parser):
|
11 |
+
parser = BaseOptions.initialize(self, parser) # define shared options
|
12 |
+
parser.add_argument('--results_dir', type=str, default='./results/', help='saves results here.')
|
13 |
+
parser.add_argument('--aspect_ratio', type=float, default=1.0, help='aspect ratio of result images')
|
14 |
+
parser.add_argument('--phase', type=str, default='test', help='train, val, test, etc')
|
15 |
+
# Dropout and Batchnorm has different behavioir during training and test.
|
16 |
+
parser.add_argument('--eval', action='store_true', help='use eval mode during test time.')
|
17 |
+
parser.add_argument('--num_test', type=int, default=50, help='how many test images to run')
|
18 |
+
# rewrite devalue values
|
19 |
+
parser.set_defaults(model='test')
|
20 |
+
# To avoid cropping, the load_size should be the same as crop_size
|
21 |
+
parser.set_defaults(load_size=parser.get_default('crop_size'))
|
22 |
+
self.isTrain = False
|
23 |
+
return parser
|
options/train_options.py
ADDED
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .base_options import BaseOptions
|
2 |
+
|
3 |
+
|
4 |
+
class TrainOptions(BaseOptions):
|
5 |
+
"""This class includes training options.
|
6 |
+
|
7 |
+
It also includes shared options defined in BaseOptions.
|
8 |
+
"""
|
9 |
+
|
10 |
+
def initialize(self, parser):
|
11 |
+
parser = BaseOptions.initialize(self, parser)
|
12 |
+
# visdom and HTML visualization parameters
|
13 |
+
parser.add_argument('--display_freq', type=int, default=400, help='frequency of showing training results on screen')
|
14 |
+
parser.add_argument('--display_ncols', type=int, default=4, help='if positive, display all images in a single visdom web panel with certain number of images per row.')
|
15 |
+
parser.add_argument('--display_id', type=int, default=1, help='window id of the web display')
|
16 |
+
parser.add_argument('--display_server', type=str, default="http://localhost", help='visdom server of the web display')
|
17 |
+
parser.add_argument('--display_env', type=str, default='main', help='visdom display environment name (default is "main")')
|
18 |
+
parser.add_argument('--display_port', type=int, default=8097, help='visdom port of the web display')
|
19 |
+
parser.add_argument('--update_html_freq', type=int, default=1000, help='frequency of saving training results to html')
|
20 |
+
parser.add_argument('--print_freq', type=int, default=100, help='frequency of showing training results on console')
|
21 |
+
parser.add_argument('--no_html', action='store_true', help='do not save intermediate training results to [opt.checkpoints_dir]/[opt.name]/web/')
|
22 |
+
# network saving and loading parameters
|
23 |
+
parser.add_argument('--save_latest_freq', type=int, default=5000, help='frequency of saving the latest results')
|
24 |
+
parser.add_argument('--save_epoch_freq', type=int, default=5, help='frequency of saving checkpoints at the end of epochs')
|
25 |
+
parser.add_argument('--save_by_iter', action='store_true', help='whether saves model by iteration')
|
26 |
+
parser.add_argument('--continue_train', action='store_true', help='continue training: load the latest model')
|
27 |
+
parser.add_argument('--epoch_count', type=int, default=1, help='the starting epoch count, we save the model by <epoch_count>, <epoch_count>+<save_latest_freq>, ...')
|
28 |
+
parser.add_argument('--phase', type=str, default='train', help='train, val, test, etc')
|
29 |
+
# training parameters
|
30 |
+
parser.add_argument('--n_epochs', type=int, default=100, help='number of epochs with the initial learning rate')
|
31 |
+
parser.add_argument('--n_epochs_decay', type=int, default=100, help='number of epochs to linearly decay learning rate to zero')
|
32 |
+
parser.add_argument('--beta1', type=float, default=0.5, help='momentum term of adam')
|
33 |
+
parser.add_argument('--lr', type=float, default=0.0002, help='initial learning rate for adam')
|
34 |
+
parser.add_argument('--gan_mode', type=str, default='lsgan', help='the type of GAN objective. [vanilla| lsgan | wgangp]. vanilla GAN loss is the cross-entropy objective used in the original GAN paper.')
|
35 |
+
parser.add_argument('--pool_size', type=int, default=50, help='the size of image buffer that stores previously generated images')
|
36 |
+
parser.add_argument('--lr_policy', type=str, default='linear', help='learning rate policy. [linear | step | plateau | cosine]')
|
37 |
+
parser.add_argument('--lr_decay_iters', type=int, default=50, help='multiply by a gamma every lr_decay_iters iterations')
|
38 |
+
|
39 |
+
self.isTrain = True
|
40 |
+
return parser
|
pix2pix.ipynb
ADDED
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
{
|
2 |
+
"cells": [
|
3 |
+
{
|
4 |
+
"cell_type": "markdown",
|
5 |
+
"metadata": {
|
6 |
+
"colab_type": "text",
|
7 |
+
"id": "view-in-github"
|
8 |
+
},
|
9 |
+
"source": [
|
10 |
+
"<a href=\"https://colab.research.google.com/github/bkkaggle/pytorch-CycleGAN-and-pix2pix/blob/master/pix2pix.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>"
|
11 |
+
]
|
12 |
+
},
|
13 |
+
{
|
14 |
+
"cell_type": "markdown",
|
15 |
+
"metadata": {
|
16 |
+
"colab_type": "text",
|
17 |
+
"id": "7wNjDKdQy35h"
|
18 |
+
},
|
19 |
+
"source": [
|
20 |
+
"# Install"
|
21 |
+
]
|
22 |
+
},
|
23 |
+
{
|
24 |
+
"cell_type": "code",
|
25 |
+
"execution_count": null,
|
26 |
+
"metadata": {
|
27 |
+
"colab": {},
|
28 |
+
"colab_type": "code",
|
29 |
+
"id": "TRm-USlsHgEV"
|
30 |
+
},
|
31 |
+
"outputs": [],
|
32 |
+
"source": [
|
33 |
+
"!git clone https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix"
|
34 |
+
]
|
35 |
+
},
|
36 |
+
{
|
37 |
+
"cell_type": "code",
|
38 |
+
"execution_count": null,
|
39 |
+
"metadata": {
|
40 |
+
"colab": {},
|
41 |
+
"colab_type": "code",
|
42 |
+
"id": "Pt3igws3eiVp"
|
43 |
+
},
|
44 |
+
"outputs": [],
|
45 |
+
"source": [
|
46 |
+
"import os\n",
|
47 |
+
"os.chdir('pytorch-CycleGAN-and-pix2pix/')"
|
48 |
+
]
|
49 |
+
},
|
50 |
+
{
|
51 |
+
"cell_type": "code",
|
52 |
+
"execution_count": null,
|
53 |
+
"metadata": {
|
54 |
+
"colab": {},
|
55 |
+
"colab_type": "code",
|
56 |
+
"id": "z1EySlOXwwoa"
|
57 |
+
},
|
58 |
+
"outputs": [],
|
59 |
+
"source": [
|
60 |
+
"!pip install -r requirements.txt"
|
61 |
+
]
|
62 |
+
},
|
63 |
+
{
|
64 |
+
"cell_type": "markdown",
|
65 |
+
"metadata": {
|
66 |
+
"colab_type": "text",
|
67 |
+
"id": "8daqlgVhw29P"
|
68 |
+
},
|
69 |
+
"source": [
|
70 |
+
"# Datasets\n",
|
71 |
+
"\n",
|
72 |
+
"Download one of the official datasets with:\n",
|
73 |
+
"\n",
|
74 |
+
"- `bash ./datasets/download_pix2pix_dataset.sh [cityscapes, night2day, edges2handbags, edges2shoes, facades, maps]`\n",
|
75 |
+
"\n",
|
76 |
+
"Or use your own dataset by creating the appropriate folders and adding in the images. Follow the instructions [here](https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix/blob/master/docs/datasets.md#pix2pix-datasets)."
|
77 |
+
]
|
78 |
+
},
|
79 |
+
{
|
80 |
+
"cell_type": "code",
|
81 |
+
"execution_count": null,
|
82 |
+
"metadata": {
|
83 |
+
"colab": {},
|
84 |
+
"colab_type": "code",
|
85 |
+
"id": "vrdOettJxaCc"
|
86 |
+
},
|
87 |
+
"outputs": [],
|
88 |
+
"source": [
|
89 |
+
"!bash ./datasets/download_pix2pix_dataset.sh facades"
|
90 |
+
]
|
91 |
+
},
|
92 |
+
{
|
93 |
+
"cell_type": "markdown",
|
94 |
+
"metadata": {
|
95 |
+
"colab_type": "text",
|
96 |
+
"id": "gdUz4116xhpm"
|
97 |
+
},
|
98 |
+
"source": [
|
99 |
+
"# Pretrained models\n",
|
100 |
+
"\n",
|
101 |
+
"Download one of the official pretrained models with:\n",
|
102 |
+
"\n",
|
103 |
+
"- `bash ./scripts/download_pix2pix_model.sh [edges2shoes, sat2map, map2sat, facades_label2photo, and day2night]`\n",
|
104 |
+
"\n",
|
105 |
+
"Or add your own pretrained model to `./checkpoints/{NAME}_pretrained/latest_net_G.pt`"
|
106 |
+
]
|
107 |
+
},
|
108 |
+
{
|
109 |
+
"cell_type": "code",
|
110 |
+
"execution_count": null,
|
111 |
+
"metadata": {
|
112 |
+
"colab": {},
|
113 |
+
"colab_type": "code",
|
114 |
+
"id": "GC2DEP4M0OsS"
|
115 |
+
},
|
116 |
+
"outputs": [],
|
117 |
+
"source": [
|
118 |
+
"!bash ./scripts/download_pix2pix_model.sh facades_label2photo"
|
119 |
+
]
|
120 |
+
},
|
121 |
+
{
|
122 |
+
"cell_type": "markdown",
|
123 |
+
"metadata": {
|
124 |
+
"colab_type": "text",
|
125 |
+
"id": "yFw1kDQBx3LN"
|
126 |
+
},
|
127 |
+
"source": [
|
128 |
+
"# Training\n",
|
129 |
+
"\n",
|
130 |
+
"- `python train.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --direction BtoA`\n",
|
131 |
+
"\n",
|
132 |
+
"Change the `--dataroot` and `--name` to your own dataset's path and model's name. Use `--gpu_ids 0,1,..` to train on multiple GPUs and `--batch_size` to change the batch size. Add `--direction BtoA` if you want to train a model to transfrom from class B to A."
|
133 |
+
]
|
134 |
+
},
|
135 |
+
{
|
136 |
+
"cell_type": "code",
|
137 |
+
"execution_count": null,
|
138 |
+
"metadata": {
|
139 |
+
"colab": {},
|
140 |
+
"colab_type": "code",
|
141 |
+
"id": "0sp7TCT2x9dB"
|
142 |
+
},
|
143 |
+
"outputs": [],
|
144 |
+
"source": [
|
145 |
+
"!python train.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --direction BtoA --display_id -1"
|
146 |
+
]
|
147 |
+
},
|
148 |
+
{
|
149 |
+
"cell_type": "markdown",
|
150 |
+
"metadata": {
|
151 |
+
"colab_type": "text",
|
152 |
+
"id": "9UkcaFZiyASl"
|
153 |
+
},
|
154 |
+
"source": [
|
155 |
+
"# Testing\n",
|
156 |
+
"\n",
|
157 |
+
"- `python test.py --dataroot ./datasets/facades --direction BtoA --model pix2pix --name facades_pix2pix`\n",
|
158 |
+
"\n",
|
159 |
+
"Change the `--dataroot`, `--name`, and `--direction` to be consistent with your trained model's configuration and how you want to transform images.\n",
|
160 |
+
"\n",
|
161 |
+
"> from https://github.com/junyanz/pytorch-CycleGAN-and-pix2pix:\n",
|
162 |
+
"> Note that we specified --direction BtoA as Facades dataset's A to B direction is photos to labels.\n",
|
163 |
+
"\n",
|
164 |
+
"> If you would like to apply a pre-trained model to a collection of input images (rather than image pairs), please use --model test option. See ./scripts/test_single.sh for how to apply a model to Facade label maps (stored in the directory facades/testB).\n",
|
165 |
+
"\n",
|
166 |
+
"> See a list of currently available models at ./scripts/download_pix2pix_model.sh"
|
167 |
+
]
|
168 |
+
},
|
169 |
+
{
|
170 |
+
"cell_type": "code",
|
171 |
+
"execution_count": null,
|
172 |
+
"metadata": {
|
173 |
+
"colab": {},
|
174 |
+
"colab_type": "code",
|
175 |
+
"id": "mey7o6j-0368"
|
176 |
+
},
|
177 |
+
"outputs": [],
|
178 |
+
"source": [
|
179 |
+
"!ls checkpoints/"
|
180 |
+
]
|
181 |
+
},
|
182 |
+
{
|
183 |
+
"cell_type": "code",
|
184 |
+
"execution_count": null,
|
185 |
+
"metadata": {
|
186 |
+
"colab": {},
|
187 |
+
"colab_type": "code",
|
188 |
+
"id": "uCsKkEq0yGh0"
|
189 |
+
},
|
190 |
+
"outputs": [],
|
191 |
+
"source": [
|
192 |
+
"!python test.py --dataroot ./datasets/facades --direction BtoA --model pix2pix --name facades_label2photo_pretrained --use_wandb"
|
193 |
+
]
|
194 |
+
},
|
195 |
+
{
|
196 |
+
"cell_type": "markdown",
|
197 |
+
"metadata": {
|
198 |
+
"colab_type": "text",
|
199 |
+
"id": "OzSKIPUByfiN"
|
200 |
+
},
|
201 |
+
"source": [
|
202 |
+
"# Visualize"
|
203 |
+
]
|
204 |
+
},
|
205 |
+
{
|
206 |
+
"cell_type": "code",
|
207 |
+
"execution_count": null,
|
208 |
+
"metadata": {
|
209 |
+
"colab": {},
|
210 |
+
"colab_type": "code",
|
211 |
+
"id": "9Mgg8raPyizq"
|
212 |
+
},
|
213 |
+
"outputs": [],
|
214 |
+
"source": [
|
215 |
+
"import matplotlib.pyplot as plt\n",
|
216 |
+
"\n",
|
217 |
+
"img = plt.imread('./results/facades_label2photo_pretrained/test_latest/images/100_fake_B.png')\n",
|
218 |
+
"plt.imshow(img)"
|
219 |
+
]
|
220 |
+
},
|
221 |
+
{
|
222 |
+
"cell_type": "code",
|
223 |
+
"execution_count": null,
|
224 |
+
"metadata": {
|
225 |
+
"colab": {},
|
226 |
+
"colab_type": "code",
|
227 |
+
"id": "0G3oVH9DyqLQ"
|
228 |
+
},
|
229 |
+
"outputs": [],
|
230 |
+
"source": [
|
231 |
+
"img = plt.imread('./results/facades_label2photo_pretrained/test_latest/images/100_real_A.png')\n",
|
232 |
+
"plt.imshow(img)"
|
233 |
+
]
|
234 |
+
},
|
235 |
+
{
|
236 |
+
"cell_type": "code",
|
237 |
+
"execution_count": null,
|
238 |
+
"metadata": {
|
239 |
+
"colab": {},
|
240 |
+
"colab_type": "code",
|
241 |
+
"id": "ErK5OC1j1LH4"
|
242 |
+
},
|
243 |
+
"outputs": [],
|
244 |
+
"source": [
|
245 |
+
"img = plt.imread('./results/facades_label2photo_pretrained/test_latest/images/100_real_B.png')\n",
|
246 |
+
"plt.imshow(img)"
|
247 |
+
]
|
248 |
+
}
|
249 |
+
],
|
250 |
+
"metadata": {
|
251 |
+
"accelerator": "GPU",
|
252 |
+
"colab": {
|
253 |
+
"collapsed_sections": [],
|
254 |
+
"include_colab_link": true,
|
255 |
+
"name": "pix2pix",
|
256 |
+
"provenance": []
|
257 |
+
},
|
258 |
+
"environment": {
|
259 |
+
"name": "tf2-gpu.2-3.m74",
|
260 |
+
"type": "gcloud",
|
261 |
+
"uri": "gcr.io/deeplearning-platform-release/tf2-gpu.2-3:m74"
|
262 |
+
},
|
263 |
+
"kernelspec": {
|
264 |
+
"display_name": "Python 3",
|
265 |
+
"language": "python",
|
266 |
+
"name": "python3"
|
267 |
+
},
|
268 |
+
"language_info": {
|
269 |
+
"codemirror_mode": {
|
270 |
+
"name": "ipython",
|
271 |
+
"version": 3
|
272 |
+
},
|
273 |
+
"file_extension": ".py",
|
274 |
+
"mimetype": "text/x-python",
|
275 |
+
"name": "python",
|
276 |
+
"nbconvert_exporter": "python",
|
277 |
+
"pygments_lexer": "ipython3",
|
278 |
+
"version": "3.7.10"
|
279 |
+
}
|
280 |
+
},
|
281 |
+
"nbformat": 4,
|
282 |
+
"nbformat_minor": 4
|
283 |
+
}
|
requirements.txt
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
torch>=1.4.0
|
2 |
+
torchvision>=0.5.0
|
3 |
+
dominate>=2.4.0
|
4 |
+
visdom>=0.1.8.8
|
5 |
+
wandb
|
6 |
+
Pillow
|
7 |
+
gradio
|
8 |
+
huggingface-hub
|
9 |
+
matplotlib
|
scripts/conda_deps.sh
ADDED
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
1 |
+
set -ex
|
2 |
+
conda install numpy pyyaml mkl mkl-include setuptools cmake cffi typing
|
3 |
+
conda install pytorch torchvision -c pytorch # add cuda90 if CUDA 9
|
4 |
+
conda install visdom dominate -c conda-forge # install visdom and dominate
|
scripts/download_cyclegan_model.sh
ADDED
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FILE=$1
|
2 |
+
|
3 |
+
echo "Note: available models are apple2orange, orange2apple, summer2winter_yosemite, winter2summer_yosemite, horse2zebra, zebra2horse, monet2photo, style_monet, style_cezanne, style_ukiyoe, style_vangogh, sat2map, map2sat, cityscapes_photo2label, cityscapes_label2photo, facades_photo2label, facades_label2photo, iphone2dslr_flower"
|
4 |
+
|
5 |
+
echo "Specified [$FILE]"
|
6 |
+
|
7 |
+
mkdir -p ./checkpoints/${FILE}_pretrained
|
8 |
+
MODEL_FILE=./checkpoints/${FILE}_pretrained/latest_net_G.pth
|
9 |
+
URL=http://efrosgans.eecs.berkeley.edu/cyclegan/pretrained_models/$FILE.pth
|
10 |
+
|
11 |
+
wget -N $URL -O $MODEL_FILE
|
scripts/download_pix2pix_model.sh
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
FILE=$1
|
2 |
+
|
3 |
+
echo "Note: available models are edges2shoes, sat2map, map2sat, facades_label2photo, and day2night"
|
4 |
+
echo "Specified [$FILE]"
|
5 |
+
|
6 |
+
mkdir -p ./checkpoints/${FILE}_pretrained
|
7 |
+
MODEL_FILE=./checkpoints/${FILE}_pretrained/latest_net_G.pth
|
8 |
+
URL=http://efrosgans.eecs.berkeley.edu/pix2pix/models-pytorch/$FILE.pth
|
9 |
+
|
10 |
+
wget -N $URL -O $MODEL_FILE
|
scripts/edges/PostprocessHED.m
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
%%% Prerequisites
|
2 |
+
% You need to get the cpp file edgesNmsMex.cpp from https://raw.githubusercontent.com/pdollar/edges/master/private/edgesNmsMex.cpp
|
3 |
+
% and compile it in Matlab: mex edgesNmsMex.cpp
|
4 |
+
% You also need to download and install Piotr's Computer Vision Matlab Toolbox: https://pdollar.github.io/toolbox/
|
5 |
+
|
6 |
+
%%% parameters
|
7 |
+
% hed_mat_dir: the hed mat file directory (the output of 'batch_hed.py')
|
8 |
+
% edge_dir: the output HED edges directory
|
9 |
+
% image_width: resize the edge map to [image_width, image_width]
|
10 |
+
% threshold: threshold for image binarization (default 25.0/255.0)
|
11 |
+
% small_edge: remove small edges (default 5)
|
12 |
+
|
13 |
+
function [] = PostprocessHED(hed_mat_dir, edge_dir, image_width, threshold, small_edge)
|
14 |
+
|
15 |
+
if ~exist(edge_dir, 'dir')
|
16 |
+
mkdir(edge_dir);
|
17 |
+
end
|
18 |
+
fileList = dir(fullfile(hed_mat_dir, '*.mat'));
|
19 |
+
nFiles = numel(fileList);
|
20 |
+
fprintf('find %d mat files\n', nFiles);
|
21 |
+
|
22 |
+
for n = 1 : nFiles
|
23 |
+
if mod(n, 1000) == 0
|
24 |
+
fprintf('process %d/%d images\n', n, nFiles);
|
25 |
+
end
|
26 |
+
fileName = fileList(n).name;
|
27 |
+
filePath = fullfile(hed_mat_dir, fileName);
|
28 |
+
jpgName = strrep(fileName, '.mat', '.jpg');
|
29 |
+
edge_path = fullfile(edge_dir, jpgName);
|
30 |
+
|
31 |
+
if ~exist(edge_path, 'file')
|
32 |
+
E = GetEdge(filePath);
|
33 |
+
E = imresize(E,[image_width,image_width]);
|
34 |
+
E_simple = SimpleEdge(E, threshold, small_edge);
|
35 |
+
E_simple = uint8(E_simple*255);
|
36 |
+
imwrite(E_simple, edge_path, 'Quality',100);
|
37 |
+
end
|
38 |
+
end
|
39 |
+
end
|
40 |
+
|
41 |
+
|
42 |
+
|
43 |
+
|
44 |
+
function [E] = GetEdge(filePath)
|
45 |
+
load(filePath);
|
46 |
+
E = 1-edge_predict;
|
47 |
+
end
|
48 |
+
|
49 |
+
function [E4] = SimpleEdge(E, threshold, small_edge)
|
50 |
+
if nargin <= 1
|
51 |
+
threshold = 25.0/255.0;
|
52 |
+
end
|
53 |
+
|
54 |
+
if nargin <= 2
|
55 |
+
small_edge = 5;
|
56 |
+
end
|
57 |
+
|
58 |
+
if ndims(E) == 3
|
59 |
+
E = E(:,:,1);
|
60 |
+
end
|
61 |
+
|
62 |
+
E1 = 1 - E;
|
63 |
+
E2 = EdgeNMS(E1);
|
64 |
+
E3 = double(E2>=max(eps,threshold));
|
65 |
+
E3 = bwmorph(E3,'thin',inf);
|
66 |
+
E4 = bwareaopen(E3, small_edge);
|
67 |
+
E4=1-E4;
|
68 |
+
end
|
69 |
+
|
70 |
+
function [E_nms] = EdgeNMS( E )
|
71 |
+
E=single(E);
|
72 |
+
[Ox,Oy] = gradient2(convTri(E,4));
|
73 |
+
[Oxx,~] = gradient2(Ox);
|
74 |
+
[Oxy,Oyy] = gradient2(Oy);
|
75 |
+
O = mod(atan(Oyy.*sign(-Oxy)./(Oxx+1e-5)),pi);
|
76 |
+
E_nms = edgesNmsMex(E,O,1,5,1.01,1);
|
77 |
+
end
|
scripts/edges/batch_hed.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# HED batch processing script; modified from https://github.com/s9xie/hed/blob/master/examples/hed/HED-tutorial.ipynb
|
2 |
+
# Step 1: download the hed repo: https://github.com/s9xie/hed
|
3 |
+
# Step 2: download the models and protoxt, and put them under {caffe_root}/examples/hed/
|
4 |
+
# Step 3: put this script under {caffe_root}/examples/hed/
|
5 |
+
# Step 4: run the following script:
|
6 |
+
# python batch_hed.py --images_dir=/data/to/path/photos/ --hed_mat_dir=/data/to/path/hed_mat_files/
|
7 |
+
# The code sometimes crashes after computation is done. Error looks like "Check failed: ... driver shutting down". You can just kill the job.
|
8 |
+
# For large images, it will produce gpu memory issue. Therefore, you better resize the images before running this script.
|
9 |
+
# Step 5: run the MATLAB post-processing script "PostprocessHED.m"
|
10 |
+
|
11 |
+
|
12 |
+
import caffe
|
13 |
+
import numpy as np
|
14 |
+
from PIL import Image
|
15 |
+
import os
|
16 |
+
import argparse
|
17 |
+
import sys
|
18 |
+
import scipy.io as sio
|
19 |
+
|
20 |
+
|
21 |
+
def parse_args():
|
22 |
+
parser = argparse.ArgumentParser(description='batch proccesing: photos->edges')
|
23 |
+
parser.add_argument('--caffe_root', dest='caffe_root', help='caffe root', default='../../', type=str)
|
24 |
+
parser.add_argument('--caffemodel', dest='caffemodel', help='caffemodel', default='./hed_pretrained_bsds.caffemodel', type=str)
|
25 |
+
parser.add_argument('--prototxt', dest='prototxt', help='caffe prototxt file', default='./deploy.prototxt', type=str)
|
26 |
+
parser.add_argument('--images_dir', dest='images_dir', help='directory to store input photos', type=str)
|
27 |
+
parser.add_argument('--hed_mat_dir', dest='hed_mat_dir', help='directory to store output hed edges in mat file', type=str)
|
28 |
+
parser.add_argument('--border', dest='border', help='padding border', type=int, default=128)
|
29 |
+
parser.add_argument('--gpu_id', dest='gpu_id', help='gpu id', type=int, default=1)
|
30 |
+
args = parser.parse_args()
|
31 |
+
return args
|
32 |
+
|
33 |
+
|
34 |
+
args = parse_args()
|
35 |
+
for arg in vars(args):
|
36 |
+
print('[%s] =' % arg, getattr(args, arg))
|
37 |
+
# Make sure that caffe is on the python path:
|
38 |
+
caffe_root = args.caffe_root # this file is expected to be in {caffe_root}/examples/hed/
|
39 |
+
sys.path.insert(0, caffe_root + 'python')
|
40 |
+
|
41 |
+
|
42 |
+
if not os.path.exists(args.hed_mat_dir):
|
43 |
+
print('create output directory %s' % args.hed_mat_dir)
|
44 |
+
os.makedirs(args.hed_mat_dir)
|
45 |
+
|
46 |
+
imgList = os.listdir(args.images_dir)
|
47 |
+
nImgs = len(imgList)
|
48 |
+
print('#images = %d' % nImgs)
|
49 |
+
|
50 |
+
caffe.set_mode_gpu()
|
51 |
+
caffe.set_device(args.gpu_id)
|
52 |
+
# load net
|
53 |
+
net = caffe.Net(args.prototxt, args.caffemodel, caffe.TEST)
|
54 |
+
# pad border
|
55 |
+
border = args.border
|
56 |
+
|
57 |
+
for i in range(nImgs):
|
58 |
+
if i % 500 == 0:
|
59 |
+
print('processing image %d/%d' % (i, nImgs))
|
60 |
+
im = Image.open(os.path.join(args.images_dir, imgList[i]))
|
61 |
+
|
62 |
+
in_ = np.array(im, dtype=np.float32)
|
63 |
+
in_ = np.pad(in_, ((border, border), (border, border), (0, 0)), 'reflect')
|
64 |
+
|
65 |
+
in_ = in_[:, :, 0:3]
|
66 |
+
in_ = in_[:, :, ::-1]
|
67 |
+
in_ -= np.array((104.00698793, 116.66876762, 122.67891434))
|
68 |
+
in_ = in_.transpose((2, 0, 1))
|
69 |
+
# remove the following two lines if testing with cpu
|
70 |
+
|
71 |
+
# shape for input (data blob is N x C x H x W), set data
|
72 |
+
net.blobs['data'].reshape(1, *in_.shape)
|
73 |
+
net.blobs['data'].data[...] = in_
|
74 |
+
# run net and take argmax for prediction
|
75 |
+
net.forward()
|
76 |
+
fuse = net.blobs['sigmoid-fuse'].data[0][0, :, :]
|
77 |
+
# get rid of the border
|
78 |
+
fuse = fuse[(border + 35):(-border + 35), (border + 35):(-border + 35)]
|
79 |
+
# save hed file to the disk
|
80 |
+
name, ext = os.path.splitext(imgList[i])
|
81 |
+
sio.savemat(os.path.join(args.hed_mat_dir, name + '.mat'), {'edge_predict': fuse})
|
scripts/eval_cityscapes/caffemodel/deploy.prototxt
ADDED
@@ -0,0 +1,769 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
layer {
|
2 |
+
name: "data"
|
3 |
+
type: "Input"
|
4 |
+
top: "data"
|
5 |
+
input_param {
|
6 |
+
shape {
|
7 |
+
dim: 1
|
8 |
+
dim: 3
|
9 |
+
dim: 500
|
10 |
+
dim: 500
|
11 |
+
}
|
12 |
+
}
|
13 |
+
}
|
14 |
+
layer {
|
15 |
+
name: "conv1_1"
|
16 |
+
type: "Convolution"
|
17 |
+
bottom: "data"
|
18 |
+
top: "conv1_1"
|
19 |
+
param {
|
20 |
+
lr_mult: 1
|
21 |
+
decay_mult: 1
|
22 |
+
}
|
23 |
+
param {
|
24 |
+
lr_mult: 2
|
25 |
+
decay_mult: 0
|
26 |
+
}
|
27 |
+
convolution_param {
|
28 |
+
num_output: 64
|
29 |
+
pad: 100
|
30 |
+
kernel_size: 3
|
31 |
+
stride: 1
|
32 |
+
weight_filler {
|
33 |
+
type: "gaussian"
|
34 |
+
std: 0.01
|
35 |
+
}
|
36 |
+
bias_filler {
|
37 |
+
type: "constant"
|
38 |
+
value: 0
|
39 |
+
}
|
40 |
+
}
|
41 |
+
}
|
42 |
+
layer {
|
43 |
+
name: "relu1_1"
|
44 |
+
type: "ReLU"
|
45 |
+
bottom: "conv1_1"
|
46 |
+
top: "conv1_1"
|
47 |
+
}
|
48 |
+
layer {
|
49 |
+
name: "conv1_2"
|
50 |
+
type: "Convolution"
|
51 |
+
bottom: "conv1_1"
|
52 |
+
top: "conv1_2"
|
53 |
+
param {
|
54 |
+
lr_mult: 1
|
55 |
+
decay_mult: 1
|
56 |
+
}
|
57 |
+
param {
|
58 |
+
lr_mult: 2
|
59 |
+
decay_mult: 0
|
60 |
+
}
|
61 |
+
convolution_param {
|
62 |
+
num_output: 64
|
63 |
+
pad: 1
|
64 |
+
kernel_size: 3
|
65 |
+
stride: 1
|
66 |
+
weight_filler {
|
67 |
+
type: "gaussian"
|
68 |
+
std: 0.01
|
69 |
+
}
|
70 |
+
bias_filler {
|
71 |
+
type: "constant"
|
72 |
+
value: 0
|
73 |
+
}
|
74 |
+
}
|
75 |
+
}
|
76 |
+
layer {
|
77 |
+
name: "relu1_2"
|
78 |
+
type: "ReLU"
|
79 |
+
bottom: "conv1_2"
|
80 |
+
top: "conv1_2"
|
81 |
+
}
|
82 |
+
layer {
|
83 |
+
name: "pool1"
|
84 |
+
type: "Pooling"
|
85 |
+
bottom: "conv1_2"
|
86 |
+
top: "pool1"
|
87 |
+
pooling_param {
|
88 |
+
pool: MAX
|
89 |
+
kernel_size: 2
|
90 |
+
stride: 2
|
91 |
+
}
|
92 |
+
}
|
93 |
+
layer {
|
94 |
+
name: "conv2_1"
|
95 |
+
type: "Convolution"
|
96 |
+
bottom: "pool1"
|
97 |
+
top: "conv2_1"
|
98 |
+
param {
|
99 |
+
lr_mult: 1
|
100 |
+
decay_mult: 1
|
101 |
+
}
|
102 |
+
param {
|
103 |
+
lr_mult: 2
|
104 |
+
decay_mult: 0
|
105 |
+
}
|
106 |
+
convolution_param {
|
107 |
+
num_output: 128
|
108 |
+
pad: 1
|
109 |
+
kernel_size: 3
|
110 |
+
stride: 1
|
111 |
+
weight_filler {
|
112 |
+
type: "gaussian"
|
113 |
+
std: 0.01
|
114 |
+
}
|
115 |
+
bias_filler {
|
116 |
+
type: "constant"
|
117 |
+
value: 0
|
118 |
+
}
|
119 |
+
}
|
120 |
+
}
|
121 |
+
layer {
|
122 |
+
name: "relu2_1"
|
123 |
+
type: "ReLU"
|
124 |
+
bottom: "conv2_1"
|
125 |
+
top: "conv2_1"
|
126 |
+
}
|
127 |
+
layer {
|
128 |
+
name: "conv2_2"
|
129 |
+
type: "Convolution"
|
130 |
+
bottom: "conv2_1"
|
131 |
+
top: "conv2_2"
|
132 |
+
param {
|
133 |
+
lr_mult: 1
|
134 |
+
decay_mult: 1
|
135 |
+
}
|
136 |
+
param {
|
137 |
+
lr_mult: 2
|
138 |
+
decay_mult: 0
|
139 |
+
}
|
140 |
+
convolution_param {
|
141 |
+
num_output: 128
|
142 |
+
pad: 1
|
143 |
+
kernel_size: 3
|
144 |
+
stride: 1
|
145 |
+
weight_filler {
|
146 |
+
type: "gaussian"
|
147 |
+
std: 0.01
|
148 |
+
}
|
149 |
+
bias_filler {
|
150 |
+
type: "constant"
|
151 |
+
value: 0
|
152 |
+
}
|
153 |
+
}
|
154 |
+
}
|
155 |
+
layer {
|
156 |
+
name: "relu2_2"
|
157 |
+
type: "ReLU"
|
158 |
+
bottom: "conv2_2"
|
159 |
+
top: "conv2_2"
|
160 |
+
}
|
161 |
+
layer {
|
162 |
+
name: "pool2"
|
163 |
+
type: "Pooling"
|
164 |
+
bottom: "conv2_2"
|
165 |
+
top: "pool2"
|
166 |
+
pooling_param {
|
167 |
+
pool: MAX
|
168 |
+
kernel_size: 2
|
169 |
+
stride: 2
|
170 |
+
}
|
171 |
+
}
|
172 |
+
layer {
|
173 |
+
name: "conv3_1"
|
174 |
+
type: "Convolution"
|
175 |
+
bottom: "pool2"
|
176 |
+
top: "conv3_1"
|
177 |
+
param {
|
178 |
+
lr_mult: 1
|
179 |
+
decay_mult: 1
|
180 |
+
}
|
181 |
+
param {
|
182 |
+
lr_mult: 2
|
183 |
+
decay_mult: 0
|
184 |
+
}
|
185 |
+
convolution_param {
|
186 |
+
num_output: 256
|
187 |
+
pad: 1
|
188 |
+
kernel_size: 3
|
189 |
+
stride: 1
|
190 |
+
weight_filler {
|
191 |
+
type: "gaussian"
|
192 |
+
std: 0.01
|
193 |
+
}
|
194 |
+
bias_filler {
|
195 |
+
type: "constant"
|
196 |
+
value: 0
|
197 |
+
}
|
198 |
+
}
|
199 |
+
}
|
200 |
+
layer {
|
201 |
+
name: "relu3_1"
|
202 |
+
type: "ReLU"
|
203 |
+
bottom: "conv3_1"
|
204 |
+
top: "conv3_1"
|
205 |
+
}
|
206 |
+
layer {
|
207 |
+
name: "conv3_2"
|
208 |
+
type: "Convolution"
|
209 |
+
bottom: "conv3_1"
|
210 |
+
top: "conv3_2"
|
211 |
+
param {
|
212 |
+
lr_mult: 1
|
213 |
+
decay_mult: 1
|
214 |
+
}
|
215 |
+
param {
|
216 |
+
lr_mult: 2
|
217 |
+
decay_mult: 0
|
218 |
+
}
|
219 |
+
convolution_param {
|
220 |
+
num_output: 256
|
221 |
+
pad: 1
|
222 |
+
kernel_size: 3
|
223 |
+
stride: 1
|
224 |
+
weight_filler {
|
225 |
+
type: "gaussian"
|
226 |
+
std: 0.01
|
227 |
+
}
|
228 |
+
bias_filler {
|
229 |
+
type: "constant"
|
230 |
+
value: 0
|
231 |
+
}
|
232 |
+
}
|
233 |
+
}
|
234 |
+
layer {
|
235 |
+
name: "relu3_2"
|
236 |
+
type: "ReLU"
|
237 |
+
bottom: "conv3_2"
|
238 |
+
top: "conv3_2"
|
239 |
+
}
|
240 |
+
layer {
|
241 |
+
name: "conv3_3"
|
242 |
+
type: "Convolution"
|
243 |
+
bottom: "conv3_2"
|
244 |
+
top: "conv3_3"
|
245 |
+
param {
|
246 |
+
lr_mult: 1
|
247 |
+
decay_mult: 1
|
248 |
+
}
|
249 |
+
param {
|
250 |
+
lr_mult: 2
|
251 |
+
decay_mult: 0
|
252 |
+
}
|
253 |
+
convolution_param {
|
254 |
+
num_output: 256
|
255 |
+
pad: 1
|
256 |
+
kernel_size: 3
|
257 |
+
stride: 1
|
258 |
+
weight_filler {
|
259 |
+
type: "gaussian"
|
260 |
+
std: 0.01
|
261 |
+
}
|
262 |
+
bias_filler {
|
263 |
+
type: "constant"
|
264 |
+
value: 0
|
265 |
+
}
|
266 |
+
}
|
267 |
+
}
|
268 |
+
layer {
|
269 |
+
name: "relu3_3"
|
270 |
+
type: "ReLU"
|
271 |
+
bottom: "conv3_3"
|
272 |
+
top: "conv3_3"
|
273 |
+
}
|
274 |
+
layer {
|
275 |
+
name: "pool3"
|
276 |
+
type: "Pooling"
|
277 |
+
bottom: "conv3_3"
|
278 |
+
top: "pool3"
|
279 |
+
pooling_param {
|
280 |
+
pool: MAX
|
281 |
+
kernel_size: 2
|
282 |
+
stride: 2
|
283 |
+
}
|
284 |
+
}
|
285 |
+
layer {
|
286 |
+
name: "conv4_1"
|
287 |
+
type: "Convolution"
|
288 |
+
bottom: "pool3"
|
289 |
+
top: "conv4_1"
|
290 |
+
param {
|
291 |
+
lr_mult: 1
|
292 |
+
decay_mult: 1
|
293 |
+
}
|
294 |
+
param {
|
295 |
+
lr_mult: 2
|
296 |
+
decay_mult: 0
|
297 |
+
}
|
298 |
+
convolution_param {
|
299 |
+
num_output: 512
|
300 |
+
pad: 1
|
301 |
+
kernel_size: 3
|
302 |
+
stride: 1
|
303 |
+
weight_filler {
|
304 |
+
type: "gaussian"
|
305 |
+
std: 0.01
|
306 |
+
}
|
307 |
+
bias_filler {
|
308 |
+
type: "constant"
|
309 |
+
value: 0
|
310 |
+
}
|
311 |
+
}
|
312 |
+
}
|
313 |
+
layer {
|
314 |
+
name: "relu4_1"
|
315 |
+
type: "ReLU"
|
316 |
+
bottom: "conv4_1"
|
317 |
+
top: "conv4_1"
|
318 |
+
}
|
319 |
+
layer {
|
320 |
+
name: "conv4_2"
|
321 |
+
type: "Convolution"
|
322 |
+
bottom: "conv4_1"
|
323 |
+
top: "conv4_2"
|
324 |
+
param {
|
325 |
+
lr_mult: 1
|
326 |
+
decay_mult: 1
|
327 |
+
}
|
328 |
+
param {
|
329 |
+
lr_mult: 2
|
330 |
+
decay_mult: 0
|
331 |
+
}
|
332 |
+
convolution_param {
|
333 |
+
num_output: 512
|
334 |
+
pad: 1
|
335 |
+
kernel_size: 3
|
336 |
+
stride: 1
|
337 |
+
weight_filler {
|
338 |
+
type: "gaussian"
|
339 |
+
std: 0.01
|
340 |
+
}
|
341 |
+
bias_filler {
|
342 |
+
type: "constant"
|
343 |
+
value: 0
|
344 |
+
}
|
345 |
+
}
|
346 |
+
}
|
347 |
+
layer {
|
348 |
+
name: "relu4_2"
|
349 |
+
type: "ReLU"
|
350 |
+
bottom: "conv4_2"
|
351 |
+
top: "conv4_2"
|
352 |
+
}
|
353 |
+
layer {
|
354 |
+
name: "conv4_3"
|
355 |
+
type: "Convolution"
|
356 |
+
bottom: "conv4_2"
|
357 |
+
top: "conv4_3"
|
358 |
+
param {
|
359 |
+
lr_mult: 1
|
360 |
+
decay_mult: 1
|
361 |
+
}
|
362 |
+
param {
|
363 |
+
lr_mult: 2
|
364 |
+
decay_mult: 0
|
365 |
+
}
|
366 |
+
convolution_param {
|
367 |
+
num_output: 512
|
368 |
+
pad: 1
|
369 |
+
kernel_size: 3
|
370 |
+
stride: 1
|
371 |
+
weight_filler {
|
372 |
+
type: "gaussian"
|
373 |
+
std: 0.01
|
374 |
+
}
|
375 |
+
bias_filler {
|
376 |
+
type: "constant"
|
377 |
+
value: 0
|
378 |
+
}
|
379 |
+
}
|
380 |
+
}
|
381 |
+
layer {
|
382 |
+
name: "relu4_3"
|
383 |
+
type: "ReLU"
|
384 |
+
bottom: "conv4_3"
|
385 |
+
top: "conv4_3"
|
386 |
+
}
|
387 |
+
layer {
|
388 |
+
name: "pool4"
|
389 |
+
type: "Pooling"
|
390 |
+
bottom: "conv4_3"
|
391 |
+
top: "pool4"
|
392 |
+
pooling_param {
|
393 |
+
pool: MAX
|
394 |
+
kernel_size: 2
|
395 |
+
stride: 2
|
396 |
+
}
|
397 |
+
}
|
398 |
+
layer {
|
399 |
+
name: "conv5_1"
|
400 |
+
type: "Convolution"
|
401 |
+
bottom: "pool4"
|
402 |
+
top: "conv5_1"
|
403 |
+
param {
|
404 |
+
lr_mult: 1
|
405 |
+
decay_mult: 1
|
406 |
+
}
|
407 |
+
param {
|
408 |
+
lr_mult: 2
|
409 |
+
decay_mult: 0
|
410 |
+
}
|
411 |
+
convolution_param {
|
412 |
+
num_output: 512
|
413 |
+
pad: 1
|
414 |
+
kernel_size: 3
|
415 |
+
stride: 1
|
416 |
+
weight_filler {
|
417 |
+
type: "gaussian"
|
418 |
+
std: 0.01
|
419 |
+
}
|
420 |
+
bias_filler {
|
421 |
+
type: "constant"
|
422 |
+
value: 0
|
423 |
+
}
|
424 |
+
}
|
425 |
+
}
|
426 |
+
layer {
|
427 |
+
name: "relu5_1"
|
428 |
+
type: "ReLU"
|
429 |
+
bottom: "conv5_1"
|
430 |
+
top: "conv5_1"
|
431 |
+
}
|
432 |
+
layer {
|
433 |
+
name: "conv5_2"
|
434 |
+
type: "Convolution"
|
435 |
+
bottom: "conv5_1"
|
436 |
+
top: "conv5_2"
|
437 |
+
param {
|
438 |
+
lr_mult: 1
|
439 |
+
decay_mult: 1
|
440 |
+
}
|
441 |
+
param {
|
442 |
+
lr_mult: 2
|
443 |
+
decay_mult: 0
|
444 |
+
}
|
445 |
+
convolution_param {
|
446 |
+
num_output: 512
|
447 |
+
pad: 1
|
448 |
+
kernel_size: 3
|
449 |
+
stride: 1
|
450 |
+
weight_filler {
|
451 |
+
type: "gaussian"
|
452 |
+
std: 0.01
|
453 |
+
}
|
454 |
+
bias_filler {
|
455 |
+
type: "constant"
|
456 |
+
value: 0
|
457 |
+
}
|
458 |
+
}
|
459 |
+
}
|
460 |
+
layer {
|
461 |
+
name: "relu5_2"
|
462 |
+
type: "ReLU"
|
463 |
+
bottom: "conv5_2"
|
464 |
+
top: "conv5_2"
|
465 |
+
}
|
466 |
+
layer {
|
467 |
+
name: "conv5_3"
|
468 |
+
type: "Convolution"
|
469 |
+
bottom: "conv5_2"
|
470 |
+
top: "conv5_3"
|
471 |
+
param {
|
472 |
+
lr_mult: 1
|
473 |
+
decay_mult: 1
|
474 |
+
}
|
475 |
+
param {
|
476 |
+
lr_mult: 2
|
477 |
+
decay_mult: 0
|
478 |
+
}
|
479 |
+
convolution_param {
|
480 |
+
num_output: 512
|
481 |
+
pad: 1
|
482 |
+
kernel_size: 3
|
483 |
+
stride: 1
|
484 |
+
weight_filler {
|
485 |
+
type: "gaussian"
|
486 |
+
std: 0.01
|
487 |
+
}
|
488 |
+
bias_filler {
|
489 |
+
type: "constant"
|
490 |
+
value: 0
|
491 |
+
}
|
492 |
+
}
|
493 |
+
}
|
494 |
+
layer {
|
495 |
+
name: "relu5_3"
|
496 |
+
type: "ReLU"
|
497 |
+
bottom: "conv5_3"
|
498 |
+
top: "conv5_3"
|
499 |
+
}
|
500 |
+
layer {
|
501 |
+
name: "pool5"
|
502 |
+
type: "Pooling"
|
503 |
+
bottom: "conv5_3"
|
504 |
+
top: "pool5"
|
505 |
+
pooling_param {
|
506 |
+
pool: MAX
|
507 |
+
kernel_size: 2
|
508 |
+
stride: 2
|
509 |
+
}
|
510 |
+
}
|
511 |
+
layer {
|
512 |
+
name: "fc6_cs"
|
513 |
+
type: "Convolution"
|
514 |
+
bottom: "pool5"
|
515 |
+
top: "fc6_cs"
|
516 |
+
param {
|
517 |
+
lr_mult: 1
|
518 |
+
decay_mult: 1
|
519 |
+
}
|
520 |
+
param {
|
521 |
+
lr_mult: 2
|
522 |
+
decay_mult: 0
|
523 |
+
}
|
524 |
+
convolution_param {
|
525 |
+
num_output: 4096
|
526 |
+
pad: 0
|
527 |
+
kernel_size: 7
|
528 |
+
stride: 1
|
529 |
+
weight_filler {
|
530 |
+
type: "gaussian"
|
531 |
+
std: 0.01
|
532 |
+
}
|
533 |
+
bias_filler {
|
534 |
+
type: "constant"
|
535 |
+
value: 0
|
536 |
+
}
|
537 |
+
}
|
538 |
+
}
|
539 |
+
layer {
|
540 |
+
name: "relu6_cs"
|
541 |
+
type: "ReLU"
|
542 |
+
bottom: "fc6_cs"
|
543 |
+
top: "fc6_cs"
|
544 |
+
}
|
545 |
+
layer {
|
546 |
+
name: "fc7_cs"
|
547 |
+
type: "Convolution"
|
548 |
+
bottom: "fc6_cs"
|
549 |
+
top: "fc7_cs"
|
550 |
+
param {
|
551 |
+
lr_mult: 1
|
552 |
+
decay_mult: 1
|
553 |
+
}
|
554 |
+
param {
|
555 |
+
lr_mult: 2
|
556 |
+
decay_mult: 0
|
557 |
+
}
|
558 |
+
convolution_param {
|
559 |
+
num_output: 4096
|
560 |
+
pad: 0
|
561 |
+
kernel_size: 1
|
562 |
+
stride: 1
|
563 |
+
weight_filler {
|
564 |
+
type: "gaussian"
|
565 |
+
std: 0.01
|
566 |
+
}
|
567 |
+
bias_filler {
|
568 |
+
type: "constant"
|
569 |
+
value: 0
|
570 |
+
}
|
571 |
+
}
|
572 |
+
}
|
573 |
+
layer {
|
574 |
+
name: "relu7_cs"
|
575 |
+
type: "ReLU"
|
576 |
+
bottom: "fc7_cs"
|
577 |
+
top: "fc7_cs"
|
578 |
+
}
|
579 |
+
layer {
|
580 |
+
name: "score_fr"
|
581 |
+
type: "Convolution"
|
582 |
+
bottom: "fc7_cs"
|
583 |
+
top: "score_fr"
|
584 |
+
param {
|
585 |
+
lr_mult: 1
|
586 |
+
decay_mult: 1
|
587 |
+
}
|
588 |
+
param {
|
589 |
+
lr_mult: 2
|
590 |
+
decay_mult: 0
|
591 |
+
}
|
592 |
+
convolution_param {
|
593 |
+
num_output: 20
|
594 |
+
pad: 0
|
595 |
+
kernel_size: 1
|
596 |
+
weight_filler {
|
597 |
+
type: "xavier"
|
598 |
+
}
|
599 |
+
bias_filler {
|
600 |
+
type: "constant"
|
601 |
+
}
|
602 |
+
}
|
603 |
+
}
|
604 |
+
layer {
|
605 |
+
name: "upscore2"
|
606 |
+
type: "Deconvolution"
|
607 |
+
bottom: "score_fr"
|
608 |
+
top: "upscore2"
|
609 |
+
param {
|
610 |
+
lr_mult: 1
|
611 |
+
}
|
612 |
+
convolution_param {
|
613 |
+
num_output: 20
|
614 |
+
bias_term: false
|
615 |
+
kernel_size: 4
|
616 |
+
stride: 2
|
617 |
+
weight_filler {
|
618 |
+
type: "xavier"
|
619 |
+
}
|
620 |
+
bias_filler {
|
621 |
+
type: "constant"
|
622 |
+
}
|
623 |
+
}
|
624 |
+
}
|
625 |
+
layer {
|
626 |
+
name: "score_pool4"
|
627 |
+
type: "Convolution"
|
628 |
+
bottom: "pool4"
|
629 |
+
top: "score_pool4"
|
630 |
+
param {
|
631 |
+
lr_mult: 1
|
632 |
+
decay_mult: 1
|
633 |
+
}
|
634 |
+
param {
|
635 |
+
lr_mult: 2
|
636 |
+
decay_mult: 0
|
637 |
+
}
|
638 |
+
convolution_param {
|
639 |
+
num_output: 20
|
640 |
+
pad: 0
|
641 |
+
kernel_size: 1
|
642 |
+
weight_filler {
|
643 |
+
type: "xavier"
|
644 |
+
}
|
645 |
+
bias_filler {
|
646 |
+
type: "constant"
|
647 |
+
}
|
648 |
+
}
|
649 |
+
}
|
650 |
+
layer {
|
651 |
+
name: "score_pool4c"
|
652 |
+
type: "Crop"
|
653 |
+
bottom: "score_pool4"
|
654 |
+
bottom: "upscore2"
|
655 |
+
top: "score_pool4c"
|
656 |
+
crop_param {
|
657 |
+
axis: 2
|
658 |
+
offset: 5
|
659 |
+
}
|
660 |
+
}
|
661 |
+
layer {
|
662 |
+
name: "fuse_pool4"
|
663 |
+
type: "Eltwise"
|
664 |
+
bottom: "upscore2"
|
665 |
+
bottom: "score_pool4c"
|
666 |
+
top: "fuse_pool4"
|
667 |
+
eltwise_param {
|
668 |
+
operation: SUM
|
669 |
+
}
|
670 |
+
}
|
671 |
+
layer {
|
672 |
+
name: "upscore_pool4"
|
673 |
+
type: "Deconvolution"
|
674 |
+
bottom: "fuse_pool4"
|
675 |
+
top: "upscore_pool4"
|
676 |
+
param {
|
677 |
+
lr_mult: 1
|
678 |
+
}
|
679 |
+
convolution_param {
|
680 |
+
num_output: 20
|
681 |
+
bias_term: false
|
682 |
+
kernel_size: 4
|
683 |
+
stride: 2
|
684 |
+
weight_filler {
|
685 |
+
type: "xavier"
|
686 |
+
}
|
687 |
+
bias_filler {
|
688 |
+
type: "constant"
|
689 |
+
}
|
690 |
+
}
|
691 |
+
}
|
692 |
+
layer {
|
693 |
+
name: "score_pool3"
|
694 |
+
type: "Convolution"
|
695 |
+
bottom: "pool3"
|
696 |
+
top: "score_pool3"
|
697 |
+
param {
|
698 |
+
lr_mult: 1
|
699 |
+
decay_mult: 1
|
700 |
+
}
|
701 |
+
param {
|
702 |
+
lr_mult: 2
|
703 |
+
decay_mult: 0
|
704 |
+
}
|
705 |
+
convolution_param {
|
706 |
+
num_output: 20
|
707 |
+
pad: 0
|
708 |
+
kernel_size: 1
|
709 |
+
weight_filler {
|
710 |
+
type: "xavier"
|
711 |
+
}
|
712 |
+
bias_filler {
|
713 |
+
type: "constant"
|
714 |
+
}
|
715 |
+
}
|
716 |
+
}
|
717 |
+
layer {
|
718 |
+
name: "score_pool3c"
|
719 |
+
type: "Crop"
|
720 |
+
bottom: "score_pool3"
|
721 |
+
bottom: "upscore_pool4"
|
722 |
+
top: "score_pool3c"
|
723 |
+
crop_param {
|
724 |
+
axis: 2
|
725 |
+
offset: 9
|
726 |
+
}
|
727 |
+
}
|
728 |
+
layer {
|
729 |
+
name: "fuse_pool3"
|
730 |
+
type: "Eltwise"
|
731 |
+
bottom: "upscore_pool4"
|
732 |
+
bottom: "score_pool3c"
|
733 |
+
top: "fuse_pool3"
|
734 |
+
eltwise_param {
|
735 |
+
operation: SUM
|
736 |
+
}
|
737 |
+
}
|
738 |
+
layer {
|
739 |
+
name: "upscore8"
|
740 |
+
type: "Deconvolution"
|
741 |
+
bottom: "fuse_pool3"
|
742 |
+
top: "upscore8"
|
743 |
+
param {
|
744 |
+
lr_mult: 1
|
745 |
+
}
|
746 |
+
convolution_param {
|
747 |
+
num_output: 20
|
748 |
+
bias_term: false
|
749 |
+
kernel_size: 16
|
750 |
+
stride: 8
|
751 |
+
weight_filler {
|
752 |
+
type: "xavier"
|
753 |
+
}
|
754 |
+
bias_filler {
|
755 |
+
type: "constant"
|
756 |
+
}
|
757 |
+
}
|
758 |
+
}
|
759 |
+
layer {
|
760 |
+
name: "score"
|
761 |
+
type: "Crop"
|
762 |
+
bottom: "upscore8"
|
763 |
+
bottom: "data"
|
764 |
+
top: "score"
|
765 |
+
crop_param {
|
766 |
+
axis: 2
|
767 |
+
offset: 31
|
768 |
+
}
|
769 |
+
}
|
scripts/eval_cityscapes/cityscapes.py
ADDED
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# The following code is modified from https://github.com/shelhamer/clockwork-fcn
|
2 |
+
import sys
|
3 |
+
import os
|
4 |
+
import glob
|
5 |
+
import numpy as np
|
6 |
+
from PIL import Image
|
7 |
+
|
8 |
+
|
9 |
+
class cityscapes:
|
10 |
+
def __init__(self, data_path):
|
11 |
+
# data_path something like /data2/cityscapes
|
12 |
+
self.dir = data_path
|
13 |
+
self.classes = ['road', 'sidewalk', 'building', 'wall', 'fence',
|
14 |
+
'pole', 'traffic light', 'traffic sign', 'vegetation', 'terrain',
|
15 |
+
'sky', 'person', 'rider', 'car', 'truck',
|
16 |
+
'bus', 'train', 'motorcycle', 'bicycle']
|
17 |
+
self.mean = np.array((72.78044, 83.21195, 73.45286), dtype=np.float32)
|
18 |
+
# import cityscapes label helper and set up label mappings
|
19 |
+
sys.path.insert(0, '{}/scripts/helpers/'.format(self.dir))
|
20 |
+
labels = __import__('labels')
|
21 |
+
self.id2trainId = {label.id: label.trainId for label in labels.labels} # dictionary mapping from raw IDs to train IDs
|
22 |
+
self.trainId2color = {label.trainId: label.color for label in labels.labels} # dictionary mapping train IDs to colors as 3-tuples
|
23 |
+
|
24 |
+
def get_dset(self, split):
|
25 |
+
'''
|
26 |
+
List images as (city, id) for the specified split
|
27 |
+
|
28 |
+
TODO(shelhamer) generate splits from cityscapes itself, instead of
|
29 |
+
relying on these separately made text files.
|
30 |
+
'''
|
31 |
+
if split == 'train':
|
32 |
+
dataset = open('{}/ImageSets/segFine/train.txt'.format(self.dir)).read().splitlines()
|
33 |
+
else:
|
34 |
+
dataset = open('{}/ImageSets/segFine/val.txt'.format(self.dir)).read().splitlines()
|
35 |
+
return [(item.split('/')[0], item.split('/')[1]) for item in dataset]
|
36 |
+
|
37 |
+
def load_image(self, split, city, idx):
|
38 |
+
im = Image.open('{}/leftImg8bit_sequence/{}/{}/{}_leftImg8bit.png'.format(self.dir, split, city, idx))
|
39 |
+
return im
|
40 |
+
|
41 |
+
def assign_trainIds(self, label):
|
42 |
+
"""
|
43 |
+
Map the given label IDs to the train IDs appropriate for training
|
44 |
+
Use the label mapping provided in labels.py from the cityscapes scripts
|
45 |
+
"""
|
46 |
+
label = np.array(label, dtype=np.float32)
|
47 |
+
if sys.version_info[0] < 3:
|
48 |
+
for k, v in self.id2trainId.iteritems():
|
49 |
+
label[label == k] = v
|
50 |
+
else:
|
51 |
+
for k, v in self.id2trainId.items():
|
52 |
+
label[label == k] = v
|
53 |
+
return label
|
54 |
+
|
55 |
+
def load_label(self, split, city, idx):
|
56 |
+
"""
|
57 |
+
Load label image as 1 x height x width integer array of label indices.
|
58 |
+
The leading singleton dimension is required by the loss.
|
59 |
+
"""
|
60 |
+
label = Image.open('{}/gtFine/{}/{}/{}_gtFine_labelIds.png'.format(self.dir, split, city, idx))
|
61 |
+
label = self.assign_trainIds(label) # get proper labels for eval
|
62 |
+
label = np.array(label, dtype=np.uint8)
|
63 |
+
label = label[np.newaxis, ...]
|
64 |
+
return label
|
65 |
+
|
66 |
+
def preprocess(self, im):
|
67 |
+
"""
|
68 |
+
Preprocess loaded image (by load_image) for Caffe:
|
69 |
+
- cast to float
|
70 |
+
- switch channels RGB -> BGR
|
71 |
+
- subtract mean
|
72 |
+
- transpose to channel x height x width order
|
73 |
+
"""
|
74 |
+
in_ = np.array(im, dtype=np.float32)
|
75 |
+
in_ = in_[:, :, ::-1]
|
76 |
+
in_ -= self.mean
|
77 |
+
in_ = in_.transpose((2, 0, 1))
|
78 |
+
return in_
|
79 |
+
|
80 |
+
def palette(self, label):
|
81 |
+
'''
|
82 |
+
Map trainIds to colors as specified in labels.py
|
83 |
+
'''
|
84 |
+
if label.ndim == 3:
|
85 |
+
label = label[0]
|
86 |
+
color = np.empty((label.shape[0], label.shape[1], 3))
|
87 |
+
if sys.version_info[0] < 3:
|
88 |
+
for k, v in self.trainId2color.iteritems():
|
89 |
+
color[label == k, :] = v
|
90 |
+
else:
|
91 |
+
for k, v in self.trainId2color.items():
|
92 |
+
color[label == k, :] = v
|
93 |
+
return color
|
94 |
+
|
95 |
+
def make_boundaries(label, thickness=None):
|
96 |
+
"""
|
97 |
+
Input is an image label, output is a numpy array mask encoding the boundaries of the objects
|
98 |
+
Extract pixels at the true boundary by dilation - erosion of label.
|
99 |
+
Don't just pick the void label as it is not exclusive to the boundaries.
|
100 |
+
"""
|
101 |
+
assert(thickness is not None)
|
102 |
+
import skimage.morphology as skm
|
103 |
+
void = 255
|
104 |
+
mask = np.logical_and(label > 0, label != void)[0]
|
105 |
+
selem = skm.disk(thickness)
|
106 |
+
boundaries = np.logical_xor(skm.dilation(mask, selem),
|
107 |
+
skm.erosion(mask, selem))
|
108 |
+
return boundaries
|
109 |
+
|
110 |
+
def list_label_frames(self, split):
|
111 |
+
"""
|
112 |
+
Select labeled frames from a split for evaluation
|
113 |
+
collected as (city, shot, idx) tuples
|
114 |
+
"""
|
115 |
+
def file2idx(f):
|
116 |
+
"""Helper to convert file path into frame ID"""
|
117 |
+
city, shot, frame = (os.path.basename(f).split('_')[:3])
|
118 |
+
return "_".join([city, shot, frame])
|
119 |
+
frames = []
|
120 |
+
cities = [os.path.basename(f) for f in glob.glob('{}/gtFine/{}/*'.format(self.dir, split))]
|
121 |
+
for c in cities:
|
122 |
+
files = sorted(glob.glob('{}/gtFine/{}/{}/*labelIds.png'.format(self.dir, split, c)))
|
123 |
+
frames.extend([file2idx(f) for f in files])
|
124 |
+
return frames
|
125 |
+
|
126 |
+
def collect_frame_sequence(self, split, idx, length):
|
127 |
+
"""
|
128 |
+
Collect sequence of frames preceding (and including) a labeled frame
|
129 |
+
as a list of Images.
|
130 |
+
|
131 |
+
Note: 19 preceding frames are provided for each labeled frame.
|
132 |
+
"""
|
133 |
+
SEQ_LEN = length
|
134 |
+
city, shot, frame = idx.split('_')
|
135 |
+
frame = int(frame)
|
136 |
+
frame_seq = []
|
137 |
+
for i in range(frame - SEQ_LEN, frame + 1):
|
138 |
+
frame_path = '{0}/leftImg8bit_sequence/val/{1}/{1}_{2}_{3:0>6d}_leftImg8bit.png'.format(
|
139 |
+
self.dir, city, shot, i)
|
140 |
+
frame_seq.append(Image.open(frame_path))
|
141 |
+
return frame_seq
|
scripts/eval_cityscapes/download_fcn8s.sh
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
URL=http://efrosgans.eecs.berkeley.edu/pix2pix_extra/fcn-8s-cityscapes.caffemodel
|
2 |
+
OUTPUT_FILE=./scripts/eval_cityscapes/caffemodel/fcn-8s-cityscapes.caffemodel
|
3 |
+
wget -N $URL -O $OUTPUT_FILE
|
scripts/eval_cityscapes/evaluate.py
ADDED
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import caffe
|
3 |
+
import argparse
|
4 |
+
import numpy as np
|
5 |
+
import scipy.misc
|
6 |
+
from PIL import Image
|
7 |
+
from util import segrun, fast_hist, get_scores
|
8 |
+
from cityscapes import cityscapes
|
9 |
+
|
10 |
+
parser = argparse.ArgumentParser()
|
11 |
+
parser.add_argument("--cityscapes_dir", type=str, required=True, help="Path to the original cityscapes dataset")
|
12 |
+
parser.add_argument("--result_dir", type=str, required=True, help="Path to the generated images to be evaluated")
|
13 |
+
parser.add_argument("--output_dir", type=str, required=True, help="Where to save the evaluation results")
|
14 |
+
parser.add_argument("--caffemodel_dir", type=str, default='./scripts/eval_cityscapes/caffemodel/', help="Where the FCN-8s caffemodel stored")
|
15 |
+
parser.add_argument("--gpu_id", type=int, default=0, help="Which gpu id to use")
|
16 |
+
parser.add_argument("--split", type=str, default='val', help="Data split to be evaluated")
|
17 |
+
parser.add_argument("--save_output_images", type=int, default=0, help="Whether to save the FCN output images")
|
18 |
+
args = parser.parse_args()
|
19 |
+
|
20 |
+
|
21 |
+
def main():
|
22 |
+
if not os.path.isdir(args.output_dir):
|
23 |
+
os.makedirs(args.output_dir)
|
24 |
+
if args.save_output_images > 0:
|
25 |
+
output_image_dir = args.output_dir + 'image_outputs/'
|
26 |
+
if not os.path.isdir(output_image_dir):
|
27 |
+
os.makedirs(output_image_dir)
|
28 |
+
CS = cityscapes(args.cityscapes_dir)
|
29 |
+
n_cl = len(CS.classes)
|
30 |
+
label_frames = CS.list_label_frames(args.split)
|
31 |
+
caffe.set_device(args.gpu_id)
|
32 |
+
caffe.set_mode_gpu()
|
33 |
+
net = caffe.Net(args.caffemodel_dir + '/deploy.prototxt',
|
34 |
+
args.caffemodel_dir + 'fcn-8s-cityscapes.caffemodel',
|
35 |
+
caffe.TEST)
|
36 |
+
|
37 |
+
hist_perframe = np.zeros((n_cl, n_cl))
|
38 |
+
for i, idx in enumerate(label_frames):
|
39 |
+
if i % 10 == 0:
|
40 |
+
print('Evaluating: %d/%d' % (i, len(label_frames)))
|
41 |
+
city = idx.split('_')[0]
|
42 |
+
# idx is city_shot_frame
|
43 |
+
label = CS.load_label(args.split, city, idx)
|
44 |
+
im_file = args.result_dir + '/' + idx + '_leftImg8bit.png'
|
45 |
+
im = np.array(Image.open(im_file))
|
46 |
+
im = scipy.misc.imresize(im, (label.shape[1], label.shape[2]))
|
47 |
+
# im = np.array(Image.fromarray(im).resize((label.shape[1], label.shape[2]))) # Note: scipy.misc.imresize is deprecated, but we still use it for reproducibility.
|
48 |
+
out = segrun(net, CS.preprocess(im))
|
49 |
+
hist_perframe += fast_hist(label.flatten(), out.flatten(), n_cl)
|
50 |
+
if args.save_output_images > 0:
|
51 |
+
label_im = CS.palette(label)
|
52 |
+
pred_im = CS.palette(out)
|
53 |
+
scipy.misc.imsave(output_image_dir + '/' + str(i) + '_pred.jpg', pred_im)
|
54 |
+
scipy.misc.imsave(output_image_dir + '/' + str(i) + '_gt.jpg', label_im)
|
55 |
+
scipy.misc.imsave(output_image_dir + '/' + str(i) + '_input.jpg', im)
|
56 |
+
|
57 |
+
mean_pixel_acc, mean_class_acc, mean_class_iou, per_class_acc, per_class_iou = get_scores(hist_perframe)
|
58 |
+
with open(args.output_dir + '/evaluation_results.txt', 'w') as f:
|
59 |
+
f.write('Mean pixel accuracy: %f\n' % mean_pixel_acc)
|
60 |
+
f.write('Mean class accuracy: %f\n' % mean_class_acc)
|
61 |
+
f.write('Mean class IoU: %f\n' % mean_class_iou)
|
62 |
+
f.write('************ Per class numbers below ************\n')
|
63 |
+
for i, cl in enumerate(CS.classes):
|
64 |
+
while len(cl) < 15:
|
65 |
+
cl = cl + ' '
|
66 |
+
f.write('%s: acc = %f, iou = %f\n' % (cl, per_class_acc[i], per_class_iou[i]))
|
67 |
+
|
68 |
+
|
69 |
+
main()
|
scripts/eval_cityscapes/util.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# The following code is modified from https://github.com/shelhamer/clockwork-fcn
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
|
5 |
+
def get_out_scoremap(net):
|
6 |
+
return net.blobs['score'].data[0].argmax(axis=0).astype(np.uint8)
|
7 |
+
|
8 |
+
|
9 |
+
def feed_net(net, in_):
|
10 |
+
"""
|
11 |
+
Load prepared input into net.
|
12 |
+
"""
|
13 |
+
net.blobs['data'].reshape(1, *in_.shape)
|
14 |
+
net.blobs['data'].data[...] = in_
|
15 |
+
|
16 |
+
|
17 |
+
def segrun(net, in_):
|
18 |
+
feed_net(net, in_)
|
19 |
+
net.forward()
|
20 |
+
return get_out_scoremap(net)
|
21 |
+
|
22 |
+
|
23 |
+
def fast_hist(a, b, n):
|
24 |
+
k = np.where((a >= 0) & (a < n))[0]
|
25 |
+
bc = np.bincount(n * a[k].astype(int) + b[k], minlength=n**2)
|
26 |
+
if len(bc) != n**2:
|
27 |
+
# ignore this example if dimension mismatch
|
28 |
+
return 0
|
29 |
+
return bc.reshape(n, n)
|
30 |
+
|
31 |
+
|
32 |
+
def get_scores(hist):
|
33 |
+
# Mean pixel accuracy
|
34 |
+
acc = np.diag(hist).sum() / (hist.sum() + 1e-12)
|
35 |
+
|
36 |
+
# Per class accuracy
|
37 |
+
cl_acc = np.diag(hist) / (hist.sum(1) + 1e-12)
|
38 |
+
|
39 |
+
# Per class IoU
|
40 |
+
iu = np.diag(hist) / (hist.sum(1) + hist.sum(0) - np.diag(hist) + 1e-12)
|
41 |
+
|
42 |
+
return acc, np.nanmean(cl_acc), np.nanmean(iu), cl_acc, iu
|
scripts/install_deps.sh
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
set -ex
|
2 |
+
pip install visdom
|
3 |
+
pip install dominate
|
scripts/test_before_push.py
ADDED
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Simple script to make sure basic usage
|
2 |
+
# such as training, testing, saving and loading
|
3 |
+
# runs without errors.
|
4 |
+
import os
|
5 |
+
|
6 |
+
|
7 |
+
def run(command):
|
8 |
+
print(command)
|
9 |
+
exit_status = os.system(command)
|
10 |
+
if exit_status > 0:
|
11 |
+
exit(1)
|
12 |
+
|
13 |
+
|
14 |
+
if __name__ == '__main__':
|
15 |
+
# download mini datasets
|
16 |
+
if not os.path.exists('./datasets/mini'):
|
17 |
+
run('bash ./datasets/download_cyclegan_dataset.sh mini')
|
18 |
+
|
19 |
+
if not os.path.exists('./datasets/mini_pix2pix'):
|
20 |
+
run('bash ./datasets/download_cyclegan_dataset.sh mini_pix2pix')
|
21 |
+
|
22 |
+
# pretrained cyclegan model
|
23 |
+
if not os.path.exists('./checkpoints/horse2zebra_pretrained/latest_net_G.pth'):
|
24 |
+
run('bash ./scripts/download_cyclegan_model.sh horse2zebra')
|
25 |
+
run('python test.py --model test --dataroot ./datasets/mini --name horse2zebra_pretrained --no_dropout --num_test 1 --no_dropout')
|
26 |
+
|
27 |
+
# pretrained pix2pix model
|
28 |
+
if not os.path.exists('./checkpoints/facades_label2photo_pretrained/latest_net_G.pth'):
|
29 |
+
run('bash ./scripts/download_pix2pix_model.sh facades_label2photo')
|
30 |
+
if not os.path.exists('./datasets/facades'):
|
31 |
+
run('bash ./datasets/download_pix2pix_dataset.sh facades')
|
32 |
+
run('python test.py --dataroot ./datasets/facades/ --direction BtoA --model pix2pix --name facades_label2photo_pretrained --num_test 1')
|
33 |
+
|
34 |
+
# cyclegan train/test
|
35 |
+
run('python train.py --model cycle_gan --name temp_cyclegan --dataroot ./datasets/mini --n_epochs 1 --n_epochs_decay 0 --save_latest_freq 10 --print_freq 1 --display_id -1')
|
36 |
+
run('python test.py --model test --name temp_cyclegan --dataroot ./datasets/mini --num_test 1 --model_suffix "_A" --no_dropout')
|
37 |
+
|
38 |
+
# pix2pix train/test
|
39 |
+
run('python train.py --model pix2pix --name temp_pix2pix --dataroot ./datasets/mini_pix2pix --n_epochs 1 --n_epochs_decay 5 --save_latest_freq 10 --display_id -1')
|
40 |
+
run('python test.py --model pix2pix --name temp_pix2pix --dataroot ./datasets/mini_pix2pix --num_test 1')
|
41 |
+
|
42 |
+
# template train/test
|
43 |
+
run('python train.py --model template --name temp2 --dataroot ./datasets/mini_pix2pix --n_epochs 1 --n_epochs_decay 0 --save_latest_freq 10 --display_id -1')
|
44 |
+
run('python test.py --model template --name temp2 --dataroot ./datasets/mini_pix2pix --num_test 1')
|
45 |
+
|
46 |
+
# colorization train/test (optional)
|
47 |
+
if not os.path.exists('./datasets/mini_colorization'):
|
48 |
+
run('bash ./datasets/download_cyclegan_dataset.sh mini_colorization')
|
49 |
+
|
50 |
+
run('python train.py --model colorization --name temp_color --dataroot ./datasets/mini_colorization --n_epochs 1 --n_epochs_decay 0 --save_latest_freq 5 --display_id -1')
|
51 |
+
run('python test.py --model colorization --name temp_color --dataroot ./datasets/mini_colorization --num_test 1')
|
scripts/test_colorization.sh
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
set -ex
|
2 |
+
python test.py --dataroot ./datasets/colorization --name color_pix2pix --model colorization
|
scripts/test_cyclegan.sh
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
set -ex
|
2 |
+
python test.py --dataroot ./datasets/maps --name maps_cyclegan --model cycle_gan --phase test --no_dropout
|
scripts/test_pix2pix.sh
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
set -ex
|
2 |
+
python test.py --dataroot ./datasets/facades --name facades_pix2pix --model pix2pix --netG unet_256 --direction BtoA --dataset_mode aligned --norm batch
|