panzs19 commited on
Commit
ca56d10
·
verified ·
1 Parent(s): f6f55b3

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +4 -0
  2. .gitignore +21 -0
  3. LICENSE +201 -0
  4. README.md +178 -0
  5. README_CN.md +155 -0
  6. WINDOWS_INSTALL_GUIDE.md +146 -0
  7. batch_npz_to_svg.py +78 -0
  8. batch_vectorize.py +252 -0
  9. dataset_utils.py +1224 -0
  10. docs/assets/bootstrap.min.css +0 -0
  11. docs/assets/font.css +37 -0
  12. docs/assets/style.css +135 -0
  13. docs/figures/1390.png +3 -0
  14. docs/figures/applications/Geometrized-Cartoon-Line-Inbetweening.png +3 -0
  15. docs/figures/applications/Painterly-Style-Transfer.png +3 -0
  16. docs/figures/applications/Vector-Line-Inbetweening-dynamic1.gif +3 -0
  17. docs/figures/applications/Vector-Line-Inbetweening.png +3 -0
  18. docs/figures/applications/Vector-Line-Inbetweening2.png +3 -0
  19. docs/figures/applications/complex-vector-drawings.png +3 -0
  20. docs/figures/applications/robot-calligraphy.png +3 -0
  21. docs/figures/applications/sketch-to-image.png +3 -0
  22. docs/figures/face-blue-1390-simplest.gif +3 -0
  23. docs/figures/muten-black-full-simplest.gif +3 -0
  24. docs/figures/muten.png +3 -0
  25. docs/figures/rocket-blue-simplest.gif +3 -0
  26. docs/figures/rocket.png +3 -0
  27. docs/index.html +293 -0
  28. hyper_parameters.py +341 -0
  29. launch_gui.bat +21 -0
  30. model_common_test.py +604 -0
  31. model_common_train.py +1193 -0
  32. outputs/sampling/clean_line_drawings__pretrain_clean_line_drawings/muten_0_pred.png +3 -0
  33. outputs/sampling/clean_line_drawings__pretrain_clean_line_drawings/muten_input.png +3 -0
  34. outputs/sampling/clean_line_drawings__pretrain_clean_line_drawings/order-compare/muten_0_pred.png +3 -0
  35. outputs/sampling/clean_line_drawings__pretrain_clean_line_drawings/order/muten_0_pred.png +3 -0
  36. outputs/sampling/clean_line_drawings__pretrain_clean_line_drawings/seq_data/muten_0.npz +3 -0
  37. outputs/sampling/faces__pretrain_faces/1390_0_pred.png +3 -0
  38. outputs/sampling/faces__pretrain_faces/1390_input.png +3 -0
  39. outputs/sampling/faces__pretrain_faces/order-compare/1390_0_pred.png +3 -0
  40. outputs/sampling/faces__pretrain_faces/order/1390_0_pred.png +3 -0
  41. outputs/sampling/faces__pretrain_faces/seq_data/1390_0.npz +3 -0
  42. outputs/sampling/rough_sketches__pretrain_rough_sketches/order-compare/rocket_0_pred.png +3 -0
  43. outputs/sampling/rough_sketches__pretrain_rough_sketches/order/rocket_0_pred.png +3 -0
  44. outputs/sampling/rough_sketches__pretrain_rough_sketches/rocket_0_pred.png +3 -0
  45. outputs/sampling/rough_sketches__pretrain_rough_sketches/rocket_input.png +3 -0
  46. outputs/sampling/rough_sketches__pretrain_rough_sketches/seq_data/rocket_0.npz +3 -0
  47. outputs/sampling/simplified/室内01/102-A_Proposed Site Plan__coarse_1/102-A_Proposed Site Plan__coarse_1_0.svg +0 -0
  48. outputs/sampling/simplified/室内01/102-A_Proposed Site Plan__coarse_1/102-A_Proposed Site Plan__coarse_1_0_pred.png +3 -0
  49. outputs/sampling/simplified/室内01/102-A_Proposed Site Plan__coarse_1/102-A_Proposed Site Plan__coarse_1_input.png +3 -0
  50. outputs/sampling/simplified/室内01/102-A_Proposed Site Plan__coarse_1/order-compare/102-A_Proposed Site Plan__coarse_1_0_pred.png +3 -0
.gitattributes CHANGED
@@ -58,3 +58,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ outputs/snapshot/p2s-75000.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
62
+ outputs/snapshot/pretrain_clean_line_drawings/p2s-75000.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
63
+ outputs/snapshot/pretrain_faces/p2s-90000.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
64
+ outputs/snapshot/pretrain_rough_sketches/p2s-90000.data-00000-of-00001 filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .idea
2
+ .idea/
3
+ data/
4
+ datas/
5
+ dataset/
6
+ datasets/
7
+ model/
8
+ models/
9
+ testData/
10
+ output/
11
+ outputs/
12
+
13
+ *.csv
14
+
15
+ # temporary files
16
+ *.txt~
17
+ *.pyc
18
+ .DS_Store
19
+ .gitignore~
20
+
21
+ *.h5
LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
README.md ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # General Virtual Sketching Framework for Vector Line Art - SIGGRAPH 2021
2
+
3
+ [[Paper]](https://esslab.jp/publications/HaoranSIGRAPH2021.pdf) | [[Project Page]](https://markmohr.github.io/virtual_sketching/) | [[中文Readme]](/README_CN.md) | [[中文论文介绍]](https://blog.csdn.net/qq_33000225/article/details/118883153)
4
+
5
+ This code is used for **line drawing vectorization**, **rough sketch simplification** and **photograph to vector line drawing**.
6
+
7
+ <img src='docs/figures/muten.png' height=300><img src='docs/figures/muten-black-full-simplest.gif' height=300>
8
+
9
+ <img src='docs/figures/rocket.png' height=150><img src='docs/figures/rocket-blue-simplest.gif' height=150>&nbsp;&nbsp;&nbsp;&nbsp;<img src='docs/figures/1390.png' height=150><img src='docs/figures/face-blue-1390-simplest.gif' height=150>
10
+
11
+ ## Outline
12
+ - [Dependencies](#dependencies)
13
+ - [Testing with Trained Weights](#testing-with-trained-weights)
14
+ - [Training](#training)
15
+ - [Citation](#citation)
16
+ - [Projects Using this Model/Method](#projects-using-this-modelmethod)
17
+ - [Blogs Mentioning this Paper](#blogs-mentioning-this-paper)
18
+ - [For Windows users](#-windows-users)
19
+
20
+ ## Dependencies
21
+ - [Tensorflow](https://www.tensorflow.org/) (1.12.0 <= version <=1.15.0)
22
+ - [opencv](https://opencv.org/) == 3.4.2
23
+ - [pillow](https://pillow.readthedocs.io/en/latest/index.html) == 6.2.0
24
+ - [scipy](https://www.scipy.org/) == 1.5.2
25
+ - [gizeh](https://github.com/Zulko/gizeh) == 0.1.11
26
+
27
+ ## Testing with Trained Weights
28
+ ### Model Preparation
29
+
30
+ Download the models [here](https://drive.google.com/drive/folders/1-hi2cl8joZ6oMOp4yvk_hObJGAK6ELHB?usp=sharing):
31
+ - `pretrain_clean_line_drawings` (105 MB): for vectorization
32
+ - `pretrain_rough_sketches` (105 MB): for rough sketch simplification
33
+ - `pretrain_faces` (105 MB): for photograph to line drawing
34
+
35
+ Then, place them in this file structure:
36
+ ```
37
+ outputs/
38
+ snapshot/
39
+ pretrain_clean_line_drawings/
40
+ pretrain_rough_sketches/
41
+ pretrain_faces/
42
+ ```
43
+
44
+ ### Usage
45
+ Choose the image in the `sample_inputs/` directory, and run one of the following commands for each task. The results will be under `outputs/sampling/`.
46
+
47
+ ``` python
48
+ python3 test_vectorization.py --input muten.png
49
+
50
+ python3 test_rough_sketch_simplification.py --input rocket.png
51
+
52
+ python3 test_photograph_to_line.py --input 1390.png
53
+ ```
54
+
55
+ **Note!!!** Our approach starts drawing from a randomly selected initial position, so it outputs different results in every testing trial (some might be fine and some might not be good enough). It is recommended to do several trials to select the visually best result. The number of outputs can be defined by the `--sample` argument:
56
+
57
+ ``` python
58
+ python3 test_vectorization.py --input muten.png --sample 10
59
+
60
+ python3 test_rough_sketch_simplification.py --input rocket.png --sample 10
61
+
62
+ python3 test_photograph_to_line.py --input 1390.png --sample 10
63
+ ```
64
+
65
+ **Reproducing Paper Figures:** our results (download from [here](https://drive.google.com/drive/folders/1-hi2cl8joZ6oMOp4yvk_hObJGAK6ELHB?usp=sharing)) are selected by doing a certain number of trials. Apparently, it is required to use the same initial drawing positions to reproduce our results.
66
+
67
+ ### Additional Tools
68
+
69
+ #### a) Visualization
70
+
71
+ Our vector output is stored in a `npz` package. Run the following command to obtain the rendered output and the drawing order. Results will be under the same directory of the `npz` file.
72
+ ``` python
73
+ python3 tools/visualize_drawing.py --file path/to/the/result.npz
74
+ ```
75
+
76
+ #### b) GIF Making
77
+
78
+ To see the dynamic drawing procedure, run the following command to obtain the `gif`. Result will be under the same directory of the `npz` file.
79
+ ``` python
80
+ python3 tools/gif_making.py --file path/to/the/result.npz
81
+ ```
82
+
83
+
84
+ #### c) Conversion to SVG
85
+
86
+ Our vector output in a `npz` package is stored as Eq.(1) in the main paper. Run the following command to convert it to the `svg` format. Result will be under the same directory of the `npz` file.
87
+
88
+ ``` python
89
+ python3 tools/svg_conversion.py --file path/to/the/result.npz
90
+ ```
91
+ - The conversion is implemented in two modes (by setting the `--svg_type` argument):
92
+ - `single` (default): each stroke (a single segment) forms a path in the SVG file
93
+ - `cluster`: each continuous curve (with multiple strokes) forms a path in the SVG file
94
+
95
+ **Important Notes**
96
+
97
+ In SVG format, all the segments on a path share the same *stroke-width*. While in our stroke design, strokes on a common curve have different widths. Inside a stroke (a single segment), the thickness also changes linearly from an endpoint to another.
98
+ Therefore, neither of the two conversion methods above generate visually the same results as the ones in our paper.
99
+ *(Please mention this issue in your paper if you do qualitative comparisons with our results in SVG format.)*
100
+
101
+
102
+ <br>
103
+
104
+ ## Training
105
+
106
+ ### Preparations
107
+
108
+ Download the models [here](https://drive.google.com/drive/folders/1-hi2cl8joZ6oMOp4yvk_hObJGAK6ELHB?usp=sharing):
109
+ - `pretrain_neural_renderer` (40 MB): the pre-trained neural renderer
110
+ - `pretrain_perceptual_model` (691 MB): the pre-trained perceptual model for raster loss
111
+
112
+ Download the datasets [here](https://drive.google.com/drive/folders/1-hi2cl8joZ6oMOp4yvk_hObJGAK6ELHB?usp=sharing):
113
+ - `QuickDraw-clean` (14 MB): for clean line drawing vectorization. Taken from [QuickDraw](https://github.com/googlecreativelab/quickdraw-dataset) dataset.
114
+ - `QuickDraw-rough` (361 MB): for rough sketch simplification. Synthesized by the pencil drawing generation method from [Sketch Simplification](https://github.com/bobbens/sketch_simplification#pencil-drawing-generation).
115
+ - `CelebAMask-faces` (370 MB): for photograph to line drawing. Processed from the [CelebAMask-HQ](https://github.com/switchablenorms/CelebAMask-HQ) dataset.
116
+
117
+ Then, place them in this file structure:
118
+ ```
119
+ datasets/
120
+ QuickDraw-clean/
121
+ QuickDraw-rough/
122
+ CelebAMask-faces/
123
+ outputs/
124
+ snapshot/
125
+ pretrain_neural_renderer/
126
+ pretrain_perceptual_model/
127
+ ```
128
+
129
+ ### Running
130
+
131
+ It is recommended to train with multi-GPU. We train each task with 2 GPUs (each with 11 GB).
132
+
133
+ ``` python
134
+ python3 train_vectorization.py
135
+
136
+ python3 train_rough_photograph.py --data rough
137
+
138
+ python3 train_rough_photograph.py --data face
139
+ ```
140
+
141
+ <br>
142
+
143
+ ## Citation
144
+
145
+ If you use the code and models please cite:
146
+
147
+ ```
148
+ @article{mo2021virtualsketching,
149
+ title = {General Virtual Sketching Framework for Vector Line Art},
150
+ author = {Mo, Haoran and Simo-Serra, Edgar and Gao, Chengying and Zou, Changqing and Wang, Ruomei},
151
+ journal = {ACM Transactions on Graphics (Proceedings of ACM SIGGRAPH 2021)},
152
+ year = {2021},
153
+ volume = {40},
154
+ number = {4},
155
+ pages = {51:1--51:14}
156
+ }
157
+ ```
158
+
159
+ <br>
160
+
161
+ ## Projects Using this Model/Method
162
+
163
+ | **[Painterly style transfer](https://github.com/xch-liu/Painterly-Style-Transfer) (TVCG 2023)** | **[Robot calligraphy](https://github.com/LoYuXr/CalliRewrite) (ICRA 2024)** |
164
+ |:-------------:|:-------------------:|
165
+ | <img src="docs/figures/applications/Painterly-Style-Transfer.png" style="height: 170px"> | <img src="docs/figures/applications/robot-calligraphy.png" style="height: 170px"> |
166
+ | **[Geometrized cartoon line inbetweening](https://github.com/lisiyao21/AnimeInbet) (ICCV 2023)** | **[Stroke correspondence and inbetweening](https://github.com/MarkMoHR/JoSTC) (TOG 2024)** |
167
+ | <img src="docs/figures/applications/Geometrized-Cartoon-Line-Inbetweening.png" style="height: 170px"> | <img src="docs/figures/applications/Vector-Line-Inbetweening2.png" style="height: 170px"><img src="docs/figures/applications/Vector-Line-Inbetweening-dynamic1.gif" style="height: 170px"> |
168
+ | **[Modelling complex vector drawings](https://github.com/Co-do/Stroke-Cloud) (ICLR 2024)** | **[Sketch-to-Image Generation](https://github.com/BlockDetail/Block-and-Detail) (UIST 2024)** |
169
+ | <img src="docs/figures/applications/complex-vector-drawings.png" style="height: 170px"> | <img src="docs/figures/applications/sketch-to-image.png" style="height: 170px"> |
170
+
171
+ ## Blogs Mentioning this Paper
172
+
173
+ - [The state of AI for hand-drawn animation inbetweening](https://yosefk.com/blog/the-state-of-ai-for-hand-drawn-animation-inbetweening.html)
174
+
175
+ ## 🪟 Windows users
176
+
177
+ See [WINDOWS_INSTALL_GUIDE.md](WINDOWS_INSTALL_GUIDE.md) for a complete Windows installation guide and GUI usage.
178
+
README_CN.md ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # General Virtual Sketching Framework for Vector Line Art - SIGGRAPH 2021
2
+
3
+ [[论文]](https://esslab.jp/publications/HaoranSIGRAPH2021.pdf) | [[项目主页]](https://markmohr.github.io/virtual_sketching/)
4
+
5
+ 这份代码能用于实现:**线稿矢量化**、**粗糙草图简化**和**自然图像到矢量草图转换**。
6
+
7
+ <img src='docs/figures/muten.png' height=300><img src='docs/figures/muten-black-full-simplest.gif' height=300>
8
+
9
+ <img src='docs/figures/rocket.png' height=150><img src='docs/figures/rocket-blue-simplest.gif' height=150>&nbsp;&nbsp;&nbsp;&nbsp;<img src='docs/figures/1390.png' height=150><img src='docs/figures/face-blue-1390-simplest.gif' height=150>
10
+
11
+ ## 目录
12
+ - [环境依赖](#环境依赖)
13
+ - [使用预训练模型测试](#使用预训练模型测试)
14
+ - [重新训练](#重新训练)
15
+ - [引用](#引用)
16
+
17
+ ## 环境依赖
18
+ - [Tensorflow](https://www.tensorflow.org/) (1.12.0 <= 版本 <=1.15.0)
19
+ - [opencv](https://opencv.org/) == 3.4.2
20
+ - [pillow](https://pillow.readthedocs.io/en/latest/index.html) == 6.2.0
21
+ - [scipy](https://www.scipy.org/) == 1.5.2
22
+ - [gizeh](https://github.com/Zulko/gizeh) == 0.1.11
23
+
24
+ ## 使用预训练模型测试
25
+ ### 模型下载与准备
26
+
27
+ 在[这里](https://drive.google.com/drive/folders/1-hi2cl8joZ6oMOp4yvk_hObJGAK6ELHB?usp=sharing)下载模型:
28
+ - `pretrain_clean_line_drawings` (105 MB): 用于线稿矢量化
29
+ - `pretrain_rough_sketches` (105 MB): 用于粗糙草图简化
30
+ - `pretrain_faces` (105 MB): 用于自然图像到矢量草图转换
31
+
32
+ 然后,按照如下结构放置模型:
33
+ ```
34
+ outputs/
35
+ snapshot/
36
+ pretrain_clean_line_drawings/
37
+ pretrain_rough_sketches/
38
+ pretrain_faces/
39
+ ```
40
+
41
+ ### 测试方法
42
+ 在`sample_inputs/`文件夹下选择图像,然后根据任务类型运行下面其中一个命令。生成结果会在`outputs/sampling/`目录下看到。
43
+
44
+ ``` python
45
+ python3 test_vectorization.py --input muten.png
46
+
47
+ python3 test_rough_sketch_simplification.py --input rocket.png
48
+
49
+ python3 test_photograph_to_line.py --input 1390.png
50
+ ```
51
+
52
+ **注意!!!** 我们的方法从一个随机挑选的初始位置启动绘制,所以每跑一次测试理论上都会得到一个不同的结果(有可能效果不错,但也可能效果不是很好)。因此,建议做多几次测试来挑选看上去最好的结果。也可以通过设置 `--sample`参数来定义跑一次测试代码同时输出(不同结果)的数量:
53
+
54
+ ``` python
55
+ python3 test_vectorization.py --input muten.png --sample 10
56
+
57
+ python3 test_rough_sketch_simplification.py --input rocket.png --sample 10
58
+
59
+ python3 test_photograph_to_line.py --input 1390.png --sample 10
60
+ ```
61
+
62
+ **如何复现论文展示的结果?** 可以从[这里](https://drive.google.com/drive/folders/1-hi2cl8joZ6oMOp4yvk_hObJGAK6ELHB?usp=sharing)下载论文展示的结果。这些是我们通过若干次测试得到不同输出后挑选的最好的结果。显然,若要复现这些结果,需要使用相同的初始位置启动绘制。
63
+
64
+ ### 其他工具
65
+
66
+ #### a) 可视化
67
+
68
+ 我们的矢量输出均使用`npz` 文件包存储。运行以下的命令可以得到渲染后的结果以及绘制顺序。可以在`npz` 文件包相同的目录下找到这些可视化结果。
69
+ ``` python
70
+ python3 tools/visualize_drawing.py --file path/to/the/result.npz
71
+ ```
72
+
73
+ #### b) GIF制作
74
+
75
+ 若要看到动态的绘制过程,可以运行以下命令来得到 `gif`。结果在`npz` 文件包相同的目录下。
76
+ ``` python
77
+ python3 tools/gif_making.py --file path/to/the/result.npz
78
+ ```
79
+
80
+
81
+ #### c) 转化为SVG
82
+
83
+ `npz` 文件包中的矢量结果均按照论文里面的公式(1)格式存储。可以运行以下命令行,来将其转化为 `svg` 文件格式。结果在`npz` 文件包相同的目录下。
84
+
85
+ ``` python
86
+ python3 tools/svg_conversion.py --file path/to/the/result.npz
87
+ ```
88
+ - 转化过程以两种模式实现(设置`--svg_type`参数):
89
+ - `single` (默认模式): 每个笔划(一根单独的曲线)构成SVG文件中的一个path路径
90
+ - `cluster`: 每个连续曲线(多个笔划)构成SVG文件中的一个path路径
91
+
92
+ **重要注意事项**
93
+
94
+ 在SVG文件格式中,一个path上的所有线段均只有同一个线宽(*stroke-width*)。然而在我们论文里面,定义一个连续曲线上所有的笔划可以有不同的线宽。同时,对于一个单独的笔划(贝塞尔曲线),定义其线宽从一个端点到另一个端点线性递增或者递减。
95
+
96
+ 因此,上述两个转化方法得到的SVG结果理论上都无法保证跟论文里面的结果在视觉上完全一致。(*假如你在论文里面使用这里转化后的SVG结果进行视觉上的对比,请提及此问题。*)
97
+
98
+
99
+ <br>
100
+
101
+ ## 重新训练
102
+
103
+ ### 训练准备
104
+
105
+ 在[这里](https://drive.google.com/drive/folders/1-hi2cl8joZ6oMOp4yvk_hObJGAK6ELHB?usp=sharing)下载模型:
106
+ - `pretrain_neural_renderer` (40 MB): 预训练好的神经网络渲染器
107
+ - `pretrain_perceptual_model` (691 MB): 预训练好的perceptual model,用于算 raster loss
108
+
109
+ 在[这里](https://drive.google.com/drive/folders/1-hi2cl8joZ6oMOp4yvk_hObJGAK6ELHB?usp=sharing)下载训练数据集:
110
+ - `QuickDraw-clean` (14 MB): 用于线稿矢量化。来自 [QuickDraw](https://github.com/googlecreativelab/quickdraw-dataset)数据集。
111
+ - `QuickDraw-rough` (361 MB): 用于粗糙草图简化。利用[Sketch Simplification](https://github.com/bobbens/sketch_simplification#pencil-drawing-generation)里面的铅笔画图像生成方法合成。
112
+ - `CelebAMask-faces` (370 MB): 用于自然图像到矢量草图转换。使用[CelebAMask-HQ](https://github.com/switchablenorms/CelebAMask-HQ)数据集进行处理后得到。
113
+
114
+ 然后,按照如下结构放置数据集:
115
+ ```
116
+ datasets/
117
+ QuickDraw-clean/
118
+ QuickDraw-rough/
119
+ CelebAMask-faces/
120
+ outputs/
121
+ snapshot/
122
+ pretrain_neural_renderer/
123
+ pretrain_perceptual_model/
124
+ ```
125
+
126
+ ### 训练方法
127
+
128
+ 建议使用多GPU进行训练。每个任务,我们均使用2个GPU(每个11 GB)来训练。
129
+
130
+ ``` python
131
+ python3 train_vectorization.py
132
+
133
+ python3 train_rough_photograph.py --data rough
134
+
135
+ python3 train_rough_photograph.py --data face
136
+ ```
137
+
138
+ <br>
139
+
140
+ ## 引用
141
+
142
+ 若使用此代码和模型,请引用本工作,谢谢!
143
+
144
+ ```
145
+ @article{mo2021virtualsketching,
146
+ title = {General Virtual Sketching Framework for Vector Line Art},
147
+ author = {Mo, Haoran and Simo-Serra, Edgar and Gao, Chengying and Zou, Changqing and Wang, Ruomei},
148
+ journal = {ACM Transactions on Graphics (Proceedings of ACM SIGGRAPH 2021)},
149
+ year = {2021},
150
+ volume = {40},
151
+ number = {4},
152
+ pages = {51:1--51:14}
153
+ }
154
+ ```
155
+
WINDOWS_INSTALL_GUIDE.md ADDED
@@ -0,0 +1,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🪟 Windows Installation Guide for Virtual Sketching
2
+
3
+ This guide provides step-by-step instructions to set up and run the [Virtual Sketching](https://github.com/MarkMoHR/virtual_sketching) project on Windows using Anaconda and Python 3.6.
4
+
5
+ ## ✅ Requirements
6
+
7
+ - Windows 10 or newer
8
+ - Anaconda installed
9
+ - Git installed (optional, but recommended)
10
+
11
+ ---
12
+
13
+ ## 📦 Step 1: Create and Activate Conda Environment
14
+
15
+ ```bash
16
+ conda create -n virtual_sketching python=3.6 -y
17
+ conda activate virtual_sketching
18
+ ```
19
+
20
+ ## 📂 Step 2: Clone the Repository
21
+
22
+ ```bash
23
+ cd D:\
24
+ git clone https://github.com/MarkMoHR/virtual_sketching.git
25
+ cd virtual_sketching
26
+ ```
27
+
28
+ (If you plan to contribute, consider forking the repo and using your own URL.)
29
+
30
+ ---
31
+
32
+ ## 🔧 Step 3: Install Required Packages
33
+
34
+ ### From `conda`:
35
+ ```bash
36
+ conda install opencv=3.4.2 pillow=6.2.0 scipy=1.5.2 -y
37
+ conda install -c conda-forge pycairo gtk3 cffi -y
38
+ ```
39
+
40
+ ### Then remove default TensorFlow (if installed via conda):
41
+ ```bash
42
+ conda remove tensorflow
43
+ ```
44
+
45
+ ### Install required packages via `pip`:
46
+ ```bash
47
+ pip install tensorflow==1.15.0
48
+ pip install numpy gizeh cairocffi matplotlib svgwrite
49
+ ```
50
+
51
+ > ⚠️ Do not upgrade `pillow`, `scipy`, or `tensorflow` — newer versions are incompatible.
52
+
53
+ ---
54
+
55
+ ## 🛠️ Step 4: Fix Backend Compatibility
56
+
57
+ In `utils.py`, near the top, ensure the following:
58
+
59
+ ```python
60
+ from PIL import Image
61
+ import matplotlib
62
+ matplotlib.use('TkAgg') # force compatible backend
63
+ import matplotlib.pyplot as plt
64
+ ```
65
+
66
+ This ensures proper rendering with tkinter on Windows.
67
+
68
+ ---
69
+
70
+ ## 🚀 Step 5: Run a Demo
71
+
72
+ From the project directory:
73
+
74
+ ```bash
75
+ python test_vectorization.py --input sample_inputs\muten.png --sample 5
76
+ ```
77
+
78
+ > ⚠️ This script only generates `.npz` and `.png` files. To convert to `.svg`, see next section.
79
+
80
+ ---
81
+
82
+ ## 🖼️ Optional: Use GUI Tool (Windows Only)
83
+
84
+ ### Step 1: Launch GUI with provided batch file
85
+
86
+ Use the `runme.bat` file to activate the conda environment and launch the Python GUI:
87
+
88
+ ```bat
89
+ rem runme.bat
90
+ set CONDAPATH=C:\ProgramData\anaconda3
91
+ set ENVNAME=virtual_sketching
92
+ call %CONDAPATH%\Scripts\activate.bat %ENVNAME%
93
+ python virtual_sketch_gui.py
94
+ pause
95
+ ```
96
+
97
+ ### Step 2: Select an input image and model
98
+
99
+ The GUI allows you to:
100
+ - Choose input image (PNG, JPEG, BMP, etc.)
101
+ - Select one of the three models
102
+ - Automatically runs processing and converts results to SVG
103
+ - Saves all outputs into a `sketches/` subfolder of the input image directory
104
+
105
+ ---
106
+
107
+ ## 🧠 Known Compatibility Notes
108
+
109
+ - Python 3.6 and TensorFlow 1.15 are required (due to use of `tensorflow.contrib`)
110
+ - Windows support requires manual setup of Gizeh and Cairo backends
111
+ - GPU usage optional — TensorFlow 1.15 requires CUDA 10.0 and cuDNN 7
112
+
113
+ ---
114
+
115
+ ## 🧩 Troubleshooting Tips
116
+
117
+ - ❌ `No module named '_cffi_backend'` → Run: `conda install -c conda-forge cffi`
118
+ - ❌ `ImportError: cannot import name 'draw_svg_from_npz'` → Use `svg_conversion.py` instead
119
+ - ❌ `.svg` looks wrong → Make sure you're using the official `svg_conversion.py` from `tools/`
120
+ - ❌ Missing `.svg`? → Use `virtual_sketch_gui.py` or run `tools/svg_conversion.py` manually on `.npz`
121
+
122
+ ---
123
+
124
+ ## 🤝 Contributing
125
+
126
+ Feel free to open issues or pull requests if you encounter bugs or want to improve the Windows support!
127
+
128
+ ---
129
+
130
+ ## 📁 Folder Structure Suggestion
131
+
132
+ ```
133
+ virtual_sketching/
134
+ ├── sample_inputs/
135
+ ├── tools/
136
+ ├── outputs/
137
+ ├── virtual_sketch_gui.py
138
+ ├── runme.bat
139
+ ├── README.md
140
+ └── WINDOWS_INSTALL_GUIDE.md ← You are here
141
+ ```
142
+
143
+ ---
144
+
145
+ Made with ❤️ by the community to help Windows users get started!
146
+
batch_npz_to_svg.py ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Batch convert npz files to SVG, placing each <name>_0.svg next to the
3
+ corresponding <name>_0_pred.png (instead of inside seq_data/<name>/).
4
+
5
+ Walks `outputs/sampling/simplified/` for every <name>_0.npz under .../seq_data/
6
+ and writes <parent_dir>/<name>_0.svg.
7
+ """
8
+ import os
9
+ import argparse
10
+ import glob
11
+ import numpy as np
12
+
13
+ # Reuse the conversion core directly
14
+ from tools.svg_conversion import convert_strokes_to_svg
15
+
16
+
17
+ def convert_one(npz_path, svg_type, out_path,
18
+ min_window_size=32, raster_size=128):
19
+ data = np.load(npz_path, encoding='latin1', allow_pickle=True)
20
+ strokes_data = data['strokes_data']
21
+ init_cursors = data['init_cursors']
22
+ image_size = data['image_size']
23
+ round_length = data['round_length']
24
+ init_width = data['init_width']
25
+
26
+ if round_length.ndim == 0:
27
+ round_lengths = [round_length]
28
+ else:
29
+ round_lengths = round_length
30
+
31
+ convert_strokes_to_svg(
32
+ strokes_data, init_cursors, image_size, round_lengths, init_width,
33
+ min_window_size=min_window_size, raster_size=raster_size,
34
+ save_path=out_path, svg_type=svg_type)
35
+
36
+
37
+ def main():
38
+ parser = argparse.ArgumentParser()
39
+ parser.add_argument('--root', type=str,
40
+ default='outputs/sampling/simplified',
41
+ help="Walk this directory for *_0.npz files.")
42
+ parser.add_argument('--svg_type', type=str,
43
+ choices=['single', 'cluster'], default='single')
44
+ parser.add_argument('--overwrite', action='store_true', default=False)
45
+ args = parser.parse_args()
46
+
47
+ pattern = os.path.join(args.root, '**', 'seq_data', '*.npz')
48
+ npz_files = sorted(glob.glob(pattern, recursive=True))
49
+ print('Found {} npz files under {}'.format(len(npz_files), args.root))
50
+
51
+ done, skipped, failed = 0, 0, []
52
+ for npz_path in npz_files:
53
+ # .../<name>/seq_data/<name>_0.npz -> .../<name>/<name>_0.svg
54
+ seq_dir = os.path.dirname(npz_path) # .../<name>/seq_data
55
+ parent_dir = os.path.dirname(seq_dir) # .../<name>
56
+ base = os.path.splitext(os.path.basename(npz_path))[0] # <name>_0
57
+ out_path = os.path.join(parent_dir, base + '.svg')
58
+
59
+ if not args.overwrite and os.path.exists(out_path):
60
+ skipped += 1
61
+ continue
62
+
63
+ try:
64
+ convert_one(npz_path, args.svg_type, out_path)
65
+ done += 1
66
+ print('[OK] {}'.format(out_path))
67
+ except Exception as e:
68
+ failed.append((npz_path, repr(e)))
69
+ print('[FAIL] {} err={}'.format(npz_path, repr(e)))
70
+
71
+ print('\n=== Done. converted={}, skipped(existing)={}, failed={} ==='
72
+ .format(done, skipped, len(failed)))
73
+ for p, e in failed:
74
+ print(' FAIL', p, e)
75
+
76
+
77
+ if __name__ == '__main__':
78
+ main()
batch_vectorize.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Batch vectorization script.
3
+ Reads images recursively from sample_inputs/simplified/<subdir>/<img>.png
4
+ and outputs to outputs/sampling/simplified/<subdir>/<img_basename>/
5
+
6
+ Reuses the core inference logic from test_vectorization.py but loads the model
7
+ ONCE and runs many images in the same TF session to amortize startup time.
8
+ """
9
+ import os
10
+ import sys
11
+ import time
12
+ import argparse
13
+ import numpy as np
14
+
15
+ # Limit TF/numpy thread counts BEFORE importing TF, so they take effect.
16
+ # Each shard worker should only use a fraction of the CPU cores to avoid
17
+ # contention when running many shards in parallel.
18
+ _NUM_THREADS = os.environ.get('VS_NUM_THREADS', '')
19
+ if _NUM_THREADS:
20
+ for _v in ['OMP_NUM_THREADS', 'OPENBLAS_NUM_THREADS', 'MKL_NUM_THREADS',
21
+ 'NUMEXPR_NUM_THREADS', 'TF_NUM_INTRAOP_THREADS',
22
+ 'TF_NUM_INTEROP_THREADS']:
23
+ os.environ.setdefault(_v, _NUM_THREADS)
24
+
25
+ import tensorflow as tf
26
+ from PIL import Image
27
+
28
+ import hyper_parameters as hparams
29
+ from model_common_test import DiffPastingV3, VirtualSketchingModel
30
+ from utils import (reset_graph, load_checkpoint, update_hyperparams,
31
+ save_seq_data, draw_strokes)
32
+ from dataset_utils import GeneralRawDataLoader, copy_hparams
33
+
34
+ # import sample() function from test_vectorization
35
+ from test_vectorization import sample as sample_vectorization
36
+
37
+ os.environ['CUDA_VISIBLE_DEVICES'] = os.environ.get('CUDA_VISIBLE_DEVICES', '0')
38
+
39
+
40
+ def collect_inputs(input_root):
41
+ """Walk input_root and collect all PNG/JPG files, returning
42
+ list of (relative_subdir, filename, full_path)."""
43
+ items = []
44
+ for dirpath, _, files in os.walk(input_root):
45
+ rel_subdir = os.path.relpath(dirpath, input_root)
46
+ for f in sorted(files):
47
+ if f.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp')):
48
+ items.append((rel_subdir, f, os.path.join(dirpath, f)))
49
+ return items
50
+
51
+
52
+ def build_eval_hparams(model_base_dir, model_name):
53
+ """Create the eval/sample hparams matching what the loaded checkpoint expects."""
54
+ model_params_default = hparams.get_default_hparams_clean()
55
+ # update_hyperparams reads the saved model_config.json under model_dir
56
+ model_params = update_hyperparams(
57
+ model_params_default, model_base_dir, model_name,
58
+ infer_dataset='clean_line_drawings')
59
+
60
+ eval_model_params = copy_hparams(model_params)
61
+ eval_model_params.use_input_dropout = 0
62
+ eval_model_params.use_recurrent_dropout = 0
63
+ eval_model_params.use_output_dropout = 0
64
+ eval_model_params.batch_size = 1
65
+ eval_model_params.model_mode = 'sample'
66
+
67
+ sample_model_params = copy_hparams(eval_model_params)
68
+ sample_model_params.batch_size = 1
69
+ sample_model_params.max_seq_len = 1
70
+
71
+ return eval_model_params, sample_model_params
72
+
73
+
74
+ def process_one_image(sess, sampling_model, paste_v3_func,
75
+ image_path, eval_hps, sample_hps,
76
+ out_dir, image_basename,
77
+ longer_infer_lens, state_dependent,
78
+ round_stop_state_num, stroke_acc_threshold,
79
+ draw_seq=False, draw_color_order=True):
80
+ """Run inference for one image and dump outputs into out_dir."""
81
+ os.makedirs(out_dir, exist_ok=True)
82
+
83
+ test_set = GeneralRawDataLoader(image_path, eval_hps.raster_size,
84
+ test_dataset='clean_line_drawings')
85
+
86
+ input_photos, init_cursors, test_image_size = test_set.get_test_image()
87
+ # input_photos: (1, image_size, image_size), [0-stroke, 1-BG]
88
+
89
+ if init_cursors.ndim == 3:
90
+ init_cursors = np.expand_dims(init_cursors, axis=0)
91
+
92
+ input_photos = input_photos[0:1, :, :]
93
+ ori_img = (input_photos.copy()[0] * 255.0).astype(np.uint8)
94
+ ori_img = np.stack([ori_img for _ in range(3)], axis=2)
95
+ Image.fromarray(ori_img, 'RGB').save(
96
+ os.path.join(out_dir, image_basename + '_input.png'), 'PNG')
97
+
98
+ (strokes_raw_out_list, states_raw_out_list, states_soft_out_list,
99
+ pred_imgs_out, window_size_out_list, round_new_cursors,
100
+ round_new_lengths) = sample_vectorization(
101
+ sess, sampling_model, input_photos, init_cursors, test_image_size,
102
+ eval_hps.max_seq_len, longer_infer_lens, state_dependent,
103
+ paste_v3_func, round_stop_state_num, stroke_acc_threshold)
104
+
105
+ best_result_idx = 0
106
+ strokes_raw_out = np.stack(strokes_raw_out_list[best_result_idx], axis=0)
107
+
108
+ multi_cursors = [init_cursors[0, best_result_idx, 0]]
109
+ for c_i in range(len(round_new_cursors)):
110
+ multi_cursors.append(round_new_cursors[c_i][best_result_idx, 0])
111
+
112
+ save_seq_data(out_dir, image_basename + '_0',
113
+ strokes_raw_out, multi_cursors,
114
+ test_image_size, round_new_lengths, eval_hps.min_width)
115
+
116
+ draw_strokes(strokes_raw_out, out_dir, image_basename + '_0_pred.png',
117
+ ori_img, test_image_size,
118
+ multi_cursors, round_new_lengths,
119
+ eval_hps.min_width, eval_hps.cursor_type,
120
+ sample_hps.raster_size, sample_hps.min_window_size,
121
+ sess, pasting_func=paste_v3_func,
122
+ save_seq=draw_seq, draw_order=draw_color_order)
123
+
124
+ return strokes_raw_out.shape[0] # number of strokes
125
+
126
+
127
+ def main():
128
+ parser = argparse.ArgumentParser()
129
+ parser.add_argument('--input_root', type=str,
130
+ default='sample_inputs/simplified',
131
+ help="Root directory of input images.")
132
+ parser.add_argument('--output_root', type=str,
133
+ default='outputs/sampling/simplified',
134
+ help="Root directory for outputs.")
135
+ parser.add_argument('--model', type=str,
136
+ default='pretrain_clean_line_drawings')
137
+ parser.add_argument('--model_base_dir', type=str,
138
+ default='outputs/snapshot')
139
+ parser.add_argument('--progress_log', type=str,
140
+ default='outputs/sampling/simplified/_progress.log')
141
+ parser.add_argument('--skip_existing', action='store_true', default=True)
142
+ parser.add_argument('--shard', type=str, default='0/1',
143
+ help="Shard spec 'i/N': this worker processes items "
144
+ "where index%%N == i (0-indexed).")
145
+ args = parser.parse_args()
146
+
147
+ # Parse shard
148
+ try:
149
+ shard_i, shard_n = (int(x) for x in args.shard.split('/'))
150
+ except Exception:
151
+ raise SystemExit("--shard must look like '0/8'")
152
+ assert 0 <= shard_i < shard_n, "Bad shard"
153
+
154
+ # Hyper-params equivalent to test_vectorization.main()
155
+ state_dependent = False
156
+ longer_infer_lens = [500 for _ in range(10)]
157
+ round_stop_state_num = 12
158
+ stroke_acc_threshold = 0.95
159
+
160
+ np.set_printoptions(precision=8, edgeitems=6, linewidth=200, suppress=True)
161
+
162
+ items = collect_inputs(args.input_root)
163
+ print('Found {} images under {}'.format(len(items), args.input_root))
164
+
165
+ # Apply shard filter
166
+ items = [it for idx, it in enumerate(items) if idx % shard_n == shard_i]
167
+ print('Shard {}/{} -> {} images'.format(shard_i, shard_n, len(items)))
168
+
169
+ # Build hparams + model ONCE
170
+ eval_hps, sample_hps = build_eval_hparams(args.model_base_dir, args.model)
171
+
172
+ reset_graph()
173
+ sampling_model = VirtualSketchingModel(sample_hps)
174
+ paste_v3_func = DiffPastingV3(sample_hps.raster_size)
175
+
176
+ tfconfig = tf.ConfigProto()
177
+ tfconfig.gpu_options.allow_growth = True
178
+ if _NUM_THREADS:
179
+ n = int(_NUM_THREADS)
180
+ tfconfig.intra_op_parallelism_threads = n
181
+ tfconfig.inter_op_parallelism_threads = n
182
+ sess = tf.InteractiveSession(config=tfconfig)
183
+ sess.run(tf.global_variables_initializer())
184
+
185
+ model_dir = os.path.join(args.model_base_dir, args.model)
186
+ snapshot_step = load_checkpoint(sess, model_dir, gen_model_pretrain=True)
187
+ print('Loaded snapshot_step:', snapshot_step)
188
+
189
+ # Per-shard progress log
190
+ progress_log = args.progress_log
191
+ if shard_n > 1:
192
+ base, ext = os.path.splitext(progress_log)
193
+ progress_log = '{}.shard{}of{}{}'.format(base, shard_i, shard_n, ext)
194
+ os.makedirs(os.path.dirname(progress_log), exist_ok=True)
195
+ log_f = open(progress_log, 'a', buffering=1)
196
+ log_f.write('=== run started at {} (shard {}/{}) ===\n'.format(
197
+ time.strftime('%F %T'), shard_i, shard_n))
198
+ log_f.write('total_images={}\n'.format(len(items)))
199
+
200
+ total_time = 0.0
201
+ done = 0
202
+ failed = []
203
+
204
+ for idx, (rel_subdir, fname, full_path) in enumerate(items, 1):
205
+ basename = os.path.splitext(fname)[0]
206
+ out_dir = os.path.join(args.output_root, rel_subdir, basename)
207
+
208
+ # Skip if already done
209
+ if args.skip_existing and os.path.exists(
210
+ os.path.join(out_dir, basename + '_0_pred.png')):
211
+ print('[{}/{}] SKIP (exists): {}'.format(idx, len(items), full_path))
212
+ continue
213
+
214
+ t0 = time.time()
215
+ try:
216
+ num_strokes = process_one_image(
217
+ sess, sampling_model, paste_v3_func,
218
+ full_path, eval_hps, sample_hps,
219
+ out_dir, basename,
220
+ longer_infer_lens, state_dependent,
221
+ round_stop_state_num, stroke_acc_threshold)
222
+ elapsed = time.time() - t0
223
+ total_time += elapsed
224
+ done += 1
225
+ avg = total_time / done
226
+ line = ('[{}/{}] OK {:.1f}s strokes={} avg={:.1f}s {}\n'
227
+ .format(idx, len(items), elapsed, num_strokes, avg, full_path))
228
+ print(line, end='')
229
+ log_f.write(line)
230
+ except Exception as e:
231
+ elapsed = time.time() - t0
232
+ line = ('[{}/{}] FAIL {:.1f}s {} err={}\n'
233
+ .format(idx, len(items), elapsed, full_path, repr(e)))
234
+ print(line, end='')
235
+ log_f.write(line)
236
+ failed.append(full_path)
237
+
238
+ summary = ('\n=== Done. processed={}, failed={}, total_time={:.1f}s, '
239
+ 'avg={:.2f}s/img ===\n').format(
240
+ done, len(failed), total_time,
241
+ total_time / max(done, 1))
242
+ print(summary)
243
+ log_f.write(summary)
244
+ if failed:
245
+ log_f.write('Failed files:\n')
246
+ for f in failed:
247
+ log_f.write(' ' + f + '\n')
248
+ log_f.close()
249
+
250
+
251
+ if __name__ == '__main__':
252
+ main()
dataset_utils.py ADDED
@@ -0,0 +1,1224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import math
3
+ import random
4
+ import scipy.io
5
+ import numpy as np
6
+ import tensorflow as tf
7
+ from PIL import Image
8
+
9
+ from rasterization_utils.RealRenderer import GizehRasterizor as RealRenderer
10
+
11
+
12
+ def copy_hparams(hparams):
13
+ """Return a copy of an HParams instance."""
14
+ return tf.contrib.training.HParams(**hparams.values())
15
+
16
+
17
+ class GeneralRawDataLoader(object):
18
+ def __init__(self,
19
+ image_path,
20
+ raster_size,
21
+ test_dataset):
22
+ self.image_path = image_path
23
+ self.raster_size = raster_size
24
+ self.test_dataset = test_dataset
25
+
26
+ def get_test_image(self, random_cursor=True, init_cursor_on_undrawn_pixel=False, init_cursor_num=1):
27
+ input_image_data, image_size_test = self.gen_input_images(self.image_path)
28
+ input_image_data = np.array(input_image_data,
29
+ dtype=np.float32) # (1, image_size, image_size, (3)), [0.0-strokes, 1.0-BG]
30
+
31
+ return input_image_data, \
32
+ self.gen_init_cursors(input_image_data, random_cursor, init_cursor_on_undrawn_pixel, init_cursor_num), \
33
+ image_size_test
34
+
35
+ def gen_input_images(self, image_path):
36
+ img = Image.open(image_path).convert('RGB')
37
+ height, width = img.height, img.width
38
+ max_dim = max(height, width)
39
+
40
+ img = np.array(img, dtype=np.uint8)
41
+
42
+ if height != width:
43
+ # Padding to a square image
44
+ if self.test_dataset == 'clean_line_drawings':
45
+ pad_value = [255, 255, 255]
46
+ elif self.test_dataset == 'faces':
47
+ pad_value = [0, 0, 0]
48
+ else:
49
+ # TODO: find better padding pixel value
50
+ pad_value = img[height - 10, width - 10]
51
+
52
+ img_r, img_g, img_b = img[:, :, 0], img[:, :, 1], img[:, :, 2]
53
+ pad_width = max_dim - width
54
+ pad_height = max_dim - height
55
+
56
+ pad_img_r = np.pad(img_r, ((0, pad_height), (0, pad_width)), 'constant', constant_values=pad_value[0])
57
+ pad_img_g = np.pad(img_g, ((0, pad_height), (0, pad_width)), 'constant', constant_values=pad_value[1])
58
+ pad_img_b = np.pad(img_b, ((0, pad_height), (0, pad_width)), 'constant', constant_values=pad_value[2])
59
+ image_array = np.stack([pad_img_r, pad_img_g, pad_img_b], axis=-1)
60
+ else:
61
+ image_array = img
62
+
63
+ if self.test_dataset == 'faces' and max_dim != 256:
64
+ image_array_resize = Image.fromarray(image_array, 'RGB')
65
+ image_array_resize = image_array_resize.resize(size=(256, 256), resample=Image.BILINEAR)
66
+ image_array = np.array(image_array_resize, dtype=np.uint8)
67
+
68
+ assert image_array.shape[0] == image_array.shape[1]
69
+ img_size = image_array.shape[0]
70
+ image_array = image_array.astype(np.float32)
71
+ if self.test_dataset == 'clean_line_drawings':
72
+ image_array = image_array[:, :, 0] / 255.0 # [0.0-stroke, 1.0-BG]
73
+ else:
74
+ image_array = image_array / 255.0 # [0.0-stroke, 1.0-BG]
75
+ image_array = np.expand_dims(image_array, axis=0)
76
+ return image_array, img_size
77
+
78
+ def crop_patch(self, image, center, image_size, crop_size):
79
+ x0 = center[0] - crop_size // 2
80
+ x1 = x0 + crop_size
81
+ y0 = center[1] - crop_size // 2
82
+ y1 = y0 + crop_size
83
+ x0 = max(0, min(x0, image_size))
84
+ y0 = max(0, min(y0, image_size))
85
+ x1 = max(0, min(x1, image_size))
86
+ y1 = max(0, min(y1, image_size))
87
+ patch = image[y0:y1, x0:x1]
88
+ return patch
89
+
90
+ def gen_init_cursor_single(self, sketch_image, init_cursor_on_undrawn_pixel, misalign_size=3):
91
+ # sketch_image: [0.0-stroke, 1.0-BG]
92
+ image_size = sketch_image.shape[0]
93
+ if np.sum(1.0 - sketch_image) == 0:
94
+ center = np.zeros((2), dtype=np.int32)
95
+ return center
96
+ else:
97
+ while True:
98
+ center = np.random.randint(0, image_size, size=(2)) # (2), in large size
99
+ patch = 1.0 - self.crop_patch(sketch_image, center, image_size, self.raster_size)
100
+ if np.sum(patch) != 0:
101
+ if not init_cursor_on_undrawn_pixel:
102
+ return center.astype(np.float32) / float(image_size) # (2), in size [0.0, 1.0)
103
+ else:
104
+ center_patch = 1.0 - self.crop_patch(sketch_image, center, image_size, misalign_size)
105
+ if np.sum(center_patch) != 0:
106
+ return center.astype(np.float32) / float(image_size) # (2), in size [0.0, 1.0)
107
+
108
+ def gen_init_cursors(self, sketch_data, random_pos=True, init_cursor_on_undrawn_pixel=False, init_cursor_num=1):
109
+ init_cursor_batch_list = []
110
+ for cursor_i in range(init_cursor_num):
111
+ if random_pos:
112
+ init_cursor_batch = []
113
+ for i in range(len(sketch_data)):
114
+ sketch_image = sketch_data[i].copy().astype(np.float32) # [0.0-stroke, 1.0-BG]
115
+ center = self.gen_init_cursor_single(sketch_image, init_cursor_on_undrawn_pixel)
116
+ init_cursor_batch.append(center)
117
+
118
+ init_cursor_batch = np.stack(init_cursor_batch, axis=0) # (N, 2)
119
+ else:
120
+ raise Exception('Not finished')
121
+ init_cursor_batch_list.append(init_cursor_batch)
122
+
123
+ if init_cursor_num == 1:
124
+ init_cursor_batch = init_cursor_batch_list[0]
125
+ init_cursor_batch = np.expand_dims(init_cursor_batch, axis=1).astype(np.float32) # (N, 1, 2)
126
+ else:
127
+ init_cursor_batch = np.stack(init_cursor_batch_list, axis=1) # (N, init_cursor_num, 2)
128
+ init_cursor_batch = np.expand_dims(init_cursor_batch, axis=2).astype(
129
+ np.float32) # (N, init_cursor_num, 1, 2)
130
+
131
+ return init_cursor_batch
132
+
133
+
134
+ def load_dataset_testing(test_data_base_dir, test_dataset, test_img_name, model_params):
135
+ assert test_dataset in ['clean_line_drawings', 'rough_sketches', 'faces']
136
+ img_path = os.path.join(test_data_base_dir, test_dataset, test_img_name)
137
+ print('Loaded {} from {}'.format(img_path, test_dataset))
138
+
139
+ eval_model_params = copy_hparams(model_params)
140
+ eval_model_params.use_input_dropout = 0
141
+ eval_model_params.use_recurrent_dropout = 0
142
+ eval_model_params.use_output_dropout = 0
143
+ eval_model_params.batch_size = 1
144
+ eval_model_params.model_mode = 'sample'
145
+
146
+ sample_model_params = copy_hparams(eval_model_params)
147
+ sample_model_params.batch_size = 1 # only sample one at a time
148
+ sample_model_params.max_seq_len = 1 # sample one point at a time
149
+
150
+ test_set = GeneralRawDataLoader(img_path, eval_model_params.raster_size, test_dataset=test_dataset)
151
+
152
+ result = [test_set, eval_model_params, sample_model_params]
153
+ return result
154
+
155
+
156
+ class GeneralMultiObjectDataLoader(object):
157
+ def __init__(self,
158
+ stroke3_data,
159
+ batch_size,
160
+ raster_size,
161
+ image_size_small,
162
+ image_size_large,
163
+ is_bin,
164
+ is_train):
165
+ self.batch_size = batch_size # minibatch size
166
+ self.raster_size = raster_size
167
+ self.image_size_small = image_size_small
168
+ self.image_size_large = image_size_large
169
+ self.is_bin = is_bin
170
+ self.is_train = is_train
171
+
172
+ self.num_batches = len(stroke3_data) // self.batch_size
173
+ self.batch_idx = -1
174
+ print('batch_size', batch_size, ', num_batches', self.num_batches)
175
+
176
+ self.rasterizor = RealRenderer()
177
+ self.memory_sketch_data_batch = []
178
+
179
+ assert type(stroke3_data) is list
180
+ self.preprocess_rand_data(stroke3_data)
181
+
182
+ def preprocess_rand_data(self, stroke3):
183
+ if self.is_train:
184
+ random.shuffle(stroke3)
185
+ self.stroke3_data = stroke3
186
+
187
+ def cal_dist(self, posA, posB):
188
+ return np.sqrt(np.sum(np.power(posA - posB, 2)))
189
+
190
+ def invalid_position(self, pos, obj_size, pos_list, size_list):
191
+ if len(pos_list) == 0:
192
+ return False
193
+
194
+ pos_a = pos
195
+ size_a = obj_size
196
+ for i in range(len(pos_list)):
197
+ pos_b = pos_list[i]
198
+ size_b = size_list[i]
199
+
200
+ if self.cal_dist(pos_a, pos_b) < ((size_a + size_b) // 4):
201
+ return True
202
+
203
+ return False
204
+
205
+ def get_object_info(self, image_size, vary_thickness=True, try_total_times=3):
206
+ if image_size <= 172:
207
+ obj_num = 1
208
+ obj_thickness_list = [3]
209
+ elif image_size <= 225:
210
+ obj_num = random.randint(1, 2)
211
+ obj_thickness_list = np.random.randint(3, 4 + 1, size=(obj_num))
212
+ elif image_size <= 278:
213
+ obj_num = 2
214
+ obj_thickness_list = np.random.randint(3, 4 + 1, size=(obj_num))
215
+ elif image_size <= 331:
216
+ obj_num = random.randint(2, 3)
217
+ while True:
218
+ obj_thickness_list = np.random.randint(3, 5 + 1, size=(obj_num))
219
+ if np.sum(obj_thickness_list) / obj_num != 5 and np.sum(obj_thickness_list) < 13:
220
+ break
221
+ elif image_size <= 384:
222
+ obj_num = 3
223
+ while True:
224
+ obj_thickness_list = np.random.randint(3, 5 + 1, size=(obj_num))
225
+ if np.sum(obj_thickness_list) / obj_num != 5 and np.sum(obj_thickness_list) < 13:
226
+ break
227
+ else:
228
+ raise Exception('Invalid image_size', image_size)
229
+
230
+ if not vary_thickness:
231
+ num_item = len(obj_thickness_list)
232
+ obj_thickness_list = [3 for _ in range(num_item)]
233
+
234
+ obj_pos_list = []
235
+ obj_size_list = []
236
+ if obj_num == 1:
237
+ obj_size_list.append(image_size)
238
+ center = (image_size // 2, image_size // 2)
239
+ obj_pos_list.append(center)
240
+ else:
241
+ for obj_i in range(obj_num):
242
+ for try_i in range(try_total_times):
243
+ obj_size = random.randint(128, image_size * 3 // 4)
244
+ obj_center = np.random.randint(obj_size // 3, image_size - (obj_size // 3) + 1, size=(2))
245
+
246
+ if not self.invalid_position(obj_center, obj_size, obj_pos_list,
247
+ obj_size_list) or try_i == try_total_times - 1:
248
+ obj_pos_list.append(obj_center)
249
+ obj_size_list.append(obj_size)
250
+ break
251
+
252
+ assert len(obj_size_list) == len(obj_pos_list) == len(obj_thickness_list) == obj_num
253
+ return obj_num, obj_size_list, obj_pos_list, obj_thickness_list
254
+
255
+ def object_pasting(self, obj_img, canvas_img, center):
256
+ c_y, c_x = center[0], center[1]
257
+ obj_size = obj_img.shape[0]
258
+ canvas_size = canvas_img.shape[0]
259
+ box_left = max(0, c_x - obj_size // 2)
260
+ box_right = min(canvas_size, c_x + obj_size // 2)
261
+ box_up = max(0, c_y - obj_size // 2)
262
+ box_bottom = min(canvas_size, c_y + obj_size // 2)
263
+
264
+ box_canvas = canvas_img[box_up: box_bottom, box_left: box_right]
265
+
266
+ obj_box_up = box_up - (c_y - obj_size // 2)
267
+ obj_box_left = box_left - (c_x - obj_size // 2)
268
+ box_obj = obj_img[obj_box_up: obj_box_up + (box_bottom - box_up),
269
+ obj_box_left: obj_box_left + (box_right - box_left)]
270
+
271
+ box_canvas += box_obj
272
+
273
+ rst_canvas = np.copy(canvas_img)
274
+ rst_canvas[box_up: box_bottom, box_left: box_right] = box_canvas
275
+ rst_canvas = np.clip(rst_canvas, 0.0, 1.0)
276
+
277
+ return rst_canvas
278
+
279
+ def get_multi_object_image(self, img_size, vary_thickness):
280
+ object_num, object_size_list, object_pos_list, object_thickness_list = self.get_object_info(
281
+ img_size, vary_thickness=vary_thickness)
282
+
283
+ canvas = np.zeros(shape=(img_size, img_size), dtype=np.float32)
284
+
285
+ for obj_i in range(object_num):
286
+ rand_idx = np.random.randint(0, len(self.stroke3_data))
287
+ rand_stroke3 = self.stroke3_data[rand_idx] # (N_points, 3)
288
+
289
+ object_size = object_size_list[obj_i]
290
+ object_enter = object_pos_list[obj_i]
291
+ object_thickness = object_thickness_list[obj_i]
292
+
293
+ stroke_image = self.gen_stroke_images([rand_stroke3], object_size, object_thickness)
294
+ stroke_image = 1.0 - stroke_image[0] # (image_size, image_size), [0.0-BG, 1.0-strokes]
295
+
296
+ canvas = self.object_pasting(stroke_image, canvas, object_enter) # [0.0-BG, 1.0-strokes]
297
+
298
+ canvas = 1.0 - canvas # [0.0-strokes, 1.0-BG]
299
+ return canvas
300
+
301
+ def get_batch_from_memory(self, memory_idx, vary_thickness, fixed_image_size=-1, random_cursor=True,
302
+ init_cursor_on_undrawn_pixel=False, init_cursor_num=1):
303
+ if len(self.memory_sketch_data_batch) >= memory_idx + 1:
304
+ sketch_data_batch = self.memory_sketch_data_batch[memory_idx]
305
+ sketch_data_batch = np.expand_dims(sketch_data_batch,
306
+ axis=0) # (1, image_size, image_size), [0.0-strokes, 1.0-BG]
307
+ image_size_rand = sketch_data_batch.shape[1]
308
+ else:
309
+ if fixed_image_size == -1:
310
+ image_size_rand = random.randint(self.image_size_small, self.image_size_large)
311
+ else:
312
+ image_size_rand = fixed_image_size
313
+
314
+ multi_obj_image = self.get_multi_object_image(image_size_rand, vary_thickness) # [0.0-strokes, 1.0-BG]
315
+ self.memory_sketch_data_batch.append(multi_obj_image)
316
+ sketch_data_batch = np.expand_dims(multi_obj_image,
317
+ axis=0) # (1, image_size, image_size), [0.0-strokes, 1.0-BG]
318
+
319
+ return None, sketch_data_batch, \
320
+ self.gen_init_cursors(sketch_data_batch, random_cursor, init_cursor_on_undrawn_pixel, init_cursor_num), \
321
+ image_size_rand
322
+
323
+ def get_batch_multi_res(self, loop_num, vary_thickness, random_cursor=True,
324
+ init_cursor_on_undrawn_pixel=False, init_cursor_num=1):
325
+ sketch_data_batch = []
326
+ init_cursors_batch = []
327
+ image_size_batch = []
328
+ batch_size_per_loop = self.batch_size // loop_num
329
+ for loop_i in range(loop_num):
330
+ image_size_rand = random.randint(self.image_size_small, self.image_size_large)
331
+ sketch_data_sub_batch = []
332
+ for batch_i in range(batch_size_per_loop):
333
+ multi_obj_image = self.get_multi_object_image(image_size_rand, vary_thickness) # [0.0-strokes, 1.0-BG]
334
+ sketch_data_sub_batch.append(multi_obj_image)
335
+ sketch_data_sub_batch = np.stack(sketch_data_sub_batch,
336
+ axis=0) # (N, image_size, image_size), [0.0-strokes, 1.0-BG]
337
+
338
+ init_cursors_sub_batch = self.gen_init_cursors(sketch_data_sub_batch, random_cursor,
339
+ init_cursor_on_undrawn_pixel, init_cursor_num)
340
+ sketch_data_batch.append(sketch_data_sub_batch)
341
+ init_cursors_batch.append(init_cursors_sub_batch)
342
+ image_size_batch.append(image_size_rand)
343
+
344
+ return None, \
345
+ sketch_data_batch, \
346
+ init_cursors_batch, \
347
+ image_size_batch
348
+
349
+ def gen_stroke_images(self, stroke3_list, image_size, stroke_width):
350
+ """
351
+ :param stroke3_list: list of (batch_size,), each with (N_points, 3)
352
+ :param image_size:
353
+ :return:
354
+ """
355
+ gt_image_array = self.rasterizor.raster_func(stroke3_list, image_size, stroke_width=stroke_width,
356
+ is_bin=self.is_bin, version='v2')
357
+ gt_image_array = np.stack(gt_image_array, axis=0)
358
+ gt_image_array = 1.0 - gt_image_array # (batch_size, image_size, image_size), [0.0-strokes, 1.0-BG]
359
+ return gt_image_array
360
+
361
+ def crop_patch(self, image, center, image_size, crop_size):
362
+ x0 = center[0] - crop_size // 2
363
+ x1 = x0 + crop_size
364
+ y0 = center[1] - crop_size // 2
365
+ y1 = y0 + crop_size
366
+ x0 = max(0, min(x0, image_size))
367
+ y0 = max(0, min(y0, image_size))
368
+ x1 = max(0, min(x1, image_size))
369
+ y1 = max(0, min(y1, image_size))
370
+ patch = image[y0:y1, x0:x1]
371
+ return patch
372
+
373
+ def gen_init_cursor_single(self, sketch_image, init_cursor_on_undrawn_pixel, misalign_size=3):
374
+ # sketch_image: [0.0-stroke, 1.0-BG]
375
+ image_size = sketch_image.shape[0]
376
+ if np.sum(1.0 - sketch_image) == 0:
377
+ center = np.zeros((2), dtype=np.int32)
378
+ return center
379
+ else:
380
+ while True:
381
+ center = np.random.randint(0, image_size, size=(2)) # (2), in large size
382
+ patch = 1.0 - self.crop_patch(sketch_image, center, image_size, self.raster_size)
383
+ if np.sum(patch) != 0:
384
+ if not init_cursor_on_undrawn_pixel:
385
+ return center.astype(np.float32) / float(image_size) # (2), in size [0.0, 1.0)
386
+ else:
387
+ center_patch = 1.0 - self.crop_patch(sketch_image, center, image_size, misalign_size)
388
+ if np.sum(center_patch) != 0:
389
+ return center.astype(np.float32) / float(image_size) # (2), in size [0.0, 1.0)
390
+
391
+ def gen_init_cursors(self, sketch_data, random_pos=True, init_cursor_on_undrawn_pixel=False, init_cursor_num=1):
392
+ init_cursor_batch_list = []
393
+ for cursor_i in range(init_cursor_num):
394
+ if random_pos:
395
+ init_cursor_batch = []
396
+ for i in range(len(sketch_data)):
397
+ sketch_image = sketch_data[i].copy().astype(np.float32) # [0.0-stroke, 1.0-BG]
398
+ center = self.gen_init_cursor_single(sketch_image, init_cursor_on_undrawn_pixel)
399
+ init_cursor_batch.append(center)
400
+
401
+ init_cursor_batch = np.stack(init_cursor_batch, axis=0) # (N, 2)
402
+ else:
403
+ raise Exception('Not finished')
404
+ init_cursor_batch_list.append(init_cursor_batch)
405
+
406
+ if init_cursor_num == 1:
407
+ init_cursor_batch = init_cursor_batch_list[0]
408
+ init_cursor_batch = np.expand_dims(init_cursor_batch, axis=1).astype(np.float32) # (N, 1, 2)
409
+ else:
410
+ init_cursor_batch = np.stack(init_cursor_batch_list, axis=1) # (N, init_cursor_num, 2)
411
+ init_cursor_batch = np.expand_dims(init_cursor_batch, axis=2).astype(
412
+ np.float32) # (N, init_cursor_num, 1, 2)
413
+
414
+ return init_cursor_batch
415
+
416
+
417
+ def load_dataset_multi_object(dataset_base_dir, model_params):
418
+ train_stroke3_data = []
419
+ val_stroke3_data = []
420
+
421
+ if model_params.data_set == 'clean_line_drawings':
422
+ def load_qd_npz_data(npz_path):
423
+ data = np.load(npz_path, encoding='latin1', allow_pickle=True)
424
+ selected_strokes3 = data['stroke3'] # (N_sketches,), each with (N_points, 3)
425
+ selected_strokes3 = selected_strokes3.tolist()
426
+ return selected_strokes3
427
+
428
+ base_dir_clean = 'QuickDraw-clean'
429
+ cates = ['airplane', 'bus', 'car', 'sailboat', 'bird', 'cat', 'dog',
430
+ # 'rabbit',
431
+ 'tree', 'flower',
432
+ # 'circle', 'line',
433
+ 'zigzag'
434
+ ]
435
+
436
+ for cate in cates:
437
+ train_cate_sketch_data_npz_path = os.path.join(dataset_base_dir, base_dir_clean, 'train', cate + '.npz')
438
+ val_cate_sketch_data_npz_path = os.path.join(dataset_base_dir, base_dir_clean, 'test', cate + '.npz')
439
+ print(train_cate_sketch_data_npz_path)
440
+
441
+ train_cate_stroke3_data = load_qd_npz_data(
442
+ train_cate_sketch_data_npz_path) # list of (N_sketches,), each with (N_points, 3)
443
+ val_cate_stroke3_data = load_qd_npz_data(val_cate_sketch_data_npz_path)
444
+ train_stroke3_data += train_cate_stroke3_data
445
+ val_stroke3_data += val_cate_stroke3_data
446
+ else:
447
+ raise Exception('Unknown data type:', model_params.data_set)
448
+
449
+ print('Loaded {}/{} from {}'.format(len(train_stroke3_data), len(val_stroke3_data), model_params.data_set))
450
+ print('model_params.max_seq_len %i.' % model_params.max_seq_len)
451
+
452
+ eval_sample_model_params = copy_hparams(model_params)
453
+ eval_sample_model_params.use_input_dropout = 0
454
+ eval_sample_model_params.use_recurrent_dropout = 0
455
+ eval_sample_model_params.use_output_dropout = 0
456
+ eval_sample_model_params.batch_size = 1 # only sample one at a time
457
+ eval_sample_model_params.model_mode = 'eval_sample'
458
+
459
+ train_set = GeneralMultiObjectDataLoader(train_stroke3_data,
460
+ model_params.batch_size, model_params.raster_size,
461
+ model_params.image_size_small, model_params.image_size_large,
462
+ model_params.bin_gt, is_train=True)
463
+ val_set = GeneralMultiObjectDataLoader(val_stroke3_data,
464
+ eval_sample_model_params.batch_size, eval_sample_model_params.raster_size,
465
+ eval_sample_model_params.image_size_small,
466
+ eval_sample_model_params.image_size_large,
467
+ eval_sample_model_params.bin_gt, is_train=False)
468
+
469
+ result = [train_set, val_set, model_params, eval_sample_model_params]
470
+ return result
471
+
472
+
473
+ class GeneralDataLoaderMultiObjectRough(object):
474
+ def __init__(self,
475
+ photo_data,
476
+ sketch_data,
477
+ texture_data,
478
+ shadow_data,
479
+ batch_size,
480
+ raster_size,
481
+ image_size_small,
482
+ image_size_large,
483
+ is_train):
484
+ self.batch_size = batch_size # minibatch size
485
+ self.raster_size = raster_size
486
+ self.image_size_small = image_size_small
487
+ self.image_size_large = image_size_large
488
+ self.is_train = is_train
489
+
490
+ assert photo_data is not None
491
+ assert len(photo_data) == len(sketch_data)
492
+ # self.num_batches = len(sketch_data) // self.batch_size
493
+ self.batch_idx = -1
494
+ print('batch_size', batch_size)
495
+
496
+ assert type(photo_data) is list
497
+ assert type(sketch_data) is list
498
+ assert type(texture_data) is list and len(texture_data) > 0
499
+ assert type(shadow_data) is list and len(shadow_data) > 0
500
+ self.photo_data = photo_data
501
+ self.sketch_data = sketch_data
502
+ self.texture_data = texture_data # list of (H, W, 3), [0, 255], uint8
503
+ self.shadow_data = shadow_data # list of (H, W), [0, 255], uint8
504
+
505
+ self.memory_photo_data_batch = []
506
+ self.memory_sketch_data_batch = []
507
+
508
+ def rough_augmentation(self, raw_photo, texture_prob=0.20, noise_prob=0.15, shadow_prob=0.20):
509
+ # raw_photo: (H, W), [0.0-stroke, 1.0-BG]
510
+ aug_photo_rgb = np.stack([raw_photo for _ in range(3)], axis=-1)
511
+
512
+ def texture_generation(texture_list, image_shape):
513
+ while True:
514
+ random_texture_id = random.randint(0, len(texture_list) - 1)
515
+ texture_large = texture_list[random_texture_id]
516
+ t_w, t_h = texture_large.shape[1], texture_large.shape[0]
517
+ i_w, i_h = image_shape[1], image_shape[0]
518
+
519
+ if t_h >= i_h and t_w >= i_w:
520
+ texture_large = np.copy(texture_large).astype(np.float32)
521
+ crop_y = random.randint(0, t_h - i_h)
522
+ crop_x = random.randint(0, t_w - i_w)
523
+ crop_texture = texture_large[crop_y: crop_y + i_h, crop_x: crop_x + i_w, :]
524
+ return crop_texture
525
+
526
+ def texture_change(rough_img_, all_textures):
527
+ # rough_img_: (H, W, 3), [0.0-stroke, 1.0-BG]
528
+
529
+ texture_image = texture_generation(all_textures, rough_img_.shape) # (h, w, 3)
530
+ texture_image /= 255.0
531
+
532
+ rand_b = np.random.uniform(1.0, 2.0, size=rough_img_.shape)
533
+ textured_img = rough_img_ * (texture_image / rand_b + (rand_b - 1.0) / rand_b) # [0.0, 1.0]
534
+ return textured_img
535
+
536
+ def noise_change(rough_img_, noise_scale=25):
537
+ # rough_img_: (H, W, 3), [0.0, 1.0]
538
+ rough_img_255 = rough_img_ * 255.0
539
+
540
+ rand_noise = np.random.uniform(-1.0, 1.0, size=rough_img_255.shape) * noise_scale
541
+ # rand_noise = np.random.normal(size=rough_img.shape) * noise_scale
542
+ noise_img = rough_img_255 + rand_noise
543
+ noise_img = np.clip(noise_img, 0.0, 255.0)
544
+ noise_img /= 255.0
545
+ return noise_img
546
+
547
+ def shadow_change(rough_img_, all_shadows):
548
+ # rough_img_: (H, W, 3), [0.0, 1.0]
549
+ rough_img_255 = rough_img_ * 255.0
550
+
551
+ shadow_i = random.randint(0, len(all_shadows) - 1)
552
+ shadow_full = all_shadows[shadow_i] # (H, W), [0, 255]
553
+ shadow_img_size = shadow_full.shape[0]
554
+
555
+ while True:
556
+ position = np.random.randint(-shadow_img_size // 2, shadow_img_size // 2, (2))
557
+ if abs(position[0]) > (shadow_img_size // 8) and abs(position[1]) > (shadow_img_size // 8):
558
+ break
559
+ position += (shadow_img_size // 2)
560
+
561
+ crop_up = shadow_img_size - position[0]
562
+ crop_left = shadow_img_size - position[1]
563
+
564
+ shadow_image_large = shadow_full[crop_up: crop_up + shadow_img_size, crop_left: crop_left + shadow_img_size]
565
+ shadow_bg = Image.fromarray(shadow_image_large, 'L')
566
+ shadow_bg = shadow_bg.resize(size=(rough_img_255.shape[1], rough_img_255.shape[0]), resample=Image.BILINEAR)
567
+ shadow_bg = np.array(shadow_bg, dtype=np.float32) / 255.0 # [0.0-shadow, 1.0-BG]
568
+ shadow_bg = np.stack([shadow_bg for _ in range(3)], axis=-1)
569
+
570
+ shadow_img = rough_img_255 * shadow_bg
571
+ shadow_img /= 255.0
572
+ return shadow_img
573
+
574
+ if random.random() <= texture_prob:
575
+ aug_photo_rgb = texture_change(aug_photo_rgb, self.texture_data) # (H, W, 3), [0.0, 1.0]
576
+ if random.random() <= noise_prob:
577
+ aug_photo_rgb = noise_change(aug_photo_rgb) # (H, W, 3), [0.0, 1.0]
578
+ if random.random() <= shadow_prob:
579
+ aug_photo_rgb = shadow_change(aug_photo_rgb, self.shadow_data) # (H, W, 3), [0.0, 1.0]
580
+
581
+ return aug_photo_rgb
582
+
583
+ def image_interpolation(self, photo, sketch, photo_prob):
584
+ interp_photo = photo * photo_prob + sketch * (1.0 - photo_prob)
585
+ interp_photo = np.clip(interp_photo, 0.0, 1.0)
586
+ return interp_photo
587
+
588
+ def get_batch_from_memory(self, memory_idx, interpolate_type, fixed_image_size=-1, random_cursor=True,
589
+ photo_prob=1.0, init_cursor_num=1):
590
+ if len(self.memory_sketch_data_batch) >= memory_idx + 1:
591
+ photo_data_batch = self.memory_photo_data_batch[memory_idx]
592
+ sketch_data_batch = self.memory_sketch_data_batch[memory_idx]
593
+ image_size_rand = sketch_data_batch.shape[1]
594
+ else:
595
+ if fixed_image_size == -1:
596
+ image_size_rand = random.randint(self.image_size_small, self.image_size_large)
597
+ else:
598
+ image_size_rand = fixed_image_size
599
+
600
+ # photo_prob = 0.0 if photo_prob_type == 'zero' else 1.0
601
+ photo_data_batch, sketch_data_batch = self.select_sketch(
602
+ image_size_rand) # both: (H, W), [0.0-stroke, 1.0-BG]
603
+ photo_data_batch = self.rough_augmentation(photo_data_batch) # (H, W, 3), [0.0-stroke, 1.0-BG]
604
+
605
+ self.memory_photo_data_batch.append(photo_data_batch)
606
+ self.memory_sketch_data_batch.append(sketch_data_batch)
607
+
608
+ if interpolate_type == 'prob':
609
+ if random.random() >= photo_prob:
610
+ photo_data_batch = np.stack([sketch_data_batch for _ in range(3)],
611
+ axis=-1) # (H, W, 3), [0.0-stroke, 1.0-BG]
612
+ elif interpolate_type == 'image':
613
+ photo_data_batch = self.image_interpolation(
614
+ photo_data_batch, np.stack([sketch_data_batch for _ in range(3)], axis=-1), photo_prob)
615
+ else:
616
+ raise Exception('Unknown interpolate_type', interpolate_type)
617
+
618
+ photo_data_batch = np.expand_dims(photo_data_batch, axis=0) # (1, image_size, image_size, 3)
619
+ sketch_data_batch = np.expand_dims(sketch_data_batch,
620
+ axis=0) # (1, image_size, image_size), [0.0-strokes, 1.0-BG]
621
+
622
+ return photo_data_batch, sketch_data_batch, \
623
+ self.gen_init_cursors(sketch_data_batch, random_cursor, init_cursor_num), image_size_rand
624
+
625
+ def select_sketch(self, image_size_rand):
626
+ resolution_idx = image_size_rand - self.image_size_small
627
+ img_idx = random.randint(0, len(self.sketch_data[resolution_idx]) - 1)
628
+ assert img_idx != -1
629
+
630
+ selected_sketch = self.sketch_data[resolution_idx][img_idx] # [0-stroke, 255-BG], uint8
631
+ selected_photo = self.photo_data[resolution_idx][img_idx] # [0-stroke, 255-BG], uint8
632
+
633
+ rst_sketch_image = selected_sketch.astype(np.float32) / 255.0 # [0.0-stroke, 1.0-BG]
634
+ rst_photo_image = selected_photo.astype(np.float32) / 255.0 # [0.0-stroke, 1.0-BG]
635
+
636
+ return rst_photo_image, rst_sketch_image
637
+
638
+ def get_batch_multi_res(self, loop_num, interpolate_type, random_cursor=True, init_cursor_num=1, photo_prob=1.0):
639
+ photo_data_batch = []
640
+ sketch_data_batch = []
641
+ init_cursors_batch = []
642
+ image_size_batch = []
643
+ batch_size_per_loop = self.batch_size // loop_num
644
+ for loop_i in range(loop_num):
645
+ image_size_rand = random.randint(self.image_size_small, self.image_size_large)
646
+
647
+ photo_data_sub_batch = []
648
+ sketch_data_sub_batch = []
649
+ for img_i in range(batch_size_per_loop):
650
+ photo_patch, sketch_patch = self.select_sketch(image_size_rand) # both: (H, W), [0.0-stroke, 1.0-BG]
651
+ photo_patch = self.rough_augmentation(photo_patch) # (H, W, 3), [0.0-stroke, 1.0-BG]
652
+
653
+ if interpolate_type == 'prob':
654
+ if random.random() >= photo_prob:
655
+ photo_patch = np.stack([sketch_patch for _ in range(3)],
656
+ axis=-1) # (H, W, 3), [0.0-stroke, 1.0-BG]
657
+ elif interpolate_type == 'image':
658
+ photo_patch = self.image_interpolation(
659
+ photo_patch, np.stack([sketch_patch for _ in range(3)], axis=-1), photo_prob)
660
+ else:
661
+ raise Exception('Unknown interpolate_type', interpolate_type)
662
+
663
+ photo_data_sub_batch.append(photo_patch)
664
+ sketch_data_sub_batch.append(sketch_patch)
665
+
666
+ photo_data_sub_batch = np.stack(photo_data_sub_batch,
667
+ axis=0) # (N, image_size, image_size, 3), [0.0-strokes, 1.0-BG]
668
+ sketch_data_sub_batch = np.stack(sketch_data_sub_batch,
669
+ axis=0) # (N, image_size, image_size), [0.0-strokes, 1.0-BG]
670
+ init_cursors_sub_batch = self.gen_init_cursors(sketch_data_sub_batch, random_cursor, init_cursor_num)
671
+ photo_data_batch.append(photo_data_sub_batch)
672
+ sketch_data_batch.append(sketch_data_sub_batch)
673
+ init_cursors_batch.append(init_cursors_sub_batch)
674
+ image_size_batch.append(image_size_rand)
675
+
676
+ return photo_data_batch, sketch_data_batch, init_cursors_batch, image_size_batch
677
+
678
+ def crop_patch(self, image, center, image_size, crop_size):
679
+ x0 = center[0] - crop_size // 2
680
+ x1 = x0 + crop_size
681
+ y0 = center[1] - crop_size // 2
682
+ y1 = y0 + crop_size
683
+ x0 = max(0, min(x0, image_size))
684
+ y0 = max(0, min(y0, image_size))
685
+ x1 = max(0, min(x1, image_size))
686
+ y1 = max(0, min(y1, image_size))
687
+ patch = image[y0:y1, x0:x1]
688
+ return patch
689
+
690
+ def gen_init_cursor_single(self, sketch_image):
691
+ # sketch_image: [0.0-stroke, 1.0-BG]
692
+ image_size = sketch_image.shape[0]
693
+ if np.sum(1.0 - sketch_image) == 0:
694
+ center = np.zeros((2), dtype=np.int32)
695
+ return center
696
+ else:
697
+ while True:
698
+ center = np.random.randint(0, image_size, size=(2)) # (2), in large size
699
+ patch = 1.0 - self.crop_patch(sketch_image, center, image_size, self.raster_size)
700
+ if np.sum(patch) != 0:
701
+ return center.astype(np.float32) / float(image_size) # (2), in size [0.0, 1.0)
702
+
703
+ def gen_init_cursors(self, sketch_data, random_pos=True, init_cursor_num=1):
704
+ init_cursor_batch_list = []
705
+ for cursor_i in range(init_cursor_num):
706
+ if random_pos:
707
+ init_cursor_batch = []
708
+ for i in range(len(sketch_data)):
709
+ sketch_image = sketch_data[i].copy().astype(np.float32) # [0.0-stroke, 1.0-BG]
710
+ center = self.gen_init_cursor_single(sketch_image)
711
+ init_cursor_batch.append(center)
712
+
713
+ init_cursor_batch = np.stack(init_cursor_batch, axis=0) # (N, 2)
714
+ else:
715
+ raise Exception('Not finished')
716
+ init_cursor_batch_list.append(init_cursor_batch)
717
+
718
+ if init_cursor_num == 1:
719
+ init_cursor_batch = init_cursor_batch_list[0]
720
+ init_cursor_batch = np.expand_dims(init_cursor_batch, axis=1).astype(np.float32) # (N, 1, 2)
721
+ else:
722
+ init_cursor_batch = np.stack(init_cursor_batch_list, axis=1) # (N, init_cursor_num, 2)
723
+ init_cursor_batch = np.expand_dims(init_cursor_batch, axis=2).astype(
724
+ np.float32) # (N, init_cursor_num, 1, 2)
725
+
726
+ return init_cursor_batch
727
+
728
+
729
+ def load_dataset_multi_object_rough(dataset_base_dir, model_params):
730
+ train_photo_data = []
731
+ train_sketch_data = []
732
+ val_photo_data = []
733
+ val_sketch_data = []
734
+ texture_data = []
735
+ shadow_data = []
736
+
737
+ if model_params.data_set == 'rough_sketches':
738
+ base_dir_rough = 'QuickDraw-rough'
739
+
740
+ def load_sketch_data(mat_path):
741
+ sketch_data_mat = scipy.io.loadmat(mat_path)
742
+ sketch_data = sketch_data_mat['sketch_array']
743
+ sketch_data = np.array(sketch_data, dtype=np.uint8) # (N, resolution, resolution), [0-strokes, 255-BG]
744
+ return sketch_data
745
+
746
+ def load_photo_data(mat_path):
747
+ photo_data_mat = scipy.io.loadmat(mat_path)
748
+ photo_data = photo_data_mat['image_array']
749
+ photo_data = np.array(photo_data, dtype=np.uint8) # (N, resolution, resolution), [0-strokes, 255-BG]
750
+ return photo_data
751
+
752
+ def load_normal_data(img_path):
753
+ assert '.png' in img_path or '.jpg'
754
+ img = Image.open(img_path).convert('RGB')
755
+ img = np.array(img, dtype=np.uint8) # (H, W, 3), [0-stroke, 255-BG], uint8
756
+ return img
757
+
758
+ ## Texture
759
+ texture_base = os.path.join(dataset_base_dir, base_dir_rough, 'texture')
760
+ all_texture = os.listdir(texture_base)
761
+ all_texture.sort()
762
+
763
+ for file_name in all_texture:
764
+ texture_path = os.path.join(texture_base, file_name)
765
+ texture_uint8 = load_normal_data(texture_path)
766
+ texture_data.append(texture_uint8)
767
+
768
+ ## shadow
769
+ def process_angle(img, temp_size):
770
+ padded_img = img.copy()
771
+ padded_img[0, 0:temp_size] -= 1
772
+ padded_img[0, -(temp_size + 1):-1] -= 1
773
+ padded_img[-1, 0:temp_size] -= 1
774
+ padded_img[-1, -(temp_size + 1):-1] -= 1
775
+
776
+ padded_img[0:temp_size, 0] -= 1
777
+ padded_img[0:temp_size, -1] -= 1
778
+ padded_img[-(temp_size + 1):-1, 0] -= 1
779
+ padded_img[-(temp_size + 1):-1, -1] -= 1
780
+ return padded_img
781
+
782
+ def pad_img(ori_img, pad_value):
783
+ padded_img = np.pad(ori_img, 1, constant_values=pad_value)
784
+ img_h, img_w = padded_img.shape[0], padded_img.shape[1]
785
+
786
+ temp_size = img_h // 3
787
+ padded_img = process_angle(padded_img, temp_size)
788
+
789
+ temp_size = img_h // 9
790
+ padded_img = process_angle(padded_img, temp_size)
791
+
792
+ temp_size = img_h // 15
793
+ padded_img = process_angle(padded_img, temp_size)
794
+
795
+ temp_size = img_h // 21
796
+ padded_img = process_angle(padded_img, temp_size)
797
+
798
+ padded_img = np.clip(padded_img, 0, 255)
799
+
800
+ return padded_img
801
+
802
+ def shadow_generation(transparency, shadow_img_size=1024):
803
+ deepest_value = int(255 * transparency)
804
+
805
+ center_patch = np.zeros((shadow_img_size // 2, shadow_img_size // 2), dtype=np.uint8)
806
+ center_patch.fill(255)
807
+
808
+ pad_gap = shadow_img_size // 2
809
+ shadow_patch = center_patch.copy()
810
+ for i in range(pad_gap):
811
+ curr_pad_value = 255.0 - float(255.0 - deepest_value) / float(pad_gap) * (i + 1)
812
+ shadow_patch = pad_img(shadow_patch, pad_value=curr_pad_value)
813
+
814
+ for i in range(shadow_img_size // 4):
815
+ shadow_patch = pad_img(shadow_patch, pad_value=deepest_value)
816
+
817
+ assert shadow_patch.shape[0] == shadow_img_size * 2, shadow_patch.shape[0]
818
+ return shadow_patch
819
+
820
+ for transparency_ in range(90, 95 + 1):
821
+ transparency = transparency_ / 100.0
822
+ shadow_full = shadow_generation(transparency)
823
+ shadow_data.append(shadow_full)
824
+
825
+ splits = ['train', 'test']
826
+
827
+ resolutions = [model_params.image_size_small, model_params.image_size_large]
828
+
829
+ for resolution in range(resolutions[0], resolutions[1] + 1):
830
+ for split in splits:
831
+ sketch_mat1_path = os.path.join(dataset_base_dir, base_dir_rough, 'model_pencil1',
832
+ 'sketch', split, 'res_' + str(resolution) + '.mat')
833
+ photo_mat1_path = os.path.join(dataset_base_dir, base_dir_rough, 'model_pencil1',
834
+ 'photo', split, 'res_' + str(resolution) + '.mat')
835
+ sketch_data1_uint8 = load_sketch_data(
836
+ sketch_mat1_path) # (N, resolution, resolution), [0-strokes, 255-BG]
837
+ photo_data1_uint8 = load_photo_data(photo_mat1_path) # (N, resolution, resolution), [0-strokes, 255-BG]
838
+
839
+ sketch_mat2_path = os.path.join(dataset_base_dir, base_dir_rough, 'model_pencil2',
840
+ 'sketch', split, 'res_' + str(resolution) + '.mat')
841
+ photo_mat2_path = os.path.join(dataset_base_dir, base_dir_rough, 'model_pencil2',
842
+ 'photo', split, 'res_' + str(resolution) + '.mat')
843
+ sketch_data2_uint8 = load_sketch_data(
844
+ sketch_mat2_path) # (N, resolution, resolution), [0-strokes, 255-BG]
845
+ photo_data2_uint8 = load_photo_data(photo_mat2_path) # (N, resolution, resolution), [0-strokes, 255-BG]
846
+
847
+ sketch_data_uint8 = np.concatenate([sketch_data1_uint8, sketch_data2_uint8],
848
+ axis=0) # (N, resolution, resolution), [0-strokes, 255-BG]
849
+ photo_data_uint8 = np.concatenate([photo_data1_uint8, photo_data2_uint8],
850
+ axis=0) # (N, resolution, resolution), [0-strokes, 255-BG]
851
+
852
+ if split == 'train':
853
+ train_photo_data.append(photo_data_uint8)
854
+ train_sketch_data.append(sketch_data_uint8)
855
+ else:
856
+ val_photo_data.append(photo_data_uint8)
857
+ val_sketch_data.append(sketch_data_uint8)
858
+
859
+ assert len(train_sketch_data) == len(train_photo_data)
860
+ assert len(val_sketch_data) == len(val_photo_data)
861
+ else:
862
+ raise Exception('Unknown data type:', model_params.data_set)
863
+
864
+ print('Loaded {}/{} from {}'.format(len(train_sketch_data), len(val_sketch_data), model_params.data_set))
865
+ print('model_params.max_seq_len %i.' % model_params.max_seq_len)
866
+
867
+ eval_sample_model_params = copy_hparams(model_params)
868
+ eval_sample_model_params.use_input_dropout = 0
869
+ eval_sample_model_params.use_recurrent_dropout = 0
870
+ eval_sample_model_params.use_output_dropout = 0
871
+ eval_sample_model_params.batch_size = 1 # only sample one at a time
872
+ eval_sample_model_params.model_mode = 'eval_sample'
873
+
874
+ train_set = GeneralDataLoaderMultiObjectRough(train_photo_data, train_sketch_data,
875
+ texture_data, shadow_data,
876
+ model_params.batch_size, model_params.raster_size,
877
+ model_params.image_size_small, model_params.image_size_large,
878
+ is_train=True)
879
+ val_set = GeneralDataLoaderMultiObjectRough(val_photo_data, val_sketch_data,
880
+ texture_data, shadow_data,
881
+ eval_sample_model_params.batch_size,
882
+ eval_sample_model_params.raster_size,
883
+ eval_sample_model_params.image_size_small,
884
+ eval_sample_model_params.image_size_large,
885
+ is_train=False)
886
+
887
+ result = [
888
+ train_set, val_set, model_params, eval_sample_model_params
889
+ ]
890
+ return result
891
+
892
+
893
+ class GeneralDataLoaderNormalImageLinear(object):
894
+ def __init__(self,
895
+ photo_data,
896
+ sketch_data,
897
+ sketch_shape,
898
+ batch_size,
899
+ raster_size,
900
+ image_size_small,
901
+ image_size_large,
902
+ random_image_size,
903
+ flip_prob,
904
+ rotate_prob,
905
+ is_train):
906
+ self.batch_size = batch_size # minibatch size
907
+ self.raster_size = raster_size
908
+ self.image_size_small = image_size_small
909
+ self.image_size_large = image_size_large
910
+ self.random_image_size = random_image_size
911
+ self.is_train = is_train
912
+
913
+ assert photo_data is not None
914
+ assert len(photo_data) == len(sketch_data)
915
+ self.num_batches = len(sketch_data) // self.batch_size
916
+ self.batch_idx = -1
917
+ print('batch_size', batch_size, ', num_batches', self.num_batches)
918
+
919
+ self.flip_prob = flip_prob
920
+ self.rotate_prob = rotate_prob
921
+
922
+ assert type(photo_data) is list
923
+ assert type(sketch_data) is list
924
+ self.photo_data = photo_data
925
+ self.sketch_data = sketch_data
926
+ self.sketch_shape = sketch_shape
927
+
928
+ def get_batch_from_memory(self, memory_idx, interpolate_type, fixed_image_size=-1, random_cursor=True,
929
+ photo_prob=1.0,
930
+ init_cursor_num=1):
931
+ if self.random_image_size:
932
+ image_size_rand = fixed_image_size
933
+ else:
934
+ image_size_rand = self.image_size_large
935
+
936
+ photo_data_batch, sketch_data_batch = self.select_sketch_and_crop(
937
+ image_size_rand, data_idx=memory_idx, photo_prob=photo_prob,
938
+ interpolate_type=interpolate_type) # sketch_patch: [0.0-stroke, 1.0-BG]
939
+
940
+ photo_data_batch = np.expand_dims(photo_data_batch, axis=0) # (1, image_size, image_size, 3)
941
+ sketch_data_batch = np.expand_dims(sketch_data_batch,
942
+ axis=0) # (1, image_size, image_size), [0.0-strokes, 1.0-BG]
943
+ image_size_rand = sketch_data_batch.shape[1]
944
+
945
+ return photo_data_batch, sketch_data_batch, \
946
+ self.gen_init_cursors(sketch_data_batch, random_cursor, init_cursor_num), image_size_rand
947
+
948
+ def crop_and_augment(self, photo, sketch, shape, crop_size, rotate_angle, stroke_cover=0.01):
949
+ # img: [0-stroke, 255-BG], uint8
950
+
951
+ def angle_convert(angle):
952
+ return angle / 180.0 * math.pi
953
+
954
+ img_h, img_w = shape[0], shape[1]
955
+
956
+ if self.is_train:
957
+ crop_up = random.randint(0, img_h - crop_size)
958
+ crop_left = random.randint(0, img_w - crop_size)
959
+ else:
960
+ crop_up = (img_h - crop_size) // 2
961
+ crop_left = (img_w - crop_size) // 2
962
+
963
+ assert crop_up >= 0
964
+ assert crop_left >= 0
965
+
966
+ crop_box = (crop_left, crop_up, crop_left + crop_size, crop_up + crop_size)
967
+ rst_sketch_image = sketch.crop(crop_box)
968
+ rst_photo_image = photo.crop(crop_box)
969
+
970
+ if random.random() <= self.flip_prob and self.is_train:
971
+ rst_sketch_image = rst_sketch_image.transpose(Image.FLIP_LEFT_RIGHT)
972
+ rst_photo_image = rst_photo_image.transpose(Image.FLIP_LEFT_RIGHT)
973
+
974
+ if rotate_angle != 0 and self.is_train:
975
+ rst_sketch_image = rst_sketch_image.rotate(rotate_angle, resample=Image.BILINEAR)
976
+ rst_photo_image = rst_photo_image.rotate(rotate_angle, resample=Image.BILINEAR)
977
+ rst_sketch_image = np.array(rst_sketch_image, dtype=np.uint8)
978
+ rst_photo_image = np.array(rst_photo_image, dtype=np.uint8)
979
+
980
+ center = rst_photo_image.shape[0] // 2
981
+
982
+ new_dim = float(crop_size) / (
983
+ math.sin(angle_convert(abs(rotate_angle))) + math.cos(angle_convert(abs(rotate_angle))))
984
+ new_dim = int(round(new_dim))
985
+
986
+ start_pos = center - new_dim // 2
987
+ end_pos = start_pos + new_dim
988
+ rst_sketch_image = rst_sketch_image[start_pos:end_pos, start_pos:end_pos, :]
989
+ rst_photo_image = rst_photo_image[start_pos:end_pos, start_pos:end_pos, :]
990
+
991
+ rst_sketch_image = np.array(rst_sketch_image, dtype=np.float32) / 255.0 # [0.0-stroke, 1.0-BG]
992
+ rst_sketch_image = rst_sketch_image[:, :, 0]
993
+ rst_photo_image = np.array(rst_photo_image, dtype=np.float32) / 255.0 # [0.0-stroke, 1.0-BG]
994
+
995
+ percentage = np.mean(1.0 - rst_sketch_image)
996
+ valid = True
997
+ if percentage < stroke_cover:
998
+ valid = False
999
+
1000
+ return rst_photo_image, rst_sketch_image, valid
1001
+
1002
+ def image_interpolation(self, photo, sketch, photo_prob):
1003
+ interp_photo = photo * photo_prob + sketch * (1.0 - photo_prob)
1004
+ interp_photo = np.clip(interp_photo, 0.0, 1.0)
1005
+ return interp_photo
1006
+
1007
+ def select_sketch_and_crop(self, image_size_rand, interpolate_type, rotate_angle=0, photo_prob=1.0,
1008
+ data_idx=-1, trial_times=10):
1009
+ if self.is_train:
1010
+ while True:
1011
+ rand_img_idx = random.randint(0, len(self.sketch_data) - 1)
1012
+ selected_sketch_shape = self.sketch_shape[rand_img_idx]
1013
+ if selected_sketch_shape[0] >= image_size_rand and selected_sketch_shape[1] >= image_size_rand:
1014
+ img_idx = rand_img_idx
1015
+ break
1016
+ else:
1017
+ assert data_idx != -1
1018
+ img_idx = data_idx
1019
+
1020
+ assert img_idx != -1
1021
+ selected_sketch = self.sketch_data[img_idx]
1022
+ selected_photo = self.photo_data[img_idx]
1023
+ selected_shape = self.sketch_shape[img_idx]
1024
+
1025
+ assert interpolate_type in ['prob', 'image']
1026
+
1027
+ if interpolate_type == 'prob' and random.random() >= photo_prob:
1028
+ selected_photo = self.sketch_data[img_idx]
1029
+
1030
+ for trial_i in range(trial_times):
1031
+ cropped_photo, cropped_sketch, valid = \
1032
+ self.crop_and_augment(selected_photo, selected_sketch, selected_shape, image_size_rand, rotate_angle)
1033
+ # cropped_photo, cropped_sketch: [0.0-stroke, 1.0-BG]
1034
+
1035
+ if valid or trial_i == trial_times - 1:
1036
+ if interpolate_type == 'image':
1037
+ cropped_photo = self.image_interpolation(cropped_photo,
1038
+ np.stack([cropped_sketch for _ in range(3)], axis=-1),
1039
+ photo_prob)
1040
+
1041
+ return cropped_photo, cropped_sketch
1042
+
1043
+ def get_batch_multi_res(self, loop_num, interpolate_type, random_cursor=True, init_cursor_num=1, photo_prob=1.0):
1044
+ photo_data_batch = []
1045
+ sketch_data_batch = []
1046
+ init_cursors_batch = []
1047
+ image_size_batch = []
1048
+ batch_size_per_loop = self.batch_size // loop_num
1049
+ for loop_i in range(loop_num):
1050
+ if self.random_image_size:
1051
+ image_size_rand = random.randint(self.image_size_small, self.image_size_large)
1052
+ else:
1053
+ image_size_rand = self.image_size_large
1054
+
1055
+ rotate_angle = 0
1056
+ if random.random() <= self.rotate_prob:
1057
+ rotate_angle = random.randint(-45, 45)
1058
+
1059
+ photo_data_sub_batch = []
1060
+ sketch_data_sub_batch = []
1061
+ for img_i in range(batch_size_per_loop):
1062
+ photo_patch, sketch_patch = \
1063
+ self.select_sketch_and_crop(image_size_rand, rotate_angle=rotate_angle, photo_prob=photo_prob,
1064
+ interpolate_type=interpolate_type) # sketch_patch: [0.0-stroke, 1.0-BG]
1065
+ photo_data_sub_batch.append(photo_patch)
1066
+ sketch_data_sub_batch.append(sketch_patch)
1067
+
1068
+ photo_data_sub_batch = np.stack(photo_data_sub_batch,
1069
+ axis=0) # (N, image_size, image_size, 3), [0.0-strokes, 1.0-BG]
1070
+ sketch_data_sub_batch = np.stack(sketch_data_sub_batch,
1071
+ axis=0) # (N, image_size, image_size), [0.0-strokes, 1.0-BG]
1072
+ init_cursors_sub_batch = self.gen_init_cursors(sketch_data_sub_batch, random_cursor, init_cursor_num)
1073
+
1074
+ photo_data_batch.append(photo_data_sub_batch)
1075
+ sketch_data_batch.append(sketch_data_sub_batch)
1076
+ init_cursors_batch.append(init_cursors_sub_batch)
1077
+
1078
+ image_size_rand = photo_data_sub_batch.shape[1]
1079
+ image_size_batch.append(image_size_rand)
1080
+
1081
+ return photo_data_batch, sketch_data_batch, init_cursors_batch, image_size_batch
1082
+
1083
+ def crop_patch(self, image, center, image_size, crop_size):
1084
+ x0 = center[0] - crop_size // 2
1085
+ x1 = x0 + crop_size
1086
+ y0 = center[1] - crop_size // 2
1087
+ y1 = y0 + crop_size
1088
+ x0 = max(0, min(x0, image_size))
1089
+ y0 = max(0, min(y0, image_size))
1090
+ x1 = max(0, min(x1, image_size))
1091
+ y1 = max(0, min(y1, image_size))
1092
+ patch = image[y0:y1, x0:x1]
1093
+ return patch
1094
+
1095
+ def gen_init_cursor_single(self, sketch_image):
1096
+ # sketch_image: [0.0-stroke, 1.0-BG]
1097
+ image_size = sketch_image.shape[0]
1098
+ if np.sum(1.0 - sketch_image) == 0:
1099
+ center = np.zeros((2), dtype=np.int32)
1100
+ return center
1101
+ else:
1102
+ while True:
1103
+ center = np.random.randint(0, image_size, size=(2)) # (2), in large size
1104
+ patch = 1.0 - self.crop_patch(sketch_image, center, image_size, self.raster_size)
1105
+ if np.sum(patch) != 0:
1106
+ return center.astype(np.float32) / float(image_size) # (2), in size [0.0, 1.0)
1107
+
1108
+ def gen_init_cursors(self, sketch_data, random_pos=True, init_cursor_num=1):
1109
+ init_cursor_batch_list = []
1110
+ for cursor_i in range(init_cursor_num):
1111
+ if random_pos:
1112
+ init_cursor_batch = []
1113
+ for i in range(len(sketch_data)):
1114
+ sketch_image = sketch_data[i].copy().astype(np.float32) # [0.0-stroke, 1.0-BG]
1115
+ center = self.gen_init_cursor_single(sketch_image)
1116
+ init_cursor_batch.append(center)
1117
+
1118
+ init_cursor_batch = np.stack(init_cursor_batch, axis=0) # (N, 2)
1119
+ else:
1120
+ raise Exception('Not finished')
1121
+ init_cursor_batch_list.append(init_cursor_batch)
1122
+
1123
+ if init_cursor_num == 1:
1124
+ init_cursor_batch = init_cursor_batch_list[0]
1125
+ init_cursor_batch = np.expand_dims(init_cursor_batch, axis=1).astype(np.float32) # (N, 1, 2)
1126
+ else:
1127
+ init_cursor_batch = np.stack(init_cursor_batch_list, axis=1) # (N, init_cursor_num, 2)
1128
+ init_cursor_batch = np.expand_dims(init_cursor_batch, axis=2).astype(
1129
+ np.float32) # (N, init_cursor_num, 1, 2)
1130
+
1131
+ return init_cursor_batch
1132
+
1133
+
1134
+ def load_dataset_normal_images(dataset_base_dir, model_params):
1135
+ train_photo_data = []
1136
+ train_sketch_data = []
1137
+ train_data_shape = []
1138
+ val_photo_data = []
1139
+ val_sketch_data = []
1140
+ val_data_shape = []
1141
+
1142
+ if model_params.data_set == 'faces':
1143
+ random_training_image_size = False
1144
+ flip_prob = -0.1
1145
+ rotate_prob = -0.1
1146
+
1147
+ splits = ['train', 'val']
1148
+
1149
+ database = os.path.join(dataset_base_dir, 'CelebAMask-faces')
1150
+ photo_base = os.path.join(database, 'CelebA-HQ-img256')
1151
+ edge_base = os.path.join(database, 'CelebAMask-HQ-edge256')
1152
+
1153
+ train_split_txt_save_path = os.path.join(database, 'train.txt')
1154
+ val_split_txt_save_path = os.path.join(database, 'val.txt')
1155
+ celeba_train_txt = np.loadtxt(train_split_txt_save_path, dtype=str)
1156
+ celeba_val_txt = np.loadtxt(val_split_txt_save_path, dtype=str)
1157
+ splits_indices_map = {'train': celeba_train_txt, 'val': celeba_val_txt}
1158
+
1159
+ for split in splits:
1160
+ split_indices = splits_indices_map[split]
1161
+
1162
+ for i in range(len(split_indices)):
1163
+ file_idx = split_indices[i]
1164
+ img_file_path = os.path.join(photo_base, str(file_idx) + '.jpg')
1165
+ edge_img_path = os.path.join(edge_base, str(file_idx) + '.png')
1166
+
1167
+ img_data = Image.open(img_file_path).convert('RGB')
1168
+ edge_data = Image.open(edge_img_path).convert('RGB')
1169
+
1170
+ if split == 'train':
1171
+ train_photo_data.append(img_data)
1172
+ train_sketch_data.append(edge_data)
1173
+ train_data_shape.append((img_data.height, img_data.width))
1174
+ else: # split == 'val'
1175
+ val_photo_data.append(img_data)
1176
+ val_sketch_data.append(edge_data)
1177
+ val_data_shape.append((img_data.height, img_data.width))
1178
+
1179
+ assert len(train_sketch_data) == len(train_data_shape) == len(train_photo_data)
1180
+ assert len(val_sketch_data) == len(val_data_shape) == len(val_photo_data)
1181
+ else:
1182
+ raise Exception('Unknown data type:', model_params.data_set)
1183
+
1184
+ print('Loaded {}/{} from {}'.format(len(train_sketch_data), len(val_sketch_data), model_params.data_set))
1185
+ print('model_params.max_seq_len %i.' % model_params.max_seq_len)
1186
+
1187
+ eval_sample_model_params = copy_hparams(model_params)
1188
+ eval_sample_model_params.use_input_dropout = 0
1189
+ eval_sample_model_params.use_recurrent_dropout = 0
1190
+ eval_sample_model_params.use_output_dropout = 0
1191
+ eval_sample_model_params.batch_size = 1 # only sample one at a time
1192
+ eval_sample_model_params.model_mode = 'eval_sample'
1193
+
1194
+ train_set = GeneralDataLoaderNormalImageLinear(train_photo_data, train_sketch_data, train_data_shape,
1195
+ model_params.batch_size, model_params.raster_size,
1196
+ image_size_small=model_params.image_size_small,
1197
+ image_size_large=model_params.image_size_large,
1198
+ random_image_size=random_training_image_size,
1199
+ flip_prob=flip_prob, rotate_prob=rotate_prob,
1200
+ is_train=True)
1201
+ val_set = GeneralDataLoaderNormalImageLinear(val_photo_data, val_sketch_data, val_data_shape,
1202
+ eval_sample_model_params.batch_size,
1203
+ eval_sample_model_params.raster_size,
1204
+ image_size_small=eval_sample_model_params.image_size_small,
1205
+ image_size_large=eval_sample_model_params.image_size_large,
1206
+ random_image_size=random_training_image_size,
1207
+ flip_prob=flip_prob, rotate_prob=rotate_prob,
1208
+ is_train=False)
1209
+
1210
+ result = [
1211
+ train_set, val_set, model_params, eval_sample_model_params
1212
+ ]
1213
+ return result
1214
+
1215
+
1216
+ def load_dataset_training(dataset_base_dir, model_params):
1217
+ if model_params.data_set == 'clean_line_drawings':
1218
+ return load_dataset_multi_object(dataset_base_dir, model_params)
1219
+ elif model_params.data_set == 'rough_sketches':
1220
+ return load_dataset_multi_object_rough(dataset_base_dir, model_params)
1221
+ elif model_params.data_set == 'faces':
1222
+ return load_dataset_normal_images(dataset_base_dir, model_params)
1223
+ else:
1224
+ raise Exception('Unknown data_set', model_params.data_set)
docs/assets/bootstrap.min.css ADDED
The diff for this file is too large to render. See raw diff
 
docs/assets/font.css ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Homepage Font */
2
+
3
+ /* latin-ext */
4
+ @font-face {
5
+ font-family: 'Lato';
6
+ font-style: normal;
7
+ font-weight: 400;
8
+ src: local('Lato Regular'), local('Lato-Regular'), url(https://fonts.gstatic.com/s/lato/v16/S6uyw4BMUTPHjxAwXjeu.woff2) format('woff2');
9
+ unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
10
+ }
11
+
12
+ /* latin */
13
+ @font-face {
14
+ font-family: 'Lato';
15
+ font-style: normal;
16
+ font-weight: 400;
17
+ src: local('Lato Regular'), local('Lato-Regular'), url(https://fonts.gstatic.com/s/lato/v16/S6uyw4BMUTPHjx4wXg.woff2) format('woff2');
18
+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
19
+ }
20
+
21
+ /* latin-ext */
22
+ @font-face {
23
+ font-family: 'Lato';
24
+ font-style: normal;
25
+ font-weight: 700;
26
+ src: local('Lato Bold'), local('Lato-Bold'), url(https://fonts.gstatic.com/s/lato/v16/S6u9w4BMUTPHh6UVSwaPGR_p.woff2) format('woff2');
27
+ unicode-range: U+0100-024F, U+0259, U+1E00-1EFF, U+2020, U+20A0-20AB, U+20AD-20CF, U+2113, U+2C60-2C7F, U+A720-A7FF;
28
+ }
29
+
30
+ /* latin */
31
+ @font-face {
32
+ font-family: 'Lato';
33
+ font-style: normal;
34
+ font-weight: 700;
35
+ src: local('Lato Bold'), local('Lato-Bold'), url(https://fonts.gstatic.com/s/lato/v16/S6u9w4BMUTPHh6UVSwiPGQ.woff2) format('woff2');
36
+ unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
37
+ }
docs/assets/style.css ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Body */
2
+ body {
3
+ background: #e3e5e8;
4
+ color: #ffffff;
5
+ font-family: 'Lato', Verdana, Helvetica, sans-serif;
6
+ font-weight: 300;
7
+ font-size: 14pt;
8
+ }
9
+
10
+ /* Hyperlinks */
11
+ a {text-decoration: none;}
12
+ a:link {color: #1772d0;}
13
+ a:visited {color: #1772d0;}
14
+ a:active {color: red;}
15
+ a:hover {color: #f09228;}
16
+
17
+ /* Pre-formatted Text */
18
+ pre {
19
+ margin: 5pt 0;
20
+ border: 0;
21
+ font-size: 12pt;
22
+ background: #fcfcfc;
23
+ }
24
+
25
+ /* Project Page Style */
26
+ /* Section */
27
+ .section {
28
+ width: 768pt;
29
+ min-height: 100pt;
30
+ margin: 15pt auto;
31
+ padding: 20pt 30pt;
32
+ border: 1pt hidden #000;
33
+ text-align: justify;
34
+ color: #000000;
35
+ background: #ffffff;
36
+ }
37
+
38
+ /* Header (Title and Logo) */
39
+ .section .header {
40
+ min-height: 80pt;
41
+ margin-top: 30pt;
42
+ }
43
+ .section .header .logo {
44
+ width: 80pt;
45
+ margin-left: 10pt;
46
+ float: left;
47
+ }
48
+ .section .header .logo img {
49
+ width: 80pt;
50
+ object-fit: cover;
51
+ }
52
+ .section .header .title {
53
+ margin: 0 120pt;
54
+ text-align: center;
55
+ font-size: 22pt;
56
+ }
57
+
58
+ /* Author */
59
+ .section .author {
60
+ margin: 5pt 0;
61
+ text-align: center;
62
+ font-size: 16pt;
63
+ }
64
+
65
+ /* Institution */
66
+ .section .institution {
67
+ margin: 5pt 0;
68
+ text-align: center;
69
+ font-size: 16pt;
70
+ }
71
+
72
+ /* Hyperlink (such as Paper and Code) */
73
+ .section .link {
74
+ margin: 5pt 0;
75
+ text-align: center;
76
+ font-size: 16pt;
77
+ }
78
+
79
+ /* Teaser */
80
+ .section .teaser {
81
+ margin: 20pt 0;
82
+ text-align: left;
83
+ }
84
+ .section .teaser img {
85
+ width: 95%;
86
+ }
87
+
88
+ /* Section Title */
89
+ .section .title {
90
+ text-align: center;
91
+ font-size: 22pt;
92
+ margin: 5pt 0 15pt 0; /* top right bottom left */
93
+ }
94
+
95
+ /* Section Body */
96
+ .section .body {
97
+ margin-bottom: 15pt;
98
+ text-align: justify;
99
+ font-size: 14pt;
100
+ }
101
+
102
+ /* BibTeX */
103
+ .section .bibtex {
104
+ margin: 5pt 0;
105
+ text-align: left;
106
+ font-size: 22pt;
107
+ }
108
+
109
+ /* Related Work */
110
+ .section .ref {
111
+ margin: 20pt 0 10pt 0; /* top right bottom left */
112
+ text-align: left;
113
+ font-size: 18pt;
114
+ font-weight: bold;
115
+ }
116
+
117
+ /* Citation */
118
+ .section .citation {
119
+ min-height: 60pt;
120
+ margin: 10pt 0;
121
+ }
122
+ .section .citation .image {
123
+ width: 120pt;
124
+ float: left;
125
+ }
126
+ .section .citation .image img {
127
+ max-height: 60pt;
128
+ width: 120pt;
129
+ object-fit: cover;
130
+ }
131
+ .section .citation .comment{
132
+ margin-left: 0pt;
133
+ text-align: left;
134
+ font-size: 14pt;
135
+ }
docs/figures/1390.png ADDED

Git LFS Details

  • SHA256: 3a0495693e1dfa07bcdfbeb5e8d45a2c7797758f39ddeebc7797b3e233605e1b
  • Pointer size: 130 Bytes
  • Size of remote file: 97.8 kB
docs/figures/applications/Geometrized-Cartoon-Line-Inbetweening.png ADDED

Git LFS Details

  • SHA256: 59c2c5ce1ce6c61636cbd7681cba51700a5e9e5c74e42da9fdd75cd5ed7c5ddd
  • Pointer size: 131 Bytes
  • Size of remote file: 343 kB
docs/figures/applications/Painterly-Style-Transfer.png ADDED

Git LFS Details

  • SHA256: a693d3d84eeb1f57e31a806525e152874e27ef1d550b9e2c682453bc5b7c1829
  • Pointer size: 131 Bytes
  • Size of remote file: 627 kB
docs/figures/applications/Vector-Line-Inbetweening-dynamic1.gif ADDED

Git LFS Details

  • SHA256: 5c8c30a749252608854164e0c261dbcd3ca98efac8ee949dad5744037b8b64d4
  • Pointer size: 131 Bytes
  • Size of remote file: 464 kB
docs/figures/applications/Vector-Line-Inbetweening.png ADDED

Git LFS Details

  • SHA256: 3c4856a59b7d1441399e1fd816f129b0bd9a52eaee6418aea08066486a4501ea
  • Pointer size: 131 Bytes
  • Size of remote file: 262 kB
docs/figures/applications/Vector-Line-Inbetweening2.png ADDED

Git LFS Details

  • SHA256: be65632d092ccbc8b6dff3dd6554e9339822eafccb186f2cf983941a2e4bfb77
  • Pointer size: 131 Bytes
  • Size of remote file: 157 kB
docs/figures/applications/complex-vector-drawings.png ADDED

Git LFS Details

  • SHA256: 69300ee1b1d669943d151bc5bb0c28f902c96f49b5e914950788ef5b8046954c
  • Pointer size: 131 Bytes
  • Size of remote file: 169 kB
docs/figures/applications/robot-calligraphy.png ADDED

Git LFS Details

  • SHA256: f2a7922857600fed368cef096d2d14e15d969901b56e0390ae34a115a02b8c22
  • Pointer size: 131 Bytes
  • Size of remote file: 226 kB
docs/figures/applications/sketch-to-image.png ADDED

Git LFS Details

  • SHA256: d8b8e6144dde52500cfc9925b1b8f5f4f778e1dd61a6b37cdb6bf460e441df90
  • Pointer size: 131 Bytes
  • Size of remote file: 405 kB
docs/figures/face-blue-1390-simplest.gif ADDED

Git LFS Details

  • SHA256: 4df0d55256430f578ea991b926d8d543ca14e8295e34a4dcd106167db8d15a59
  • Pointer size: 132 Bytes
  • Size of remote file: 1.79 MB
docs/figures/muten-black-full-simplest.gif ADDED

Git LFS Details

  • SHA256: 3c5bdc2c18c64265f85e2e0a0e702e3cef23f4d28bbbf8ccd45857d9a743ed0a
  • Pointer size: 132 Bytes
  • Size of remote file: 1.89 MB
docs/figures/muten.png ADDED

Git LFS Details

  • SHA256: 4055a1f48408c0fbdca12aabc24a68629cfc015615f3b1336338b9f512a12c38
  • Pointer size: 130 Bytes
  • Size of remote file: 18.7 kB
docs/figures/rocket-blue-simplest.gif ADDED

Git LFS Details

  • SHA256: d04bbdbbd5c962f74cd7d38ef36d080267e24c2d68ffb9a3d831658ffff3ac6e
  • Pointer size: 132 Bytes
  • Size of remote file: 3.01 MB
docs/figures/rocket.png ADDED

Git LFS Details

  • SHA256: 946d0655162a1dd008aea2f43bf25c04e49dfeaa04ba3e253d71a26969a7eafe
  • Pointer size: 131 Bytes
  • Size of remote file: 101 kB
docs/index.html ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html>
2
+ <html lang="en">
3
+
4
+
5
+ <!-- === Header Starts === -->
6
+ <head>
7
+ <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
8
+
9
+ <title>General Virtual Sketching Framework for Vector Line Art</title>
10
+
11
+ <link href="./assets/bootstrap.min.css" rel="stylesheet">
12
+ <link href="./assets/font.css" rel="stylesheet" type="text/css">
13
+ <link href="./assets/style.css" rel="stylesheet" type="text/css">
14
+ </head>
15
+ <!-- === Header Ends === -->
16
+
17
+
18
+ <body>
19
+
20
+
21
+ <!-- === Home Section Starts === -->
22
+ <div class="section">
23
+ <!-- === Title Starts === -->
24
+ <div class="title">
25
+ <b>General Virtual Sketching Framework for Vector Line Art</b>
26
+ </div>
27
+ <!-- === Title Ends === -->
28
+ <div class="author">
29
+ <a href="http://mo-haoran.com/" target="_blank">Haoran Mo</a><sup>1</sup>,&nbsp;
30
+ <a href="https://esslab.jp/~ess/en/" target="_blank">Edgar Simo-Serra</a><sup>2</sup>,&nbsp;
31
+ <a href="http://cse.sysu.edu.cn/content/2537" target="_blank">Chengying Gao</a><sup>*1</sup>,&nbsp;
32
+ <a href="https://changqingzou.weebly.com/" target="_blank">Changqing Zou</a><sup>3</sup>,&nbsp;
33
+ <a href="http://cse.sysu.edu.cn/content/2523" target="_blank">Ruomei Wang</a><sup>1</sup>
34
+ </div>
35
+ <div class="institution">
36
+ <sup>1</sup>Sun Yat-sen University,&nbsp;
37
+ <sup>2</sup>Waseda University,&nbsp;
38
+ <br>
39
+ <sup>3</sup>Huawei Technologies Canada
40
+ </div>
41
+ <br>
42
+ <div class="institution">
43
+ Accepted by <a href="https://s2021.siggraph.org/" target="_blank">ACM SIGGRAPH 2021</a>
44
+ </div>
45
+ <div class="link">
46
+ <a href="https://esslab.jp/publications/HaoranSIGRAPH2021.pdf" target="_blank">[Paper]</a>&nbsp;
47
+ <a href="https://github.com/MarkMoHR/virtual_sketching" target="_blank">[Code]</a>
48
+ </div>
49
+ <div class="teaser">
50
+ <img src="https://cdn.jsdelivr.net/gh/mark-cdn/CDN-for-works@1.4/files/SIG21/teaser6.png" style="width: 100%;">
51
+ <br>
52
+ <br>
53
+ <font size="3">
54
+ Given clean line drawings, rough sketches or photographs of arbitrary resolution as input, our framework generates the corresponding vector line drawings directly. As shown in (b), the framework models a virtual pen surrounded by a dynamic window (red boxes), which moves while drawing the strokes. It learns to move around by scaling the window and sliding to an undrawn area for restarting the drawing (bottom example; sliding trajectory in blue arrow). With our proposed stroke regularization mechanism, the framework is able to enlarge the window and draw long strokes for simplicity (top example).
55
+ </font>
56
+ </div>
57
+ </div>
58
+ <!-- === Home Section Ends === -->
59
+
60
+
61
+ <!-- === Overview Section Starts === -->
62
+ <div class="section">
63
+ <div class="title">Abstract</div>
64
+ <div class="body">
65
+ Vector line art plays an important role in graphic design, however, it is tedious to manually create.
66
+ We introduce a general framework to produce line drawings from a wide variety of images,
67
+ by learning a mapping from raster image space to vector image space.
68
+ Our approach is based on a recurrent neural network that draws the lines one by one.
69
+ A differentiable rasterization module allows for training with only supervised raster data.
70
+ We use a dynamic window around a virtual pen while drawing lines,
71
+ implemented with a proposed aligned cropping and differentiable pasting modules.
72
+ Furthermore, we develop a stroke regularization loss
73
+ that encourages the model to use fewer and longer strokes to simplify the resulting vector image.
74
+ Ablation studies and comparisons with existing methods corroborate the efficiency of our approach
75
+ which is able to generate visually better results in less computation time,
76
+ while generalizing better to a diversity of images and applications.
77
+ </div>
78
+ <div class="link">
79
+ <a href="https://esslab.jp/publications/HaoranSIGRAPH2021.pdf" target="_blank">[Paper]</a>&nbsp; &nbsp;
80
+ <a href="https://dl.acm.org/doi/abs/10.1145/3450626.3459833" target="_blank">[Paper (ACM)]</a>&nbsp; &nbsp;
81
+ <a href="https://markmohr.github.io/files/SIG2021/SketchVectorization_SIG2021_supplemental.pdf" target="_blank">[Supplementary]</a>&nbsp; &nbsp;
82
+ <a href="https://github.com/MarkMoHR/virtual_sketching" target="_blank">[Code]</a>&nbsp; &nbsp;
83
+ <a href="https://drive.google.com/drive/folders/1-hi2cl8joZ6oMOp4yvk_hObJGAK6ELHB?usp=sharing" target="_blank">[All Precomputed Results]</a>
84
+ <!-- <a href="" target="_blank">[Presentation (TBD)]</a>&nbsp; &nbsp; -->
85
+ </div>
86
+ </div>
87
+ <!-- === Overview Section Ends === -->
88
+
89
+
90
+ <!-- === Result Section Starts === -->
91
+ <div class="section">
92
+ <div class="title">Method</div>
93
+ <br>
94
+ <div class="body">
95
+ <p style="text-align:center; font-size:23px; font-weight:bold">Framework Overview<p>
96
+ <img src="https://cdn.jsdelivr.net/gh/mark-cdn/CDN-for-works@1.4/files/SIG21/framework6.png" width="100%">
97
+ <br>
98
+ <br>
99
+ <font size="4">
100
+ Our framework generates the parametrized strokes step by step in a recurrent manner.
101
+ It uses a dynamic window (dashed red boxes) around a virtual pen to draw the strokes,
102
+ and can both move and change the size of the window.
103
+ (a) Four main modules at each time step: aligned cropping, stroke generation, differentiable rendering and differentiable pasting.
104
+ (b) Architecture of the stroke generation module.
105
+ (c) Structural strokes predicted at each step;
106
+ movement only is illustrated by blue arrows during which no stroke is drawn on the canvas.
107
+ </font>
108
+ <br>
109
+ <br>
110
+
111
+ <p style="text-align:center; font-size:23px; font-weight:bold">
112
+ Overall Introduction
113
+ <p>
114
+ <p style="text-align:center; font-size:20px">
115
+ (Or watch on <a href="https://www.bilibili.com/video/BV1gM4y1V7i7/" target="_blank">Bilibili</a>)
116
+ <br>
117
+ 👇
118
+ <p>
119
+ <!-- Adjust the frame size based on the demo (EVERY project differs). -->
120
+ <div style="position: relative; padding-top: 50%; text-align: center;">
121
+ <iframe src="https://www.youtube.com/embed/gXk3TMceByY" frameborder=0
122
+ style="position: absolute; top: 1%; left: 5%; width: 90%; height: 100%;"
123
+ allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
124
+ allowfullscreen></iframe>
125
+ </div>
126
+
127
+ </div>
128
+ </div>
129
+ <!-- === Result Section Ends === -->
130
+
131
+ <!-- === Result Section Starts === -->
132
+ <div class="section">
133
+ <div class="title">Results</div>
134
+ <div class="body">
135
+ Our framework is applicable to a diversity of image types, such as clean line drawing images, rough sketches and photographs.
136
+
137
+ <p style="margin-top: 10pt; text-align:center; font-size:23px; font-weight:bold">Vectorization<p>
138
+ <table width="100%" style="margin: 0pt auto; text-align: center; border-collapse: separate; border-spacing: 5pt;">
139
+ <tr>
140
+ <td width="45%"><img src="https://cdn.jsdelivr.net/gh/mark-cdn/CDN-for-works@1.4/files/SIG21/gifs/clean/muten.png" width="100%"></td>
141
+ <td width="10%"></td>
142
+ <td width="45%"><img src="https://cdn.jsdelivr.net/gh/mark-cdn/CDN-for-works@1.4/files/SIG21/gifs/clean/muten-black-full-simplest.gif" width="100%"></td>
143
+ </tr>
144
+ </table>
145
+ <br>
146
+
147
+ <p style="margin-top: 10pt; text-align:center; font-size:23px; font-weight:bold">Rough sketch simplification<p>
148
+ <table width="100%" style="margin: 0pt auto; text-align: center; border-collapse: separate; border-spacing: 5pt;">
149
+ <tr>
150
+ <td width="26%"><img src="https://cdn.jsdelivr.net/gh/mark-cdn/CDN-for-works@1.4/files/SIG21/gifs/rough/rocket.png" width="100%"></td>
151
+ <td width="26%"><img src="https://cdn.jsdelivr.net/gh/mark-cdn/CDN-for-works@1.4/files/SIG21/gifs/rough/rocket-blue-simplest.gif" width="100%"></td>
152
+ <td width="4%"></td>
153
+ <td width="14%"><img src="https://cdn.jsdelivr.net/gh/mark-cdn/CDN-for-works@1.4/files/SIG21/gifs/rough/penguin.png" width="100%"></td>
154
+ <td width="14%"><img src="https://cdn.jsdelivr.net/gh/mark-cdn/CDN-for-works@1.4/files/SIG21/gifs/rough/penguin-blue-simplest.gif" width="100%"></td>
155
+ </tr>
156
+ </table>
157
+ <br>
158
+
159
+ <p style="margin-top: 10pt; text-align:center; font-size:23px; font-weight:bold">Photograph to line drawing<p>
160
+ <table width="100%" style="margin: 0pt auto; text-align: center; border-collapse: separate; border-spacing: 5pt;">
161
+ <tr>
162
+ <td width="23%"><img src="https://cdn.jsdelivr.net/gh/mark-cdn/CDN-for-works@1.4/files/SIG21/gifs/face/1390_input.png" width="100%"></td>
163
+ <td width="23%"><img src="https://cdn.jsdelivr.net/gh/mark-cdn/CDN-for-works@1.4/files/SIG21/gifs/face/face-blue-1390-simplest.gif" width="100%"></td>
164
+ <td width="8%"></td>
165
+ <td width="23%"><img src="https://cdn.jsdelivr.net/gh/mark-cdn/CDN-for-works@1.4/files/SIG21/gifs/face/1190_input.png" width="100%"></td>
166
+ <td width="23%"><img src="https://cdn.jsdelivr.net/gh/mark-cdn/CDN-for-works@1.4/files/SIG21/gifs/face/face-blue-1190-simplest.gif" width="100%"></td>
167
+ </tr>
168
+ </table>
169
+ <br>
170
+
171
+ <p style="margin-top: 10pt; text-align:center; font-size:23px; font-weight:bold">
172
+ More Results
173
+ <p>
174
+ <p style="text-align:center; font-size:20px">
175
+ (Or watch on <a href="https://www.bilibili.com/video/BV1pv411N7Yx/" target="_blank">Bilibili</a>)
176
+ <br>
177
+ 👇
178
+ <p>
179
+ <!-- Adjust the frame size based on the demo (EVERY project differs). -->
180
+ <div style="position: relative; padding-top: 50%; text-align: center;">
181
+ <iframe src="https://www.youtube.com/embed/Pr6mK9ddXkQ" frameborder=0
182
+ style="position: absolute; top: 1%; left: 5%; width: 90%; height: 100%;"
183
+ allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
184
+ allowfullscreen></iframe>
185
+ </div>
186
+ <br>
187
+
188
+ <div class="link">
189
+ <a href="https://drive.google.com/drive/folders/1-hi2cl8joZ6oMOp4yvk_hObJGAK6ELHB?usp=sharing" target="_blank">
190
+ [Download Our Precomputed Output Results (7MB)]</a>
191
+ </div>
192
+
193
+ </div>
194
+ </div>
195
+ <!-- === Result Section Ends === -->
196
+
197
+
198
+ <!-- === Result Section Starts === -->
199
+ <div class="section">
200
+ <div class="title">Presentations</div>
201
+ <div class="body">
202
+
203
+ <p style="margin-top: 10pt; text-align:center; font-size:23px; font-weight:bold">
204
+ 3-5 minute presentation
205
+ <p>
206
+ <p style="text-align:center; font-size:20px">
207
+ (Or watch on <a href="https://www.bilibili.com/video/BV1S3411q7VX/" target="_blank">Bilibili</a>)
208
+ <br>
209
+ 👇
210
+ <p>
211
+ <!-- Adjust the frame size based on the demo (EVERY project differs). -->
212
+ <div style="position: relative; padding-top: 50%; text-align: center;">
213
+ <iframe src="https://www.youtube.com/embed/BSJN1ixacts" frameborder=0
214
+ style="position: absolute; top: 1%; left: 5%; width: 90%; height: 100%;"
215
+ allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
216
+ allowfullscreen></iframe>
217
+ </div>
218
+ <br>
219
+
220
+ <div class="link">
221
+ 👉 15-20 minute presentation:
222
+ <a href="https://youtu.be/D_U4e1qh5qc" target="_blank">[YouTube]</a>
223
+ <a href="https://www.bilibili.com/video/BV1uU4y1E7Wg/" target="_blank">[Bilibili]</a>
224
+ </div>
225
+
226
+ <div class="link">
227
+ 👉 30-second fast forward:
228
+ <a href="https://youtu.be/d0EbSU_EeFg" target="_blank">[YouTube]</a>
229
+ <a href="https://www.bilibili.com/video/BV1vq4y1M7j1/" target="_blank">[Bilibili]</a>
230
+ </div>
231
+
232
+ </div>
233
+ </div>
234
+ <!-- === Result Section Ends === -->
235
+
236
+
237
+ <!-- === Reference Section Starts === -->
238
+ <div class="section">
239
+ <div class="bibtex">BibTeX</div>
240
+ <pre>
241
+ @article{mo2021virtualsketching,
242
+ title = {General Virtual Sketching Framework for Vector Line Art},
243
+ author = {Mo, Haoran and Simo-Serra, Edgar and Gao, Chengying and Zou, Changqing and Wang, Ruomei},
244
+ journal = {ACM Transactions on Graphics (Proceedings of ACM SIGGRAPH 2021)},
245
+ year = {2021},
246
+ volume = {40},
247
+ number = {4},
248
+ pages = {51:1--51:14}
249
+ }
250
+ </pre>
251
+
252
+ <br>
253
+ <div class="bibtex">Related Work</div>
254
+ <div class="citation">
255
+ <div class="comment">
256
+ Jean-Dominique Favreau, Florent Lafarge and Adrien Bousseau.
257
+ <strong>Fidelity vs. Simplicity: a Global Approach to Line Drawing Vectorization</strong>. SIGGRAPH 2016.
258
+ [<a href="https://www-sop.inria.fr/reves/Basilic/2016/FLB16/fidelity_simplicity.pdf">Paper</a>]
259
+ [<a href="https://www-sop.inria.fr/reves/Basilic/2016/FLB16/">Webpage</a>]
260
+ <br><br>
261
+ </div>
262
+
263
+ <div class="comment">
264
+ Mikhail Bessmeltsev and Justin Solomon.
265
+ <strong>Vectorization of Line Drawings via PolyVector Fields</strong>. SIGGRAPH 2019.
266
+ [<a href="https://arxiv.org/abs/1801.01922">Paper</a>]
267
+ [<a href="https://github.com/bmpix/PolyVectorization">Code</a>]
268
+ <br><br>
269
+ </div>
270
+
271
+ <div class="comment">
272
+ Edgar Simo-Serra, Satoshi Iizuka and Hiroshi Ishikawa.
273
+ <strong>Mastering Sketching: Adversarial Augmentation for Structured Prediction</strong>. SIGGRAPH 2018.
274
+ [<a href="https://esslab.jp/~ess/publications/SimoSerraTOG2018.pdf">Paper</a>]
275
+ [<a href="https://esslab.jp/~ess/en/research/sketch_master/">Webpage</a>]
276
+ [<a href="https://github.com/bobbens/sketch_simplification">Code</a>]
277
+ <br><br>
278
+ </div>
279
+
280
+ <div class="comment">
281
+ Zhewei Huang, Wen Heng and Shuchang Zhou.
282
+ <strong>Learning to Paint With Model-based Deep Reinforcement Learning</strong>. ICCV 2019.
283
+ [<a href="https://openaccess.thecvf.com/content_ICCV_2019/papers/Huang_Learning_to_Paint_With_Model-Based_Deep_Reinforcement_Learning_ICCV_2019_paper.pdf">Paper</a>]
284
+ [<a href="https://github.com/megvii-research/ICCV2019-LearningToPaint">Code</a>]
285
+ <br><br>
286
+ </div>
287
+ </div>
288
+ </div>
289
+ <!-- === Reference Section Ends === -->
290
+
291
+
292
+ </body>
293
+ </html>
hyper_parameters.py ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import tensorflow as tf
2
+
3
+
4
+ #############################################
5
+ # Common parameters
6
+ #############################################
7
+
8
+ FLAGS = tf.app.flags.FLAGS
9
+
10
+ tf.app.flags.DEFINE_string(
11
+ 'dataset_dir',
12
+ 'datasets',
13
+ 'The directory of sketch data of the dataset.')
14
+ tf.app.flags.DEFINE_string(
15
+ 'log_root',
16
+ 'outputs/log',
17
+ 'Directory to store tensorboard.')
18
+ tf.app.flags.DEFINE_string(
19
+ 'log_img_root',
20
+ 'outputs/log_img',
21
+ 'Directory to store intermediate output images.')
22
+ tf.app.flags.DEFINE_string(
23
+ 'snapshot_root',
24
+ 'outputs/snapshot',
25
+ 'Directory to store model checkpoints.')
26
+ tf.app.flags.DEFINE_string(
27
+ 'neural_renderer_path',
28
+ 'outputs/snapshot/pretrain_neural_renderer/renderer_300000.tfmodel',
29
+ 'Path to the neural renderer model.')
30
+ tf.app.flags.DEFINE_string(
31
+ 'perceptual_model_root',
32
+ 'outputs/snapshot/pretrain_perceptual_model',
33
+ 'Directory to store perceptual model.')
34
+ tf.app.flags.DEFINE_string(
35
+ 'data',
36
+ '',
37
+ 'The dataset type.')
38
+
39
+
40
+ def get_default_hparams_clean():
41
+ """Return default HParams for sketch-rnn."""
42
+ hparams = tf.contrib.training.HParams(
43
+ program_name='new_train_clean_line_drawings',
44
+ data_set='clean_line_drawings', # Our dataset.
45
+
46
+ input_channel=1,
47
+
48
+ num_steps=75040, # Total number of steps of training.
49
+ save_every=75000,
50
+ eval_every=5000,
51
+
52
+ max_seq_len=48,
53
+ batch_size=20,
54
+ gpus=[0, 1],
55
+ loop_per_gpu=1,
56
+
57
+ sn_loss_type='increasing', # ['decreasing', 'fixed', 'increasing']
58
+ stroke_num_loss_weight=0.02,
59
+ stroke_num_loss_weight_end=0.0,
60
+ increase_start_steps=25000,
61
+ decrease_stop_steps=40000,
62
+
63
+ perc_loss_layers=['ReLU1_2', 'ReLU2_2', 'ReLU3_3', 'ReLU5_1'],
64
+ perc_loss_fuse_type='add', # ['max', 'add', 'raw_add', 'weighted_sum']
65
+
66
+ init_cursor_on_undrawn_pixel=False,
67
+
68
+ early_pen_loss_type='move', # ['head', 'tail', 'move']
69
+ early_pen_loss_weight=0.1,
70
+ early_pen_length=7,
71
+
72
+ min_width=0.01,
73
+ min_window_size=32,
74
+ max_scaling=2.0,
75
+
76
+ encode_cursor_type='value',
77
+
78
+ image_size_small=128,
79
+ image_size_large=278,
80
+
81
+ cropping_type='v3', # ['v2', 'v3']
82
+ pasting_type='v3', # ['v2', 'v3']
83
+ pasting_diff=True,
84
+
85
+ concat_win_size=True,
86
+
87
+ encoder_type='conv13_c3',
88
+ # ['conv10', 'conv10_deep', 'conv13', 'conv10_c3', 'conv10_deep_c3', 'conv13_c3']
89
+ # ['conv13_c3_attn']
90
+ # ['combine33', 'combine43', 'combine53', 'combineFC']
91
+ vary_thickness=False,
92
+
93
+ outside_loss_weight=10.0,
94
+ win_size_outside_loss_weight=10.0,
95
+
96
+ resize_method='AREA', # ['BILINEAR', 'NEAREST_NEIGHBOR', 'BICUBIC', 'AREA']
97
+
98
+ concat_cursor=True,
99
+
100
+ use_softargmax=True,
101
+ soft_beta=10, # value for the soft argmax
102
+
103
+ raster_loss_weight=1.0,
104
+
105
+ dec_rnn_size=256, # Size of decoder.
106
+ dec_model='hyper', # Decoder: lstm, layer_norm or hyper.
107
+ # z_size=128, # Size of latent vector z. Recommend 32, 64 or 128.
108
+ bin_gt=True,
109
+
110
+ stop_accu_grad=True,
111
+
112
+ random_cursor=True,
113
+ cursor_type='next',
114
+
115
+ raster_size=128,
116
+
117
+ pix_drop_kp=1.0, # Dropout keep rate
118
+ add_coordconv=True,
119
+ position_format='abs',
120
+ raster_loss_base_type='perceptual', # [l1, mse, perceptual]
121
+
122
+ grad_clip=1.0, # Gradient clipping. Recommend leaving at 1.0.
123
+
124
+ learning_rate=0.0001, # Learning rate.
125
+ decay_rate=0.9999, # Learning rate decay per minibatch.
126
+ decay_power=0.9,
127
+ min_learning_rate=0.000001, # Minimum learning rate.
128
+
129
+ use_recurrent_dropout=True, # Dropout with memory loss. Recommended
130
+ recurrent_dropout_prob=0.90, # Probability of recurrent dropout keep.
131
+ use_input_dropout=False, # Input dropout. Recommend leaving False.
132
+ input_dropout_prob=0.90, # Probability of input dropout keep.
133
+ use_output_dropout=False, # Output dropout. Recommend leaving False.
134
+ output_dropout_prob=0.90, # Probability of output dropout keep.
135
+
136
+ model_mode='train' # ['train', 'eval', 'sample']
137
+ )
138
+ return hparams
139
+
140
+
141
+ def get_default_hparams_rough():
142
+ """Return default HParams for sketch-rnn."""
143
+ hparams = tf.contrib.training.HParams(
144
+ program_name='new_train_rough_sketches',
145
+ data_set='rough_sketches', # ['rough_sketches', 'faces']
146
+
147
+ input_channel=3,
148
+
149
+ num_steps=90040, # Total number of steps of training.
150
+ save_every=90000,
151
+ eval_every=5000,
152
+
153
+ max_seq_len=48,
154
+ batch_size=20,
155
+ gpus=[0, 1],
156
+ loop_per_gpu=1,
157
+
158
+ sn_loss_type='increasing', # ['decreasing', 'fixed', 'increasing']
159
+ stroke_num_loss_weight=0.1,
160
+ stroke_num_loss_weight_end=0.0,
161
+ increase_start_steps=25000,
162
+ decrease_stop_steps=40000,
163
+
164
+ photo_prob_type='one', # ['increasing', 'zero', 'one']
165
+ photo_prob_start_step=35000,
166
+
167
+ perc_loss_layers=['ReLU2_2', 'ReLU3_3', 'ReLU5_1'],
168
+ perc_loss_fuse_type='add', # ['max', 'add', 'raw_add', 'weighted_sum']
169
+
170
+ early_pen_loss_type='move', # ['head', 'tail', 'move']
171
+ early_pen_loss_weight=0.2,
172
+ early_pen_length=7,
173
+
174
+ min_width=0.01,
175
+ min_window_size=32,
176
+ max_scaling=2.0,
177
+
178
+ encode_cursor_type='value',
179
+
180
+ image_size_small=128,
181
+ image_size_large=278,
182
+
183
+ cropping_type='v3', # ['v2', 'v3']
184
+ pasting_type='v3', # ['v2', 'v3']
185
+ pasting_diff=True,
186
+
187
+ concat_win_size=True,
188
+
189
+ encoder_type='conv13_c3',
190
+ # ['conv10', 'conv10_deep', 'conv13', 'conv10_c3', 'conv10_deep_c3', 'conv13_c3']
191
+ # ['conv13_c3_attn']
192
+ # ['combine33', 'combine43', 'combine53', 'combineFC']
193
+
194
+ outside_loss_weight=10.0,
195
+ win_size_outside_loss_weight=10.0,
196
+
197
+ resize_method='AREA', # ['BILINEAR', 'NEAREST_NEIGHBOR', 'BICUBIC', 'AREA']
198
+
199
+ concat_cursor=True,
200
+
201
+ use_softargmax=True,
202
+ soft_beta=10, # value for the soft argmax
203
+
204
+ raster_loss_weight=1.0,
205
+
206
+ dec_rnn_size=256, # Size of decoder.
207
+ dec_model='hyper', # Decoder: lstm, layer_norm or hyper.
208
+ # z_size=128, # Size of latent vector z. Recommend 32, 64 or 128.
209
+ bin_gt=True,
210
+
211
+ stop_accu_grad=True,
212
+
213
+ random_cursor=True,
214
+ cursor_type='next',
215
+
216
+ raster_size=128,
217
+
218
+ pix_drop_kp=1.0, # Dropout keep rate
219
+ add_coordconv=True,
220
+ position_format='abs',
221
+ raster_loss_base_type='perceptual', # [l1, mse, perceptual]
222
+
223
+ grad_clip=1.0, # Gradient clipping. Recommend leaving at 1.0.
224
+
225
+ learning_rate=0.0001, # Learning rate.
226
+ decay_rate=0.9999, # Learning rate decay per minibatch.
227
+ decay_power=0.9,
228
+ min_learning_rate=0.000001, # Minimum learning rate.
229
+
230
+ use_recurrent_dropout=True, # Dropout with memory loss. Recommended
231
+ recurrent_dropout_prob=0.90, # Probability of recurrent dropout keep.
232
+ use_input_dropout=False, # Input dropout. Recommend leaving False.
233
+ input_dropout_prob=0.90, # Probability of input dropout keep.
234
+ use_output_dropout=False, # Output dropout. Recommend leaving False.
235
+ output_dropout_prob=0.90, # Probability of output dropout keep.
236
+
237
+ model_mode='train' # ['train', 'eval', 'sample']
238
+ )
239
+ return hparams
240
+
241
+
242
+ def get_default_hparams_normal():
243
+ """Return default HParams for sketch-rnn."""
244
+ hparams = tf.contrib.training.HParams(
245
+ program_name='new_train_faces',
246
+ data_set='faces', # ['rough_sketches', 'faces']
247
+
248
+ input_channel=3,
249
+
250
+ num_steps=90040, # Total number of steps of training.
251
+ save_every=90000,
252
+ eval_every=5000,
253
+
254
+ max_seq_len=48,
255
+ batch_size=20,
256
+ gpus=[0, 1],
257
+ loop_per_gpu=1,
258
+
259
+ sn_loss_type='fixed', # ['decreasing', 'fixed', 'increasing']
260
+ stroke_num_loss_weight=0.0,
261
+ stroke_num_loss_weight_end=0.0,
262
+ increase_start_steps=0,
263
+ decrease_stop_steps=40000,
264
+
265
+ photo_prob_type='interpolate', # ['increasing', 'zero', 'one', 'interpolate']
266
+ photo_prob_start_step=30000,
267
+ photo_prob_end_step=60000,
268
+
269
+ perc_loss_layers=['ReLU2_2', 'ReLU3_3', 'ReLU4_2', 'ReLU5_1'],
270
+ perc_loss_fuse_type='add', # ['max', 'add', 'raw_add', 'weighted_sum']
271
+
272
+ early_pen_loss_type='move', # ['head', 'tail', 'move']
273
+ early_pen_loss_weight=0.2,
274
+ early_pen_length=7,
275
+
276
+ min_width=0.01,
277
+ min_window_size=32,
278
+ max_scaling=2.0,
279
+
280
+ encode_cursor_type='value',
281
+
282
+ image_size_small=128,
283
+ image_size_large=256,
284
+
285
+ cropping_type='v3', # ['v2', 'v3']
286
+ pasting_type='v3', # ['v2', 'v3']
287
+ pasting_diff=True,
288
+
289
+ concat_win_size=True,
290
+
291
+ encoder_type='conv13_c3',
292
+ # ['conv10', 'conv10_deep', 'conv13', 'conv10_c3', 'conv10_deep_c3', 'conv13_c3']
293
+ # ['conv13_c3_attn']
294
+ # ['combine33', 'combine43', 'combine53', 'combineFC']
295
+
296
+ outside_loss_weight=10.0,
297
+ win_size_outside_loss_weight=10.0,
298
+
299
+ resize_method='AREA', # ['BILINEAR', 'NEAREST_NEIGHBOR', 'BICUBIC', 'AREA']
300
+
301
+ concat_cursor=True,
302
+
303
+ use_softargmax=True,
304
+ soft_beta=10, # value for the soft argmax
305
+
306
+ raster_loss_weight=1.0,
307
+
308
+ dec_rnn_size=256, # Size of decoder.
309
+ dec_model='hyper', # Decoder: lstm, layer_norm or hyper.
310
+ # z_size=128, # Size of latent vector z. Recommend 32, 64 or 128.
311
+ bin_gt=True,
312
+
313
+ stop_accu_grad=True,
314
+
315
+ random_cursor=True,
316
+ cursor_type='next',
317
+
318
+ raster_size=128,
319
+
320
+ pix_drop_kp=1.0, # Dropout keep rate
321
+ add_coordconv=True,
322
+ position_format='abs',
323
+ raster_loss_base_type='perceptual', # [l1, mse, perceptual]
324
+
325
+ grad_clip=1.0, # Gradient clipping. Recommend leaving at 1.0.
326
+
327
+ learning_rate=0.0001, # Learning rate.
328
+ decay_rate=0.9999, # Learning rate decay per minibatch.
329
+ decay_power=0.9,
330
+ min_learning_rate=0.000001, # Minimum learning rate.
331
+
332
+ use_recurrent_dropout=True, # Dropout with memory loss. Recommended
333
+ recurrent_dropout_prob=0.90, # Probability of recurrent dropout keep.
334
+ use_input_dropout=False, # Input dropout. Recommend leaving False.
335
+ input_dropout_prob=0.90, # Probability of input dropout keep.
336
+ use_output_dropout=False, # Output dropout. Recommend leaving False.
337
+ output_dropout_prob=0.90, # Probability of output dropout keep.
338
+
339
+ model_mode='train' # ['train', 'eval', 'sample']
340
+ )
341
+ return hparams
launch_gui.bat ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo OFF
2
+
3
+ REM === Cesta k instalaci Anacondy ===
4
+ set "CONDAPATH=C:\ProgramData\anaconda3"
5
+
6
+ REM === Název a cesta k prostředí ===
7
+ set "ENVNAME=virtual_sketching"
8
+ set "ENVPATH=%USERPROFILE%\.conda\envs\%ENVNAME%"
9
+
10
+ REM === Aktivace prostředí ===
11
+ call "%CONDAPATH%\Scripts\activate.bat" "%ENVPATH%"
12
+
13
+ REM === Spuštění GUI ===
14
+ python virtual_sketch_gui.py
15
+
16
+ REM === Pozastavení po ukončení ===
17
+ echo.
18
+ pause
19
+
20
+ REM === Deaktivace prostředí ===
21
+ call conda deactivate
model_common_test.py ADDED
@@ -0,0 +1,604 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import rnn
2
+ import tensorflow as tf
3
+
4
+ from subnet_tf_utils import generative_cnn_encoder, generative_cnn_encoder_deeper, generative_cnn_encoder_deeper13, \
5
+ generative_cnn_c3_encoder, generative_cnn_c3_encoder_deeper, generative_cnn_c3_encoder_deeper13, \
6
+ generative_cnn_c3_encoder_combine33, generative_cnn_c3_encoder_combine43, \
7
+ generative_cnn_c3_encoder_combine53, generative_cnn_c3_encoder_combineFC, \
8
+ generative_cnn_c3_encoder_deeper13_attn
9
+
10
+
11
+ class DiffPastingV3(object):
12
+ def __init__(self, raster_size):
13
+ self.patch_canvas = tf.placeholder(dtype=tf.float32,
14
+ shape=(None, None, 1)) # (raster_size, raster_size, 1), [0.0-BG, 1.0-stroke]
15
+ self.cursor_pos_a = tf.placeholder(dtype=tf.float32, shape=(2)) # (2), float32, in large size
16
+ self.image_size_a = tf.placeholder(dtype=tf.int32, shape=()) # ()
17
+ self.window_size_a = tf.placeholder(dtype=tf.float32, shape=()) # (), float32, with grad
18
+ self.raster_size_a = float(raster_size)
19
+
20
+ self.pasted_image = self.image_pasting_sampling_v3()
21
+ # (image_size, image_size, 1), [0.0-BG, 1.0-stroke]
22
+
23
+ def image_pasting_sampling_v3(self):
24
+ padding_size = tf.cast(tf.ceil(self.window_size_a / 2.0), tf.int32)
25
+
26
+ x1y1_a = self.cursor_pos_a - self.window_size_a / 2.0 # (2), float32
27
+ x2y2_a = self.cursor_pos_a + self.window_size_a / 2.0 # (2), float32
28
+
29
+ x1y1_a_floor = tf.floor(x1y1_a) # (2)
30
+ x2y2_a_ceil = tf.ceil(x2y2_a) # (2)
31
+
32
+ cursor_pos_b_oricoord = (x1y1_a_floor + x2y2_a_ceil) / 2.0 # (2)
33
+ cursor_pos_b = (cursor_pos_b_oricoord - x1y1_a) / self.window_size_a * self.raster_size_a # (2)
34
+ raster_size_b = (x2y2_a_ceil - x1y1_a_floor) # (x, y)
35
+ image_size_b = self.raster_size_a
36
+ window_size_b = self.raster_size_a * (raster_size_b / self.window_size_a) # (x, y)
37
+
38
+ cursor_b_x, cursor_b_y = tf.split(cursor_pos_b, 2, axis=-1) # (1)
39
+
40
+ y1_b = cursor_b_y - (window_size_b[1] - 1.) / 2.
41
+ x1_b = cursor_b_x - (window_size_b[0] - 1.) / 2.
42
+ y2_b = y1_b + (window_size_b[1] - 1.)
43
+ x2_b = x1_b + (window_size_b[0] - 1.)
44
+ boxes_b = tf.concat([y1_b, x1_b, y2_b, x2_b], axis=-1) # (4)
45
+ boxes_b = boxes_b / tf.cast(image_size_b - 1, tf.float32) # with grad to window_size_a
46
+
47
+ box_ind_b = tf.ones((1), dtype=tf.int32) # (1)
48
+ box_ind_b = tf.cumsum(box_ind_b) - 1
49
+
50
+ patch_canvas = tf.expand_dims(self.patch_canvas,
51
+ axis=0) # (1, raster_size, raster_size, 1), [0.0-BG, 1.0-stroke]
52
+ boxes_b = tf.expand_dims(boxes_b, axis=0) # (1, 4)
53
+
54
+ valid_canvas = tf.image.crop_and_resize(patch_canvas, boxes_b, box_ind_b,
55
+ crop_size=[raster_size_b[1], raster_size_b[0]])
56
+ valid_canvas = valid_canvas[0] # (raster_size_b, raster_size_b, 1)
57
+
58
+ pad_up = tf.cast(x1y1_a_floor[1], tf.int32) + padding_size
59
+ pad_down = self.image_size_a + padding_size - tf.cast(x2y2_a_ceil[1], tf.int32)
60
+ pad_left = tf.cast(x1y1_a_floor[0], tf.int32) + padding_size
61
+ pad_right = self.image_size_a + padding_size - tf.cast(x2y2_a_ceil[0], tf.int32)
62
+
63
+ paddings = [[pad_up, pad_down],
64
+ [pad_left, pad_right],
65
+ [0, 0]]
66
+ pad_img = tf.pad(valid_canvas, paddings=paddings, mode='CONSTANT',
67
+ constant_values=0.0) # (H_p, W_p, 1), [0.0-BG, 1.0-stroke]
68
+
69
+ pasted_image = pad_img[padding_size: padding_size + self.image_size_a,
70
+ padding_size: padding_size + self.image_size_a, :]
71
+ # (image_size, image_size, 1), [0.0-BG, 1.0-stroke]
72
+ return pasted_image
73
+
74
+
75
+ class VirtualSketchingModel(object):
76
+ def __init__(self, hps, gpu_mode=True, reuse=False):
77
+ """Initializer for the model.
78
+
79
+ Args:
80
+ hps: a HParams object containing model hyperparameters
81
+ gpu_mode: a boolean that when True, uses GPU mode.
82
+ reuse: a boolean that when true, attemps to reuse variables.
83
+ """
84
+ self.hps = hps
85
+ assert hps.model_mode in ['train', 'eval', 'eval_sample', 'sample']
86
+ # with tf.variable_scope('SCC', reuse=reuse):
87
+ if not gpu_mode:
88
+ with tf.device('/cpu:0'):
89
+ print('Model using cpu.')
90
+ self.build_model()
91
+ else:
92
+ print('-' * 100)
93
+ print('model_mode:', hps.model_mode)
94
+ print('Model using gpu.')
95
+ self.build_model()
96
+
97
+ def build_model(self):
98
+ """Define model architecture."""
99
+ self.config_model()
100
+
101
+ initial_state = self.get_decoder_inputs()
102
+ self.initial_state = initial_state
103
+
104
+ ## use pred as the prev points
105
+ other_params, pen_ras, final_state = self.get_points_and_raster_image(self.image_size)
106
+ # other_params: (N * max_seq_len, 6)
107
+ # pen_ras: (N * max_seq_len, 2), after softmax
108
+
109
+ self.other_params = other_params # (N * max_seq_len, 6)
110
+ self.pen_ras = pen_ras # (N * max_seq_len, 2), after softmax
111
+ self.final_state = final_state
112
+
113
+ if not self.hps.use_softargmax:
114
+ pen_state_soft = pen_ras[:, 1:2] # (N * max_seq_len, 1)
115
+ else:
116
+ pen_state_soft = self.differentiable_argmax(pen_ras, self.hps.soft_beta) # (N * max_seq_len, 1)
117
+
118
+ pred_params = tf.concat([pen_state_soft, other_params], axis=1) # (N * max_seq_len, 7)
119
+ self.pred_params = tf.reshape(pred_params, shape=[-1, self.hps.max_seq_len, 7]) # (N, max_seq_len, 7)
120
+ # pred_params: (N, max_seq_len, 7)
121
+
122
+ def config_model(self):
123
+ if self.hps.model_mode == 'train':
124
+ self.global_step = tf.Variable(0, name='global_step', trainable=False)
125
+
126
+ if self.hps.dec_model == 'lstm':
127
+ dec_cell_fn = rnn.LSTMCell
128
+ elif self.hps.dec_model == 'layer_norm':
129
+ dec_cell_fn = rnn.LayerNormLSTMCell
130
+ elif self.hps.dec_model == 'hyper':
131
+ dec_cell_fn = rnn.HyperLSTMCell
132
+ else:
133
+ assert False, 'please choose a respectable cell'
134
+
135
+ use_recurrent_dropout = self.hps.use_recurrent_dropout
136
+ use_input_dropout = self.hps.use_input_dropout
137
+ use_output_dropout = self.hps.use_output_dropout
138
+
139
+ dec_cell = dec_cell_fn(
140
+ self.hps.dec_rnn_size,
141
+ use_recurrent_dropout=use_recurrent_dropout,
142
+ dropout_keep_prob=self.hps.recurrent_dropout_prob)
143
+
144
+ # dropout:
145
+ # print('Input dropout mode = %s.' % use_input_dropout)
146
+ # print('Output dropout mode = %s.' % use_output_dropout)
147
+ # print('Recurrent dropout mode = %s.' % use_recurrent_dropout)
148
+ if use_input_dropout:
149
+ print('Dropout to input w/ keep_prob = %4.4f.' % self.hps.input_dropout_prob)
150
+ dec_cell = tf.contrib.rnn.DropoutWrapper(
151
+ dec_cell, input_keep_prob=self.hps.input_dropout_prob)
152
+ if use_output_dropout:
153
+ print('Dropout to output w/ keep_prob = %4.4f.' % self.hps.output_dropout_prob)
154
+ dec_cell = tf.contrib.rnn.DropoutWrapper(
155
+ dec_cell, output_keep_prob=self.hps.output_dropout_prob)
156
+ self.dec_cell = dec_cell
157
+
158
+ self.input_photo = tf.placeholder(dtype=tf.float32,
159
+ shape=[self.hps.batch_size, None, None, self.hps.input_channel]) # [0.0-stroke, 1.0-BG]
160
+ self.init_cursor = tf.placeholder(
161
+ dtype=tf.float32,
162
+ shape=[self.hps.batch_size, 1, 2]) # (N, 1, 2), in size [0.0, 1.0)
163
+ self.init_width = tf.placeholder(
164
+ dtype=tf.float32,
165
+ shape=[self.hps.batch_size]) # (1), in [0.0, 1.0]
166
+ self.init_scaling = tf.placeholder(
167
+ dtype=tf.float32,
168
+ shape=[self.hps.batch_size]) # (N), in [0.0, 1.0]
169
+ self.init_window_size = tf.placeholder(
170
+ dtype=tf.float32,
171
+ shape=[self.hps.batch_size]) # (N)
172
+ self.image_size = tf.placeholder(dtype=tf.int32, shape=()) # ()
173
+
174
+ ###########################
175
+
176
+ def normalize_image_m1to1(self, in_img_0to1):
177
+ norm_img_m1to1 = tf.multiply(in_img_0to1, 2.0)
178
+ norm_img_m1to1 = tf.subtract(norm_img_m1to1, 1.0)
179
+ return norm_img_m1to1
180
+
181
+ def add_coords(self, input_tensor):
182
+ batch_size_tensor = tf.shape(input_tensor)[0] # get N size
183
+
184
+ xx_ones = tf.ones([batch_size_tensor, self.hps.raster_size], dtype=tf.int32) # e.g. (N, raster_size)
185
+ xx_ones = tf.expand_dims(xx_ones, -1) # e.g. (N, raster_size, 1)
186
+ xx_range = tf.tile(tf.expand_dims(tf.range(self.hps.raster_size), 0),
187
+ [batch_size_tensor, 1]) # e.g. (N, raster_size)
188
+ xx_range = tf.expand_dims(xx_range, 1) # e.g. (N, 1, raster_size)
189
+
190
+ xx_channel = tf.matmul(xx_ones, xx_range) # e.g. (N, raster_size, raster_size)
191
+ xx_channel = tf.expand_dims(xx_channel, -1) # e.g. (N, raster_size, raster_size, 1)
192
+
193
+ yy_ones = tf.ones([batch_size_tensor, self.hps.raster_size], dtype=tf.int32) # e.g. (N, raster_size)
194
+ yy_ones = tf.expand_dims(yy_ones, 1) # e.g. (N, 1, raster_size)
195
+ yy_range = tf.tile(tf.expand_dims(tf.range(self.hps.raster_size), 0),
196
+ [batch_size_tensor, 1]) # (N, raster_size)
197
+ yy_range = tf.expand_dims(yy_range, -1) # e.g. (N, raster_size, 1)
198
+
199
+ yy_channel = tf.matmul(yy_range, yy_ones) # e.g. (N, raster_size, raster_size)
200
+ yy_channel = tf.expand_dims(yy_channel, -1) # e.g. (N, raster_size, raster_size, 1)
201
+
202
+ xx_channel = tf.cast(xx_channel, 'float32') / (self.hps.raster_size - 1)
203
+ yy_channel = tf.cast(yy_channel, 'float32') / (self.hps.raster_size - 1)
204
+ # xx_channel = xx_channel * 2 - 1 # [-1, 1]
205
+ # yy_channel = yy_channel * 2 - 1
206
+
207
+ ret = tf.concat([
208
+ input_tensor,
209
+ xx_channel,
210
+ yy_channel,
211
+ ], axis=-1) # e.g. (N, raster_size, raster_size, 4)
212
+
213
+ return ret
214
+
215
+ def build_combined_encoder(self, patch_canvas, patch_photo, entire_canvas, entire_photo, cursor_pos,
216
+ image_size, window_size):
217
+ """
218
+ :param patch_canvas: (N, raster_size, raster_size, 1), [-1.0-stroke, 1.0-BG]
219
+ :param patch_photo: (N, raster_size, raster_size, 1/3), [-1.0-stroke, 1.0-BG]
220
+ :param entire_canvas: (N, image_size, image_size, 1), [0.0-stroke, 1.0-BG]
221
+ :param entire_photo: (N, image_size, image_size, 1/3), [0.0-stroke, 1.0-BG]
222
+ :param cursor_pos: (N, 1, 2), in size [0.0, 1.0)
223
+ :param window_size: (N, 1, 1), float, in large size
224
+ :return:
225
+ """
226
+ if self.hps.resize_method == 'BILINEAR':
227
+ resize_method = tf.image.ResizeMethod.BILINEAR
228
+ elif self.hps.resize_method == 'NEAREST_NEIGHBOR':
229
+ resize_method = tf.image.ResizeMethod.NEAREST_NEIGHBOR
230
+ elif self.hps.resize_method == 'BICUBIC':
231
+ resize_method = tf.image.ResizeMethod.BICUBIC
232
+ elif self.hps.resize_method == 'AREA':
233
+ resize_method = tf.image.ResizeMethod.AREA
234
+ else:
235
+ raise Exception('unknown resize_method', self.hps.resize_method)
236
+
237
+ patch_photo = tf.stop_gradient(patch_photo)
238
+ patch_canvas = tf.stop_gradient(patch_canvas)
239
+ cursor_pos = tf.stop_gradient(cursor_pos)
240
+ window_size = tf.stop_gradient(window_size)
241
+
242
+ entire_photo_small = tf.stop_gradient(tf.image.resize_images(entire_photo,
243
+ (self.hps.raster_size, self.hps.raster_size),
244
+ method=resize_method))
245
+ entire_canvas_small = tf.stop_gradient(tf.image.resize_images(entire_canvas,
246
+ (self.hps.raster_size, self.hps.raster_size),
247
+ method=resize_method))
248
+ entire_photo_small = self.normalize_image_m1to1(entire_photo_small) # [-1.0-stroke, 1.0-BG]
249
+ entire_canvas_small = self.normalize_image_m1to1(entire_canvas_small) # [-1.0-stroke, 1.0-BG]
250
+
251
+ if self.hps.encode_cursor_type == 'value':
252
+ cursor_pos_norm = tf.expand_dims(cursor_pos, axis=1) # (N, 1, 1, 2)
253
+ cursor_pos_norm = tf.tile(cursor_pos_norm, [1, self.hps.raster_size, self.hps.raster_size, 1])
254
+ cursor_info = cursor_pos_norm
255
+ else:
256
+ raise Exception('Unknown encode_cursor_type', self.hps.encode_cursor_type)
257
+
258
+ batch_input_combined = tf.concat([patch_photo, patch_canvas, entire_photo_small, entire_canvas_small, cursor_info],
259
+ axis=-1) # [N, raster_size, raster_size, 6/10]
260
+ batch_input_local = tf.concat([patch_photo, patch_canvas], axis=-1) # [N, raster_size, raster_size, 2/4]
261
+ batch_input_global = tf.concat([entire_photo_small, entire_canvas_small, cursor_info],
262
+ axis=-1) # [N, raster_size, raster_size, 4/6]
263
+
264
+ if self.hps.model_mode == 'train':
265
+ is_training = True
266
+ dropout_keep_prob = self.hps.pix_drop_kp
267
+ else:
268
+ is_training = False
269
+ dropout_keep_prob = 1.0
270
+
271
+ if self.hps.add_coordconv:
272
+ batch_input_combined = self.add_coords(batch_input_combined) # (N, in_H, in_W, in_dim + 2)
273
+ batch_input_local = self.add_coords(batch_input_local) # (N, in_H, in_W, in_dim + 2)
274
+ batch_input_global = self.add_coords(batch_input_global) # (N, in_H, in_W, in_dim + 2)
275
+
276
+ if 'combine' in self.hps.encoder_type:
277
+ if self.hps.encoder_type == 'combine33':
278
+ image_embedding, _ = generative_cnn_c3_encoder_combine33(batch_input_local, batch_input_global,
279
+ is_training, dropout_keep_prob) # (N, 128)
280
+ elif self.hps.encoder_type == 'combine43':
281
+ image_embedding, _ = generative_cnn_c3_encoder_combine43(batch_input_local, batch_input_global,
282
+ is_training, dropout_keep_prob) # (N, 128)
283
+ elif self.hps.encoder_type == 'combine53':
284
+ image_embedding, _ = generative_cnn_c3_encoder_combine53(batch_input_local, batch_input_global,
285
+ is_training, dropout_keep_prob) # (N, 128)
286
+ elif self.hps.encoder_type == 'combineFC':
287
+ image_embedding, _ = generative_cnn_c3_encoder_combineFC(batch_input_local, batch_input_global,
288
+ is_training, dropout_keep_prob) # (N, 256)
289
+ else:
290
+ raise Exception('Unknown encoder_type', self.hps.encoder_type)
291
+ else:
292
+ with tf.variable_scope('Combined_Encoder', reuse=tf.AUTO_REUSE):
293
+ if self.hps.encoder_type == 'conv10':
294
+ image_embedding, _ = generative_cnn_encoder(batch_input_combined, is_training, dropout_keep_prob) # (N, 128)
295
+ elif self.hps.encoder_type == 'conv10_deep':
296
+ image_embedding, _ = generative_cnn_encoder_deeper(batch_input_combined, is_training, dropout_keep_prob) # (N, 512)
297
+ elif self.hps.encoder_type == 'conv13':
298
+ image_embedding, _ = generative_cnn_encoder_deeper13(batch_input_combined, is_training, dropout_keep_prob) # (N, 128)
299
+ elif self.hps.encoder_type == 'conv10_c3':
300
+ image_embedding, _ = generative_cnn_c3_encoder(batch_input_combined, is_training, dropout_keep_prob) # (N, 128)
301
+ elif self.hps.encoder_type == 'conv10_deep_c3':
302
+ image_embedding, _ = generative_cnn_c3_encoder_deeper(batch_input_combined, is_training, dropout_keep_prob) # (N, 512)
303
+ elif self.hps.encoder_type == 'conv13_c3':
304
+ image_embedding, _ = generative_cnn_c3_encoder_deeper13(batch_input_combined, is_training, dropout_keep_prob) # (N, 128)
305
+ elif self.hps.encoder_type == 'conv13_c3_attn':
306
+ image_embedding, _ = generative_cnn_c3_encoder_deeper13_attn(batch_input_combined, is_training, dropout_keep_prob) # (N, 128)
307
+ else:
308
+ raise Exception('Unknown encoder_type', self.hps.encoder_type)
309
+ return image_embedding
310
+
311
+ def build_seq_decoder(self, dec_cell, actual_input_x, initial_state):
312
+ rnn_output, last_state = self.rnn_decoder(dec_cell, initial_state, actual_input_x)
313
+ rnn_output_flat = tf.reshape(rnn_output, [-1, self.hps.dec_rnn_size])
314
+
315
+ pen_n_out = 2
316
+ params_n_out = 6
317
+
318
+ with tf.variable_scope('DEC_RNN_out_pen', reuse=tf.AUTO_REUSE):
319
+ output_w_pen = tf.get_variable('output_w', [self.hps.dec_rnn_size, pen_n_out])
320
+ output_b_pen = tf.get_variable('output_b', [pen_n_out], initializer=tf.constant_initializer(0.0))
321
+ output_pen = tf.nn.xw_plus_b(rnn_output_flat, output_w_pen, output_b_pen) # (N, pen_n_out)
322
+
323
+ with tf.variable_scope('DEC_RNN_out_params', reuse=tf.AUTO_REUSE):
324
+ output_w_params = tf.get_variable('output_w', [self.hps.dec_rnn_size, params_n_out])
325
+ output_b_params = tf.get_variable('output_b', [params_n_out], initializer=tf.constant_initializer(0.0))
326
+ output_params = tf.nn.xw_plus_b(rnn_output_flat, output_w_params, output_b_params) # (N, params_n_out)
327
+
328
+ output = tf.concat([output_pen, output_params], axis=1) # (N, n_out)
329
+
330
+ return output, last_state
331
+
332
+ def get_mixture_coef(self, outputs):
333
+ z = outputs
334
+ z_pen_logits = z[:, 0:2] # (N, 2), pen states
335
+ z_other_params_logits = z[:, 2:] # (N, 6)
336
+
337
+ z_pen = tf.nn.softmax(z_pen_logits) # (N, 2)
338
+ if self.hps.position_format == 'abs':
339
+ x1y1 = tf.nn.sigmoid(z_other_params_logits[:, 0:2]) # (N, 2)
340
+ x2y2 = tf.tanh(z_other_params_logits[:, 2:4]) # (N, 2)
341
+ widths = tf.nn.sigmoid(z_other_params_logits[:, 4:5]) # (N, 1)
342
+ widths = tf.add(tf.multiply(widths, 1.0 - self.hps.min_width), self.hps.min_width)
343
+ scaling = tf.nn.sigmoid(z_other_params_logits[:, 5:6]) * self.hps.max_scaling # (N, 1), [0.0, max_scaling]
344
+ # scaling = tf.add(tf.multiply(scaling, (self.hps.max_scaling - self.hps.min_scaling) / self.hps.max_scaling),
345
+ # self.hps.min_scaling)
346
+ z_other_params = tf.concat([x1y1, x2y2, widths, scaling], axis=-1) # (N, 6)
347
+ else: # "rel"
348
+ raise Exception('Unknown position_format', self.hps.position_format)
349
+
350
+ r = [z_other_params, z_pen]
351
+ return r
352
+
353
+ ###########################
354
+
355
+ def get_decoder_inputs(self):
356
+ initial_state = self.dec_cell.zero_state(batch_size=self.hps.batch_size, dtype=tf.float32)
357
+ return initial_state
358
+
359
+ def rnn_decoder(self, dec_cell, initial_state, actual_input_x):
360
+ with tf.variable_scope("RNN_DEC", reuse=tf.AUTO_REUSE):
361
+ output, last_state = tf.nn.dynamic_rnn(
362
+ dec_cell,
363
+ actual_input_x,
364
+ initial_state=initial_state,
365
+ time_major=False,
366
+ swap_memory=True,
367
+ dtype=tf.float32)
368
+ return output, last_state
369
+
370
+ ###########################
371
+
372
+ def image_padding(self, ori_image, window_size, pad_value):
373
+ """
374
+ Pad with (bg)
375
+ :param ori_image:
376
+ :return:
377
+ """
378
+ paddings = [[0, 0],
379
+ [window_size // 2, window_size // 2],
380
+ [window_size // 2, window_size // 2],
381
+ [0, 0]]
382
+ pad_img = tf.pad(ori_image, paddings=paddings, mode='CONSTANT', constant_values=pad_value) # (N, H_p, W_p, k)
383
+ return pad_img
384
+
385
+ def image_cropping_fn(self, fn_inputs):
386
+ """
387
+ crop the patch
388
+ :return:
389
+ """
390
+ index_offset = self.hps.input_channel - 1
391
+ input_image = fn_inputs[:, :, 0:2 + index_offset] # (image_size, image_size, -), [0.0-BG, 1.0-stroke]
392
+ cursor_pos = fn_inputs[0, 0, 2 + index_offset:4 + index_offset] # (2), in [0.0, 1.0)
393
+ image_size = fn_inputs[0, 0, 4 + index_offset] # (), float32
394
+ window_size = tf.cast(fn_inputs[0, 0, 5 + index_offset], tf.int32) # ()
395
+
396
+ input_img_reshape = tf.expand_dims(input_image, axis=0)
397
+ pad_img = self.image_padding(input_img_reshape, window_size, pad_value=0.0)
398
+
399
+ cursor_pos = tf.cast(tf.round(tf.multiply(cursor_pos, image_size)), dtype=tf.int32)
400
+ x0, x1 = cursor_pos[0], cursor_pos[0] + window_size # ()
401
+ y0, y1 = cursor_pos[1], cursor_pos[1] + window_size # ()
402
+ patch_image = pad_img[:, y0:y1, x0:x1, :] # (1, window_size, window_size, 2/4)
403
+
404
+ # resize to raster_size
405
+ patch_image_scaled = tf.image.resize_images(patch_image, (self.hps.raster_size, self.hps.raster_size),
406
+ method=tf.image.ResizeMethod.AREA)
407
+ patch_image_scaled = tf.squeeze(patch_image_scaled, axis=0)
408
+ # patch_canvas_scaled: (raster_size, raster_size, 2/4), [0.0-BG, 1.0-stroke]
409
+
410
+ return patch_image_scaled
411
+
412
+ def image_cropping(self, cursor_position, input_img, image_size, window_sizes):
413
+ """
414
+ :param cursor_position: (N, 1, 2), float type, in size [0.0, 1.0)
415
+ :param input_img: (N, image_size, image_size, 2/4), [0.0-BG, 1.0-stroke]
416
+ :param window_sizes: (N, 1, 1), float32, with grad
417
+ """
418
+ input_img_ = input_img
419
+ window_sizes_non_grad = tf.stop_gradient(tf.round(window_sizes)) # (N, 1, 1), no grad
420
+
421
+ cursor_position_ = tf.reshape(cursor_position, (-1, 1, 1, 2)) # (N, 1, 1, 2)
422
+ cursor_position_ = tf.tile(cursor_position_, [1, image_size, image_size, 1]) # (N, image_size, image_size, 2)
423
+
424
+ image_size_ = tf.reshape(tf.cast(image_size, tf.float32), (1, 1, 1, 1)) # (1, 1, 1, 1)
425
+ image_size_ = tf.tile(image_size_, [self.hps.batch_size, image_size, image_size, 1])
426
+
427
+ window_sizes_ = tf.reshape(window_sizes_non_grad, (-1, 1, 1, 1)) # (N, 1, 1, 1)
428
+ window_sizes_ = tf.tile(window_sizes_, [1, image_size, image_size, 1]) # (N, image_size, image_size, 1)
429
+
430
+ fn_inputs = tf.concat([input_img_, cursor_position_, image_size_, window_sizes_],
431
+ axis=-1) # (N, image_size, image_size, 2/4 + 4)
432
+ curr_patch_imgs = tf.map_fn(self.image_cropping_fn, fn_inputs, parallel_iterations=32) # (N, raster_size, raster_size, -)
433
+ return curr_patch_imgs
434
+
435
+ def image_cropping_v3(self, cursor_position, input_img, image_size, window_sizes):
436
+ """
437
+ :param cursor_position: (N, 1, 2), float type, in size [0.0, 1.0)
438
+ :param input_img: (N, image_size, image_size, k), [0.0-BG, 1.0-stroke]
439
+ :param window_sizes: (N, 1, 1), float32, with grad
440
+ """
441
+ window_sizes_non_grad = tf.stop_gradient(window_sizes) # (N, 1, 1), no grad
442
+
443
+ cursor_pos = tf.multiply(cursor_position, tf.cast(image_size, tf.float32))
444
+ cursor_x, cursor_y = tf.split(cursor_pos, 2, axis=-1) # (N, 1, 1)
445
+
446
+ y1 = cursor_y - (window_sizes_non_grad - 1.0) / 2
447
+ x1 = cursor_x - (window_sizes_non_grad - 1.0) / 2
448
+ y2 = y1 + (window_sizes_non_grad - 1.0)
449
+ x2 = x1 + (window_sizes_non_grad - 1.0)
450
+ boxes = tf.concat([y1, x1, y2, x2], axis=-1) # (N, 1, 4)
451
+ boxes = tf.squeeze(boxes, axis=1) # (N, 4)
452
+ boxes = boxes / tf.cast(image_size - 1, tf.float32)
453
+
454
+ box_ind = tf.ones_like(cursor_x)[:, 0, 0] # (N)
455
+ box_ind = tf.cast(box_ind, dtype=tf.int32)
456
+ box_ind = tf.cumsum(box_ind) - 1
457
+
458
+ curr_patch_imgs = tf.image.crop_and_resize(input_img, boxes, box_ind,
459
+ crop_size=[self.hps.raster_size, self.hps.raster_size])
460
+ # (N, raster_size, raster_size, k), [0.0-BG, 1.0-stroke]
461
+ return curr_patch_imgs
462
+
463
+ def get_points_and_raster_image(self, image_size):
464
+ ## generate the other_params and pen_ras and raster image for raster loss
465
+ prev_state = self.initial_state # (N, dec_rnn_size * 3)
466
+
467
+ prev_width = self.init_width # (N)
468
+ prev_width = tf.expand_dims(tf.expand_dims(prev_width, axis=-1), axis=-1) # (N, 1, 1)
469
+
470
+ prev_scaling = self.init_scaling # (N)
471
+ prev_scaling = tf.reshape(prev_scaling, (-1, 1, 1)) # (N, 1, 1)
472
+
473
+ prev_window_size = self.init_window_size # (N)
474
+ prev_window_size = tf.reshape(prev_window_size, (-1, 1, 1)) # (N, 1, 1)
475
+
476
+ cursor_position_temp = self.init_cursor
477
+ self.cursor_position = cursor_position_temp # (N, 1, 2), in size [0.0, 1.0)
478
+ cursor_position_loop = self.cursor_position
479
+
480
+ other_params_list = []
481
+ pen_ras_list = []
482
+
483
+ curr_canvas_soft = tf.zeros_like(self.input_photo[:, :, :, 0]) # (N, image_size, image_size), [0.0-BG, 1.0-stroke]
484
+ curr_canvas_hard = tf.zeros_like(curr_canvas_soft) # [0.0-BG, 1.0-stroke]
485
+
486
+ #### sampling part - start ####
487
+ self.curr_canvas_hard = curr_canvas_hard
488
+
489
+ if self.hps.cropping_type == 'v3':
490
+ cropping_func = self.image_cropping_v3
491
+ # elif self.hps.cropping_type == 'v2':
492
+ # cropping_func = self.image_cropping
493
+ else:
494
+ raise Exception('Unknown cropping_type', self.hps.cropping_type)
495
+
496
+ for time_i in range(self.hps.max_seq_len):
497
+ cursor_position_non_grad = tf.stop_gradient(cursor_position_loop) # (N, 1, 2), in size [0.0, 1.0)
498
+
499
+ curr_window_size = tf.multiply(prev_scaling, tf.stop_gradient(prev_window_size)) # float, with grad
500
+ curr_window_size = tf.maximum(curr_window_size, tf.cast(self.hps.min_window_size, tf.float32))
501
+ curr_window_size = tf.minimum(curr_window_size, tf.cast(image_size, tf.float32))
502
+
503
+ ## patch-level encoding
504
+ # Here, we make the gradients from canvas_z to curr_canvas_hard be None to avoid recurrent gradient propagation.
505
+ curr_canvas_hard_non_grad = tf.stop_gradient(self.curr_canvas_hard)
506
+ curr_canvas_hard_non_grad = tf.expand_dims(curr_canvas_hard_non_grad, axis=-1)
507
+
508
+ # input_photo: (N, image_size, image_size, 1/3), [0.0-stroke, 1.0-BG]
509
+ crop_inputs = tf.concat([1.0 - self.input_photo, curr_canvas_hard_non_grad], axis=-1) # (N, H_p, W_p, 1+1)
510
+
511
+ cropped_outputs = cropping_func(cursor_position_non_grad, crop_inputs, image_size, curr_window_size)
512
+ index_offset = self.hps.input_channel - 1
513
+ curr_patch_inputs = cropped_outputs[:, :, :, 0:1 + index_offset] # [0.0-BG, 1.0-stroke]
514
+ curr_patch_canvas_hard_non_grad = cropped_outputs[:, :, :, 1 + index_offset:2 + index_offset]
515
+ # (N, raster_size, raster_size, 1/3), [0.0-BG, 1.0-stroke]
516
+
517
+ curr_patch_inputs = 1.0 - curr_patch_inputs # [0.0-stroke, 1.0-BG]
518
+ curr_patch_inputs = self.normalize_image_m1to1(curr_patch_inputs)
519
+ # (N, raster_size, raster_size, 1/3), [-1.0-stroke, 1.0-BG]
520
+
521
+ # Normalizing image
522
+ curr_patch_canvas_hard_non_grad = 1.0 - curr_patch_canvas_hard_non_grad # [0.0-stroke, 1.0-BG]
523
+ curr_patch_canvas_hard_non_grad = self.normalize_image_m1to1(curr_patch_canvas_hard_non_grad) # [-1.0-stroke, 1.0-BG]
524
+
525
+ ## image-level encoding
526
+ combined_z = self.build_combined_encoder(
527
+ curr_patch_canvas_hard_non_grad,
528
+ curr_patch_inputs,
529
+ 1.0 - curr_canvas_hard_non_grad,
530
+ self.input_photo,
531
+ cursor_position_non_grad,
532
+ image_size,
533
+ curr_window_size) # (N, z_size)
534
+ combined_z = tf.expand_dims(combined_z, axis=1) # (N, 1, z_size)
535
+
536
+ curr_window_size_top_side_norm_non_grad = \
537
+ tf.stop_gradient(curr_window_size / tf.cast(image_size, tf.float32))
538
+ curr_window_size_bottom_side_norm_non_grad = \
539
+ tf.stop_gradient(curr_window_size / tf.cast(self.hps.min_window_size, tf.float32))
540
+ if not self.hps.concat_win_size:
541
+ combined_z = tf.concat([tf.stop_gradient(prev_width), combined_z], 2) # (N, 1, 2+z_size)
542
+ else:
543
+ combined_z = tf.concat([tf.stop_gradient(prev_width),
544
+ curr_window_size_top_side_norm_non_grad,
545
+ curr_window_size_bottom_side_norm_non_grad,
546
+ combined_z],
547
+ 2) # (N, 1, 2+z_size)
548
+
549
+ if self.hps.concat_cursor:
550
+ prev_input_x = tf.concat([cursor_position_non_grad, combined_z], 2) # (N, 1, 2+2+z_size)
551
+ else:
552
+ prev_input_x = combined_z # (N, 1, 2+z_size)
553
+
554
+ h_output, next_state = self.build_seq_decoder(self.dec_cell, prev_input_x, prev_state)
555
+ # h_output: (N * 1, n_out), next_state: (N, dec_rnn_size * 3)
556
+ [o_other_params, o_pen_ras] = self.get_mixture_coef(h_output)
557
+ # o_other_params: (N * 1, 6)
558
+ # o_pen_ras: (N * 1, 2), after softmax
559
+
560
+ o_other_params = tf.reshape(o_other_params, [-1, 1, 6]) # (N, 1, 6)
561
+ o_pen_ras_raw = tf.reshape(o_pen_ras, [-1, 1, 2]) # (N, 1, 2)
562
+
563
+ other_params_list.append(o_other_params)
564
+ pen_ras_list.append(o_pen_ras_raw)
565
+
566
+ #### sampling part - end ####
567
+
568
+ prev_state = next_state
569
+
570
+ other_params_ = tf.reshape(tf.concat(other_params_list, axis=1), [-1, 6]) # (N * max_seq_len, 6)
571
+ pen_ras_ = tf.reshape(tf.concat(pen_ras_list, axis=1), [-1, 2]) # (N * max_seq_len, 2)
572
+
573
+ return other_params_, pen_ras_, prev_state
574
+
575
+ def differentiable_argmax(self, input_pen, soft_beta):
576
+ """
577
+ Differentiable argmax trick.
578
+ :param input_pen: (N, n_class)
579
+ :return: pen_state: (N, 1)
580
+ """
581
+ def sign_onehot(x):
582
+ """
583
+ :param x: (N, n_class)
584
+ :return: (N, n_class)
585
+ """
586
+ y = tf.sign(tf.reduce_max(x, axis=-1, keepdims=True) - x)
587
+ y = (y - 1) * (-1)
588
+ return y
589
+
590
+ def softargmax(x, beta=1e2):
591
+ """
592
+ :param x: (N, n_class)
593
+ :param beta: 1e10 is the best. 1e2 is acceptable.
594
+ :return: (N)
595
+ """
596
+ x_range = tf.cumsum(tf.ones_like(x), axis=1) # (N, 2)
597
+ return tf.reduce_sum(tf.nn.softmax(x * beta) * x_range, axis=1) - 1
598
+
599
+ ## Better to use softargmax(beta=1e2). The sign_onehot's gradient is close to zero.
600
+ # pen_onehot = sign_onehot(input_pen) # one-hot form, (N * max_seq_len, 2)
601
+ # pen_state = pen_onehot[:, 1:2] # (N * max_seq_len, 1)
602
+ pen_state = softargmax(input_pen, soft_beta)
603
+ pen_state = tf.expand_dims(pen_state, axis=1) # (N * max_seq_len, 1)
604
+ return pen_state
model_common_train.py ADDED
@@ -0,0 +1,1193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import rnn
2
+ import tensorflow as tf
3
+
4
+ from subnet_tf_utils import generative_cnn_encoder, generative_cnn_encoder_deeper, generative_cnn_encoder_deeper13, \
5
+ generative_cnn_c3_encoder, generative_cnn_c3_encoder_deeper, generative_cnn_c3_encoder_deeper13, \
6
+ generative_cnn_c3_encoder_combine33, generative_cnn_c3_encoder_combine43, \
7
+ generative_cnn_c3_encoder_combine53, generative_cnn_c3_encoder_combineFC, \
8
+ generative_cnn_c3_encoder_deeper13_attn
9
+ from rasterization_utils.NeuralRenderer import NeuralRasterizorStep
10
+ from vgg_utils.VGG16 import vgg_net_slim
11
+
12
+
13
+ class VirtualSketchingModel(object):
14
+ def __init__(self, hps, gpu_mode=True, reuse=False):
15
+ """Initializer for the model.
16
+
17
+ Args:
18
+ hps: a HParams object containing model hyperparameters
19
+ gpu_mode: a boolean that when True, uses GPU mode.
20
+ reuse: a boolean that when true, attemps to reuse variables.
21
+ """
22
+ self.hps = hps
23
+ assert hps.model_mode in ['train', 'eval', 'eval_sample', 'sample']
24
+ # with tf.variable_scope('SCC', reuse=reuse):
25
+ if not gpu_mode:
26
+ with tf.device('/cpu:0'):
27
+ print('Model using cpu.')
28
+ self.build_model()
29
+ else:
30
+ print('-' * 100)
31
+ print('model_mode:', hps.model_mode)
32
+ print('Model using gpu.')
33
+ self.build_model()
34
+
35
+ def build_model(self):
36
+ """Define model architecture."""
37
+ self.config_model()
38
+
39
+ initial_state = self.get_decoder_inputs()
40
+ self.initial_state = initial_state
41
+ self.initial_state_list = tf.split(self.initial_state, self.total_loop, axis=0)
42
+
43
+ total_loss_list = []
44
+ ras_loss_list = []
45
+ perc_relu_raw_list = []
46
+ perc_relu_norm_list = []
47
+ sn_loss_list = []
48
+ cursor_outside_loss_list = []
49
+ win_size_outside_loss_list = []
50
+ early_state_loss_list = []
51
+
52
+ tower_grads = []
53
+
54
+ pred_raster_imgs_list = []
55
+ pred_raster_imgs_rgb_list = []
56
+
57
+ for t_i in range(self.total_loop):
58
+ gpu_idx = t_i // self.hps.loop_per_gpu
59
+ gpu_i = self.hps.gpus[gpu_idx]
60
+ print(self.hps.model_mode, 'model, gpu:', gpu_i, ', loop:', t_i % self.hps.loop_per_gpu)
61
+ with tf.device('/gpu:%d' % gpu_i):
62
+ with tf.name_scope('GPU_%d' % gpu_i) as scope:
63
+ if t_i > 0:
64
+ tf.get_variable_scope().reuse_variables()
65
+ else:
66
+ total_loss_list.clear()
67
+ ras_loss_list.clear()
68
+ perc_relu_raw_list.clear()
69
+ perc_relu_norm_list.clear()
70
+ sn_loss_list.clear()
71
+ cursor_outside_loss_list.clear()
72
+ win_size_outside_loss_list.clear()
73
+ early_state_loss_list.clear()
74
+ tower_grads.clear()
75
+ pred_raster_imgs_list.clear()
76
+ pred_raster_imgs_rgb_list.clear()
77
+
78
+ split_input_photo = self.input_photo_list[t_i]
79
+ split_image_size = self.image_size[t_i]
80
+ split_init_cursor = self.init_cursor_list[t_i]
81
+ split_initial_state = self.initial_state_list[t_i]
82
+ if self.hps.input_channel == 1:
83
+ split_target_sketch = split_input_photo
84
+ else:
85
+ split_target_sketch = self.target_sketch_list[t_i]
86
+
87
+ ## use pred as the prev points
88
+ other_params, pen_ras, final_state, pred_raster_images, pred_raster_images_rgb, \
89
+ pos_before_max_min, win_size_before_max_min \
90
+ = self.get_points_and_raster_image(split_initial_state, split_init_cursor, split_input_photo,
91
+ split_image_size)
92
+ # other_params: (N * max_seq_len, 6)
93
+ # pen_ras: (N * max_seq_len, 2), after softmax
94
+ # pos_before_max_min: (N, max_seq_len, 2), in image_size
95
+ # win_size_before_max_min: (N, max_seq_len, 1), in image_size
96
+
97
+ pred_raster_imgs = 1.0 - pred_raster_images # (N, image_size, image_size), [0.0-stroke, 1.0-BG]
98
+ pred_raster_imgs_rgb = 1.0 - pred_raster_images_rgb # (N, image_size, image_size, 3)
99
+ pred_raster_imgs_list.append(pred_raster_imgs)
100
+ pred_raster_imgs_rgb_list.append(pred_raster_imgs_rgb)
101
+
102
+ if not self.hps.use_softargmax:
103
+ pen_state_soft = pen_ras[:, 1:2] # (N * max_seq_len, 1)
104
+ else:
105
+ pen_state_soft = self.differentiable_argmax(pen_ras, self.hps.soft_beta) # (N * max_seq_len, 1)
106
+
107
+ pred_params = tf.concat([pen_state_soft, other_params], axis=1) # (N * max_seq_len, 7)
108
+ pred_params = tf.reshape(pred_params, shape=[-1, self.hps.max_seq_len, 7]) # (N, max_seq_len, 7)
109
+ # pred_params: (N, max_seq_len, 7)
110
+
111
+ if self.hps.model_mode == 'train' or self.hps.model_mode == 'eval':
112
+ raster_cost, sn_cost, cursor_outside_cost, winsize_outside_cost, \
113
+ early_pen_states_cost, \
114
+ perc_relu_loss_raw, perc_relu_loss_norm = \
115
+ self.build_losses(split_target_sketch, pred_raster_imgs, pred_params,
116
+ pos_before_max_min, win_size_before_max_min,
117
+ split_image_size)
118
+ # perc_relu_loss_raw, perc_relu_loss_norm: (n_layers)
119
+
120
+ ras_loss_list.append(raster_cost)
121
+ perc_relu_raw_list.append(perc_relu_loss_raw)
122
+ perc_relu_norm_list.append(perc_relu_loss_norm)
123
+ sn_loss_list.append(sn_cost)
124
+ cursor_outside_loss_list.append(cursor_outside_cost)
125
+ win_size_outside_loss_list.append(winsize_outside_cost)
126
+ early_state_loss_list.append(early_pen_states_cost)
127
+
128
+ if self.hps.model_mode == 'train':
129
+ total_cost_split, grads_and_vars_split = self.build_training_op_split(
130
+ raster_cost, sn_cost, cursor_outside_cost, winsize_outside_cost,
131
+ early_pen_states_cost)
132
+ total_loss_list.append(total_cost_split)
133
+ tower_grads.append(grads_and_vars_split)
134
+
135
+ self.raster_cost = tf.reduce_mean(tf.stack(ras_loss_list, axis=0))
136
+ self.perc_relu_losses_raw = tf.reduce_mean(tf.stack(perc_relu_raw_list, axis=0), axis=0) # (n_layers)
137
+ self.perc_relu_losses_norm = tf.reduce_mean(tf.stack(perc_relu_norm_list, axis=0), axis=0) # (n_layers)
138
+ self.stroke_num_cost = tf.reduce_mean(tf.stack(sn_loss_list, axis=0))
139
+ self.pos_outside_cost = tf.reduce_mean(tf.stack(cursor_outside_loss_list, axis=0))
140
+ self.win_size_outside_cost = tf.reduce_mean(tf.stack(win_size_outside_loss_list, axis=0))
141
+ self.early_pen_states_cost = tf.reduce_mean(tf.stack(early_state_loss_list, axis=0))
142
+ self.cost = tf.reduce_mean(tf.stack(total_loss_list, axis=0))
143
+
144
+ self.pred_raster_imgs = tf.concat(pred_raster_imgs_list, axis=0) # (N, image_size, image_size), [0.0-stroke, 1.0-BG]
145
+ self.pred_raster_imgs_rgb = tf.concat(pred_raster_imgs_rgb_list, axis=0) # (N, image_size, image_size, 3)
146
+
147
+ if self.hps.model_mode == 'train':
148
+ self.build_training_op(tower_grads)
149
+
150
+ def config_model(self):
151
+ if self.hps.model_mode == 'train':
152
+ self.global_step = tf.Variable(0, name='global_step', trainable=False)
153
+
154
+ if self.hps.dec_model == 'lstm':
155
+ dec_cell_fn = rnn.LSTMCell
156
+ elif self.hps.dec_model == 'layer_norm':
157
+ dec_cell_fn = rnn.LayerNormLSTMCell
158
+ elif self.hps.dec_model == 'hyper':
159
+ dec_cell_fn = rnn.HyperLSTMCell
160
+ else:
161
+ assert False, 'please choose a respectable cell'
162
+
163
+ use_recurrent_dropout = self.hps.use_recurrent_dropout
164
+ use_input_dropout = self.hps.use_input_dropout
165
+ use_output_dropout = self.hps.use_output_dropout
166
+
167
+ dec_cell = dec_cell_fn(
168
+ self.hps.dec_rnn_size,
169
+ use_recurrent_dropout=use_recurrent_dropout,
170
+ dropout_keep_prob=self.hps.recurrent_dropout_prob)
171
+
172
+ # dropout:
173
+ # print('Input dropout mode = %s.' % use_input_dropout)
174
+ # print('Output dropout mode = %s.' % use_output_dropout)
175
+ # print('Recurrent dropout mode = %s.' % use_recurrent_dropout)
176
+ if use_input_dropout:
177
+ print('Dropout to input w/ keep_prob = %4.4f.' % self.hps.input_dropout_prob)
178
+ dec_cell = tf.contrib.rnn.DropoutWrapper(
179
+ dec_cell, input_keep_prob=self.hps.input_dropout_prob)
180
+ if use_output_dropout:
181
+ print('Dropout to output w/ keep_prob = %4.4f.' % self.hps.output_dropout_prob)
182
+ dec_cell = tf.contrib.rnn.DropoutWrapper(
183
+ dec_cell, output_keep_prob=self.hps.output_dropout_prob)
184
+ self.dec_cell = dec_cell
185
+
186
+ self.total_loop = len(self.hps.gpus) * self.hps.loop_per_gpu
187
+
188
+ self.init_cursor = tf.placeholder(
189
+ dtype=tf.float32,
190
+ shape=[self.hps.batch_size, 1, 2]) # (N, 1, 2), in size [0.0, 1.0)
191
+ self.init_width = tf.placeholder(
192
+ dtype=tf.float32,
193
+ shape=[1]) # (1), in [0.0, 1.0]
194
+ self.image_size = tf.placeholder(dtype=tf.int32, shape=(self.total_loop)) # ()
195
+
196
+ self.init_cursor_list = tf.split(self.init_cursor, self.total_loop, axis=0)
197
+ self.input_photo_list = []
198
+ for loop_i in range(self.total_loop):
199
+ input_photo_i = tf.placeholder(dtype=tf.float32, shape=[None, None, None, self.hps.input_channel]) # [0.0-stroke, 1.0-BG]
200
+ self.input_photo_list.append(input_photo_i)
201
+
202
+ if self.hps.input_channel == 3:
203
+ self.target_sketch_list = []
204
+ for loop_i in range(self.total_loop):
205
+ target_sketch_i = tf.placeholder(dtype=tf.float32, shape=[None, None, None, 1]) # [0.0-stroke, 1.0-BG]
206
+ self.target_sketch_list.append(target_sketch_i)
207
+
208
+ if self.hps.model_mode == 'train' or self.hps.model_mode == 'eval':
209
+ self.stroke_num_loss_weight = tf.Variable(0.0, trainable=False)
210
+ self.early_pen_loss_start_idx = tf.Variable(0, dtype=tf.int32, trainable=False)
211
+ self.early_pen_loss_end_idx = tf.Variable(0, dtype=tf.int32, trainable=False)
212
+
213
+ if self.hps.model_mode == 'train':
214
+ self.perc_loss_mean_list = []
215
+ for loop_i in range(len(self.hps.perc_loss_layers)):
216
+ relu_loss_mean = tf.Variable(0.0, trainable=False)
217
+ self.perc_loss_mean_list.append(relu_loss_mean)
218
+ self.last_step_num = tf.Variable(0.0, trainable=False)
219
+
220
+ with tf.variable_scope('train_op', reuse=tf.AUTO_REUSE):
221
+ self.lr = tf.Variable(self.hps.learning_rate, trainable=False)
222
+ self.optimizer = tf.train.AdamOptimizer(self.lr)
223
+
224
+ ###########################
225
+
226
+ def normalize_image_m1to1(self, in_img_0to1):
227
+ norm_img_m1to1 = tf.multiply(in_img_0to1, 2.0)
228
+ norm_img_m1to1 = tf.subtract(norm_img_m1to1, 1.0)
229
+ return norm_img_m1to1
230
+
231
+ def add_coords(self, input_tensor):
232
+ batch_size_tensor = tf.shape(input_tensor)[0] # get N size
233
+
234
+ xx_ones = tf.ones([batch_size_tensor, self.hps.raster_size], dtype=tf.int32) # e.g. (N, raster_size)
235
+ xx_ones = tf.expand_dims(xx_ones, -1) # e.g. (N, raster_size, 1)
236
+ xx_range = tf.tile(tf.expand_dims(tf.range(self.hps.raster_size), 0),
237
+ [batch_size_tensor, 1]) # e.g. (N, raster_size)
238
+ xx_range = tf.expand_dims(xx_range, 1) # e.g. (N, 1, raster_size)
239
+
240
+ xx_channel = tf.matmul(xx_ones, xx_range) # e.g. (N, raster_size, raster_size)
241
+ xx_channel = tf.expand_dims(xx_channel, -1) # e.g. (N, raster_size, raster_size, 1)
242
+
243
+ yy_ones = tf.ones([batch_size_tensor, self.hps.raster_size], dtype=tf.int32) # e.g. (N, raster_size)
244
+ yy_ones = tf.expand_dims(yy_ones, 1) # e.g. (N, 1, raster_size)
245
+ yy_range = tf.tile(tf.expand_dims(tf.range(self.hps.raster_size), 0),
246
+ [batch_size_tensor, 1]) # (N, raster_size)
247
+ yy_range = tf.expand_dims(yy_range, -1) # e.g. (N, raster_size, 1)
248
+
249
+ yy_channel = tf.matmul(yy_range, yy_ones) # e.g. (N, raster_size, raster_size)
250
+ yy_channel = tf.expand_dims(yy_channel, -1) # e.g. (N, raster_size, raster_size, 1)
251
+
252
+ xx_channel = tf.cast(xx_channel, 'float32') / (self.hps.raster_size - 1)
253
+ yy_channel = tf.cast(yy_channel, 'float32') / (self.hps.raster_size - 1)
254
+ # xx_channel = xx_channel * 2 - 1 # [-1, 1]
255
+ # yy_channel = yy_channel * 2 - 1
256
+
257
+ ret = tf.concat([
258
+ input_tensor,
259
+ xx_channel,
260
+ yy_channel,
261
+ ], axis=-1) # e.g. (N, raster_size, raster_size, 4)
262
+
263
+ return ret
264
+
265
+ def build_combined_encoder(self, patch_canvas, patch_photo, entire_canvas, entire_photo, cursor_pos,
266
+ image_size, window_size):
267
+ """
268
+ :param patch_canvas: (N, raster_size, raster_size, 1), [-1.0-stroke, 1.0-BG]
269
+ :param patch_photo: (N, raster_size, raster_size, 1/3), [-1.0-stroke, 1.0-BG]
270
+ :param entire_canvas: (N, image_size, image_size, 1), [0.0-stroke, 1.0-BG]
271
+ :param entire_photo: (N, image_size, image_size, 1/3), [0.0-stroke, 1.0-BG]
272
+ :param cursor_pos: (N, 1, 2), in size [0.0, 1.0)
273
+ :param window_size: (N, 1, 1), float, in large size
274
+ :return:
275
+ """
276
+ if self.hps.resize_method == 'BILINEAR':
277
+ resize_method = tf.image.ResizeMethod.BILINEAR
278
+ elif self.hps.resize_method == 'NEAREST_NEIGHBOR':
279
+ resize_method = tf.image.ResizeMethod.NEAREST_NEIGHBOR
280
+ elif self.hps.resize_method == 'BICUBIC':
281
+ resize_method = tf.image.ResizeMethod.BICUBIC
282
+ elif self.hps.resize_method == 'AREA':
283
+ resize_method = tf.image.ResizeMethod.AREA
284
+ else:
285
+ raise Exception('unknown resize_method', self.hps.resize_method)
286
+
287
+ patch_photo = tf.stop_gradient(patch_photo)
288
+ patch_canvas = tf.stop_gradient(patch_canvas)
289
+ cursor_pos = tf.stop_gradient(cursor_pos)
290
+ window_size = tf.stop_gradient(window_size)
291
+
292
+ entire_photo_small = tf.stop_gradient(tf.image.resize_images(entire_photo,
293
+ (self.hps.raster_size, self.hps.raster_size),
294
+ method=resize_method))
295
+ entire_canvas_small = tf.stop_gradient(tf.image.resize_images(entire_canvas,
296
+ (self.hps.raster_size, self.hps.raster_size),
297
+ method=resize_method))
298
+ entire_photo_small = self.normalize_image_m1to1(entire_photo_small) # [-1.0-stroke, 1.0-BG]
299
+ entire_canvas_small = self.normalize_image_m1to1(entire_canvas_small) # [-1.0-stroke, 1.0-BG]
300
+
301
+ if self.hps.encode_cursor_type == 'value':
302
+ cursor_pos_norm = tf.expand_dims(cursor_pos, axis=1) # (N, 1, 1, 2)
303
+ cursor_pos_norm = tf.tile(cursor_pos_norm, [1, self.hps.raster_size, self.hps.raster_size, 1])
304
+ cursor_info = cursor_pos_norm
305
+ else:
306
+ raise Exception('Unknown encode_cursor_type', self.hps.encode_cursor_type)
307
+
308
+ batch_input_combined = tf.concat([patch_photo, patch_canvas, entire_photo_small, entire_canvas_small, cursor_info],
309
+ axis=-1) # [N, raster_size, raster_size, 6/10]
310
+ batch_input_local = tf.concat([patch_photo, patch_canvas], axis=-1) # [N, raster_size, raster_size, 2/4]
311
+ batch_input_global = tf.concat([entire_photo_small, entire_canvas_small, cursor_info],
312
+ axis=-1) # [N, raster_size, raster_size, 4/6]
313
+
314
+ if self.hps.model_mode == 'train':
315
+ is_training = True
316
+ dropout_keep_prob = self.hps.pix_drop_kp
317
+ else:
318
+ is_training = False
319
+ dropout_keep_prob = 1.0
320
+
321
+ if self.hps.add_coordconv:
322
+ batch_input_combined = self.add_coords(batch_input_combined) # (N, in_H, in_W, in_dim + 2)
323
+ batch_input_local = self.add_coords(batch_input_local) # (N, in_H, in_W, in_dim + 2)
324
+ batch_input_global = self.add_coords(batch_input_global) # (N, in_H, in_W, in_dim + 2)
325
+
326
+ if 'combine' in self.hps.encoder_type:
327
+ if self.hps.encoder_type == 'combine33':
328
+ image_embedding, _ = generative_cnn_c3_encoder_combine33(batch_input_local, batch_input_global,
329
+ is_training, dropout_keep_prob) # (N, 128)
330
+ elif self.hps.encoder_type == 'combine43':
331
+ image_embedding, _ = generative_cnn_c3_encoder_combine43(batch_input_local, batch_input_global,
332
+ is_training, dropout_keep_prob) # (N, 128)
333
+ elif self.hps.encoder_type == 'combine53':
334
+ image_embedding, _ = generative_cnn_c3_encoder_combine53(batch_input_local, batch_input_global,
335
+ is_training, dropout_keep_prob) # (N, 128)
336
+ elif self.hps.encoder_type == 'combineFC':
337
+ image_embedding, _ = generative_cnn_c3_encoder_combineFC(batch_input_local, batch_input_global,
338
+ is_training, dropout_keep_prob) # (N, 256)
339
+ else:
340
+ raise Exception('Unknown encoder_type', self.hps.encoder_type)
341
+ else:
342
+ with tf.variable_scope('Combined_Encoder', reuse=tf.AUTO_REUSE):
343
+ if self.hps.encoder_type == 'conv10':
344
+ image_embedding, _ = generative_cnn_encoder(batch_input_combined, is_training, dropout_keep_prob) # (N, 128)
345
+ elif self.hps.encoder_type == 'conv10_deep':
346
+ image_embedding, _ = generative_cnn_encoder_deeper(batch_input_combined, is_training, dropout_keep_prob) # (N, 512)
347
+ elif self.hps.encoder_type == 'conv13':
348
+ image_embedding, _ = generative_cnn_encoder_deeper13(batch_input_combined, is_training, dropout_keep_prob) # (N, 128)
349
+ elif self.hps.encoder_type == 'conv10_c3':
350
+ image_embedding, _ = generative_cnn_c3_encoder(batch_input_combined, is_training, dropout_keep_prob) # (N, 128)
351
+ elif self.hps.encoder_type == 'conv10_deep_c3':
352
+ image_embedding, _ = generative_cnn_c3_encoder_deeper(batch_input_combined, is_training, dropout_keep_prob) # (N, 512)
353
+ elif self.hps.encoder_type == 'conv13_c3':
354
+ image_embedding, _ = generative_cnn_c3_encoder_deeper13(batch_input_combined, is_training, dropout_keep_prob) # (N, 128)
355
+ elif self.hps.encoder_type == 'conv13_c3_attn':
356
+ image_embedding, _ = generative_cnn_c3_encoder_deeper13_attn(batch_input_combined, is_training, dropout_keep_prob) # (N, 128)
357
+ else:
358
+ raise Exception('Unknown encoder_type', self.hps.encoder_type)
359
+ return image_embedding
360
+
361
+ def build_seq_decoder(self, dec_cell, actual_input_x, initial_state):
362
+ rnn_output, last_state = self.rnn_decoder(dec_cell, initial_state, actual_input_x)
363
+ rnn_output_flat = tf.reshape(rnn_output, [-1, self.hps.dec_rnn_size])
364
+
365
+ pen_n_out = 2
366
+ params_n_out = 6
367
+
368
+ with tf.variable_scope('DEC_RNN_out_pen', reuse=tf.AUTO_REUSE):
369
+ output_w_pen = tf.get_variable('output_w', [self.hps.dec_rnn_size, pen_n_out])
370
+ output_b_pen = tf.get_variable('output_b', [pen_n_out], initializer=tf.constant_initializer(0.0))
371
+ output_pen = tf.nn.xw_plus_b(rnn_output_flat, output_w_pen, output_b_pen) # (N, pen_n_out)
372
+
373
+ with tf.variable_scope('DEC_RNN_out_params', reuse=tf.AUTO_REUSE):
374
+ output_w_params = tf.get_variable('output_w', [self.hps.dec_rnn_size, params_n_out])
375
+ output_b_params = tf.get_variable('output_b', [params_n_out], initializer=tf.constant_initializer(0.0))
376
+ output_params = tf.nn.xw_plus_b(rnn_output_flat, output_w_params, output_b_params) # (N, params_n_out)
377
+
378
+ output = tf.concat([output_pen, output_params], axis=1) # (N, n_out)
379
+
380
+ return output, last_state
381
+
382
+ def get_mixture_coef(self, outputs):
383
+ z = outputs
384
+ z_pen_logits = z[:, 0:2] # (N, 2), pen states
385
+ z_other_params_logits = z[:, 2:] # (N, 6)
386
+
387
+ z_pen = tf.nn.softmax(z_pen_logits) # (N, 2)
388
+ if self.hps.position_format == 'abs':
389
+ x1y1 = tf.nn.sigmoid(z_other_params_logits[:, 0:2]) # (N, 2)
390
+ x2y2 = tf.tanh(z_other_params_logits[:, 2:4]) # (N, 2)
391
+ widths = tf.nn.sigmoid(z_other_params_logits[:, 4:5]) # (N, 1)
392
+ widths = tf.add(tf.multiply(widths, 1.0 - self.hps.min_width), self.hps.min_width)
393
+ scaling = tf.nn.sigmoid(z_other_params_logits[:, 5:6]) * self.hps.max_scaling # (N, 1), [0.0, max_scaling]
394
+ # scaling = tf.add(tf.multiply(scaling, (self.hps.max_scaling - self.hps.min_scaling) / self.hps.max_scaling),
395
+ # self.hps.min_scaling)
396
+ z_other_params = tf.concat([x1y1, x2y2, widths, scaling], axis=-1) # (N, 6)
397
+ else: # "rel"
398
+ raise Exception('Unknown position_format', self.hps.position_format)
399
+
400
+ r = [z_other_params, z_pen]
401
+ return r
402
+
403
+ ###########################
404
+
405
+ def get_decoder_inputs(self):
406
+ initial_state = self.dec_cell.zero_state(batch_size=self.hps.batch_size, dtype=tf.float32)
407
+ return initial_state
408
+
409
+ def rnn_decoder(self, dec_cell, initial_state, actual_input_x):
410
+ with tf.variable_scope("RNN_DEC", reuse=tf.AUTO_REUSE):
411
+ output, last_state = tf.nn.dynamic_rnn(
412
+ dec_cell,
413
+ actual_input_x,
414
+ initial_state=initial_state,
415
+ time_major=False,
416
+ swap_memory=True,
417
+ dtype=tf.float32)
418
+ return output, last_state
419
+
420
+ ###########################
421
+
422
+ def image_padding(self, ori_image, window_size, pad_value):
423
+ """
424
+ Pad with (bg)
425
+ :param ori_image:
426
+ :return:
427
+ """
428
+ paddings = [[0, 0],
429
+ [window_size // 2, window_size // 2],
430
+ [window_size // 2, window_size // 2],
431
+ [0, 0]]
432
+ pad_img = tf.pad(ori_image, paddings=paddings, mode='CONSTANT', constant_values=pad_value) # (N, H_p, W_p, k)
433
+ return pad_img
434
+
435
+ def image_cropping_fn(self, fn_inputs):
436
+ """
437
+ crop the patch
438
+ :return:
439
+ """
440
+ index_offset = self.hps.input_channel - 1
441
+ input_image = fn_inputs[:, :, 0:2 + index_offset] # (image_size, image_size, 2), [0.0-BG, 1.0-stroke]
442
+ cursor_pos = fn_inputs[0, 0, 2 + index_offset:4 + index_offset] # (2), in [0.0, 1.0)
443
+ image_size = fn_inputs[0, 0, 4 + index_offset] # (), float32
444
+ window_size = tf.cast(fn_inputs[0, 0, 5 + index_offset], tf.int32) # ()
445
+
446
+ input_img_reshape = tf.expand_dims(input_image, axis=0)
447
+ pad_img = self.image_padding(input_img_reshape, window_size, pad_value=0.0)
448
+
449
+ cursor_pos = tf.cast(tf.round(tf.multiply(cursor_pos, image_size)), dtype=tf.int32)
450
+ x0, x1 = cursor_pos[0], cursor_pos[0] + window_size # ()
451
+ y0, y1 = cursor_pos[1], cursor_pos[1] + window_size # ()
452
+ patch_image = pad_img[:, y0:y1, x0:x1, :] # (1, window_size, window_size, 2/4)
453
+
454
+ # resize to raster_size
455
+ patch_image_scaled = tf.image.resize_images(patch_image, (self.hps.raster_size, self.hps.raster_size),
456
+ method=tf.image.ResizeMethod.AREA)
457
+ patch_image_scaled = tf.squeeze(patch_image_scaled, axis=0)
458
+ # patch_canvas_scaled: (raster_size, raster_size, 2/4), [0.0-BG, 1.0-stroke]
459
+
460
+ return patch_image_scaled
461
+
462
+ def image_cropping(self, cursor_position, input_img, image_size, window_sizes):
463
+ """
464
+ :param cursor_position: (N, 1, 2), float type, in size [0.0, 1.0)
465
+ :param input_img: (N, image_size, image_size, 2/4), [0.0-BG, 1.0-stroke]
466
+ :param window_sizes: (N, 1, 1), float32, with grad
467
+ """
468
+ input_img_ = input_img
469
+ window_sizes_non_grad = tf.stop_gradient(tf.round(window_sizes)) # (N, 1, 1), no grad
470
+
471
+ cursor_position_ = tf.reshape(cursor_position, (-1, 1, 1, 2)) # (N, 1, 1, 2)
472
+ cursor_position_ = tf.tile(cursor_position_, [1, image_size, image_size, 1]) # (N, image_size, image_size, 2)
473
+
474
+ image_size_ = tf.reshape(tf.cast(image_size, tf.float32), (1, 1, 1, 1)) # (1, 1, 1, 1)
475
+ image_size_ = tf.tile(image_size_, [self.hps.batch_size // self.total_loop, image_size, image_size, 1])
476
+
477
+ window_sizes_ = tf.reshape(window_sizes_non_grad, (-1, 1, 1, 1)) # (N, 1, 1, 1)
478
+ window_sizes_ = tf.tile(window_sizes_, [1, image_size, image_size, 1]) # (N, image_size, image_size, 1)
479
+
480
+ fn_inputs = tf.concat([input_img_, cursor_position_, image_size_, window_sizes_],
481
+ axis=-1) # (N, image_size, image_size, 2/4 + 4)
482
+ curr_patch_imgs = tf.map_fn(self.image_cropping_fn, fn_inputs, parallel_iterations=32) # (N, raster_size, raster_size, -)
483
+ return curr_patch_imgs
484
+
485
+ def image_cropping_v3(self, cursor_position, input_img, image_size, window_sizes):
486
+ """
487
+ :param cursor_position: (N, 1, 2), float type, in size [0.0, 1.0)
488
+ :param input_img: (N, image_size, image_size, k), [0.0-BG, 1.0-stroke]
489
+ :param window_sizes: (N, 1, 1), float32, with grad
490
+ """
491
+ window_sizes_non_grad = tf.stop_gradient(window_sizes) # (N, 1, 1), no grad
492
+
493
+ cursor_pos = tf.multiply(cursor_position, tf.cast(image_size, tf.float32))
494
+ cursor_x, cursor_y = tf.split(cursor_pos, 2, axis=-1) # (N, 1, 1)
495
+
496
+ y1 = cursor_y - (window_sizes_non_grad - 1.0) / 2
497
+ x1 = cursor_x - (window_sizes_non_grad - 1.0) / 2
498
+ y2 = y1 + (window_sizes_non_grad - 1.0)
499
+ x2 = x1 + (window_sizes_non_grad - 1.0)
500
+ boxes = tf.concat([y1, x1, y2, x2], axis=-1) # (N, 1, 4)
501
+ boxes = tf.squeeze(boxes, axis=1) # (N, 4)
502
+ boxes = boxes / tf.cast(image_size - 1, tf.float32)
503
+
504
+ box_ind = tf.ones_like(cursor_x)[:, 0, 0] # (N)
505
+ box_ind = tf.cast(box_ind, dtype=tf.int32)
506
+ box_ind = tf.cumsum(box_ind) - 1
507
+
508
+ curr_patch_imgs = tf.image.crop_and_resize(input_img, boxes, box_ind,
509
+ crop_size=[self.hps.raster_size, self.hps.raster_size])
510
+ # (N, raster_size, raster_size, k), [0.0-BG, 1.0-stroke]
511
+ return curr_patch_imgs
512
+
513
+ def get_pixel_value(self, img, x, y):
514
+ """
515
+ Utility function to get pixel value for coordinate vectors x and y from a 4D tensor image.
516
+
517
+ Input
518
+ -----
519
+ - img: tensor of shape (B, H, W, C)
520
+ - x: flattened tensor of shape (B, H', W')
521
+ - y: flattened tensor of shape (B, H', W')
522
+
523
+ Returns
524
+ -------
525
+ - output: tensor of shape (B, H', W', C)
526
+ """
527
+ shape = tf.shape(x)
528
+ batch_size = shape[0]
529
+ height = shape[1]
530
+ width = shape[2]
531
+
532
+ batch_idx = tf.range(0, batch_size)
533
+ batch_idx = tf.reshape(batch_idx, (batch_size, 1, 1))
534
+ b = tf.tile(batch_idx, (1, height, width))
535
+
536
+ indices = tf.stack([b, y, x], 3)
537
+
538
+ return tf.gather_nd(img, indices)
539
+
540
+ def image_pasting_nondiff_single(self, fn_inputs):
541
+ patch_image = fn_inputs[:, :, 0:1] # (raster_size, raster_size, 1), [0.0-BG, 1.0-stroke]
542
+ cursor_pos = fn_inputs[0, 0, 1:3] # (2), in large size
543
+ image_size = tf.cast(fn_inputs[0, 0, 3], tf.int32) # ()
544
+ window_size = tf.cast(fn_inputs[0, 0, 4], tf.int32) # ()
545
+
546
+ patch_image_scaled = tf.expand_dims(patch_image, axis=0) # (1, raster_size, raster_size, 1)
547
+ patch_image_scaled = tf.image.resize_images(patch_image_scaled, (window_size, window_size),
548
+ method=tf.image.ResizeMethod.BILINEAR)
549
+ patch_image_scaled = tf.squeeze(patch_image_scaled, axis=0)
550
+ # patch_canvas_scaled: (window_size, window_size, 1)
551
+
552
+ cursor_pos = tf.cast(tf.round(cursor_pos), dtype=tf.int32) # (2)
553
+ cursor_x, cursor_y = cursor_pos[0], cursor_pos[1]
554
+
555
+ pad_up = cursor_y
556
+ pad_down = image_size - cursor_y
557
+ pad_left = cursor_x
558
+ pad_right = image_size - cursor_x
559
+
560
+ paddings = [[pad_up, pad_down],
561
+ [pad_left, pad_right],
562
+ [0, 0]]
563
+ pad_img = tf.pad(patch_image_scaled, paddings=paddings, mode='CONSTANT',
564
+ constant_values=0.0) # (H_p, W_p, 1), [0.0-BG, 1.0-stroke]
565
+
566
+ crop_start = window_size // 2
567
+ pasted_image = pad_img[crop_start: crop_start + image_size, crop_start: crop_start + image_size, :]
568
+ return pasted_image
569
+
570
+ def image_pasting_diff_single(self, fn_inputs):
571
+ patch_canvas = fn_inputs[:, :, 0:1] # (raster_size, raster_size, 1), [0.0-BG, 1.0-stroke]
572
+ cursor_pos = fn_inputs[0, 0, 1:3] # (2), in large size
573
+ image_size = tf.cast(fn_inputs[0, 0, 3], tf.int32) # ()
574
+ window_size = tf.cast(fn_inputs[0, 0, 4], tf.int32) # ()
575
+ cursor_x, cursor_y = cursor_pos[0], cursor_pos[1]
576
+
577
+ patch_canvas_scaled = tf.expand_dims(patch_canvas, axis=0) # (1, raster_size, raster_size, 1)
578
+ patch_canvas_scaled = tf.image.resize_images(patch_canvas_scaled, (window_size, window_size),
579
+ method=tf.image.ResizeMethod.BILINEAR)
580
+ # patch_canvas_scaled: (1, window_size, window_size, 1)
581
+
582
+ valid_canvas = self.image_pasting_diff_batch(patch_canvas_scaled,
583
+ tf.expand_dims(tf.expand_dims(cursor_pos, axis=0), axis=0),
584
+ window_size)
585
+ valid_canvas = tf.squeeze(valid_canvas, axis=0)
586
+ # (window_size + 1, window_size + 1, 1)
587
+
588
+ pad_up = tf.cast(tf.floor(cursor_y), tf.int32)
589
+ pad_down = image_size - 1 - tf.cast(tf.floor(cursor_y), tf.int32)
590
+ pad_left = tf.cast(tf.floor(cursor_x), tf.int32)
591
+ pad_right = image_size - 1 - tf.cast(tf.floor(cursor_x), tf.int32)
592
+
593
+ paddings = [[pad_up, pad_down],
594
+ [pad_left, pad_right],
595
+ [0, 0]]
596
+ pad_img = tf.pad(valid_canvas, paddings=paddings, mode='CONSTANT',
597
+ constant_values=0.0) # (H_p, W_p, 1), [0.0-BG, 1.0-stroke]
598
+
599
+ crop_start = window_size // 2
600
+ pasted_image = pad_img[crop_start: crop_start + image_size, crop_start: crop_start + image_size, :]
601
+ return pasted_image
602
+
603
+ def image_pasting_diff_single_v3(self, fn_inputs):
604
+ patch_canvas = fn_inputs[:, :, 0:1] # (raster_size, raster_size, 1), [0.0-BG, 1.0-stroke]
605
+ cursor_pos_a = fn_inputs[0, 0, 1:3] # (2), float32, in large size
606
+ image_size_a = tf.cast(fn_inputs[0, 0, 3], tf.int32) # ()
607
+ window_size_a = fn_inputs[0, 0, 4] # (), float32, with grad
608
+ raster_size_a = float(self.hps.raster_size)
609
+
610
+ padding_size = tf.cast(tf.ceil(window_size_a / 2.0), tf.int32)
611
+
612
+ x1y1_a = cursor_pos_a - window_size_a / 2.0 # (2), float32
613
+ x2y2_a = cursor_pos_a + window_size_a / 2.0 # (2), float32
614
+
615
+ x1y1_a_floor = tf.floor(x1y1_a) # (2)
616
+ x2y2_a_ceil = tf.ceil(x2y2_a) # (2)
617
+
618
+ cursor_pos_b_oricoord = (x1y1_a_floor + x2y2_a_ceil) / 2.0 # (2)
619
+ cursor_pos_b = (cursor_pos_b_oricoord - x1y1_a) / window_size_a * raster_size_a # (2)
620
+ raster_size_b = (x2y2_a_ceil - x1y1_a_floor) # (x, y)
621
+ image_size_b = raster_size_a
622
+ window_size_b = raster_size_a * (raster_size_b / window_size_a) # (x, y)
623
+
624
+ cursor_b_x, cursor_b_y = tf.split(cursor_pos_b, 2, axis=-1) # (1)
625
+
626
+ y1_b = cursor_b_y - (window_size_b[1] - 1.) / 2.
627
+ x1_b = cursor_b_x - (window_size_b[0] - 1.) / 2.
628
+ y2_b = y1_b + (window_size_b[1] - 1.)
629
+ x2_b = x1_b + (window_size_b[0] - 1.)
630
+ boxes_b = tf.concat([y1_b, x1_b, y2_b, x2_b], axis=-1) # (4)
631
+ boxes_b = boxes_b / tf.cast(image_size_b - 1, tf.float32) # with grad to window_size_a
632
+
633
+ box_ind_b = tf.ones((1), dtype=tf.int32) # (1)
634
+ box_ind_b = tf.cumsum(box_ind_b) - 1
635
+
636
+ patch_canvas = tf.expand_dims(patch_canvas, axis=0) # (1, raster_size, raster_size, 1), [0.0-BG, 1.0-stroke]
637
+ boxes_b = tf.expand_dims(boxes_b, axis=0) # (1, 4)
638
+
639
+ valid_canvas = tf.image.crop_and_resize(patch_canvas, boxes_b, box_ind_b,
640
+ crop_size=[raster_size_b[1], raster_size_b[0]])
641
+ valid_canvas = valid_canvas[0] # (raster_size_b, raster_size_b, 1)
642
+
643
+ pad_up = tf.cast(x1y1_a_floor[1], tf.int32) + padding_size
644
+ pad_down = image_size_a + padding_size - tf.cast(x2y2_a_ceil[1], tf.int32)
645
+ pad_left = tf.cast(x1y1_a_floor[0], tf.int32) + padding_size
646
+ pad_right = image_size_a + padding_size - tf.cast(x2y2_a_ceil[0], tf.int32)
647
+
648
+ paddings = [[pad_up, pad_down],
649
+ [pad_left, pad_right],
650
+ [0, 0]]
651
+ pad_img = tf.pad(valid_canvas, paddings=paddings, mode='CONSTANT',
652
+ constant_values=0.0) # (H_p, W_p, 1), [0.0-BG, 1.0-stroke]
653
+
654
+ pasted_image = pad_img[padding_size: padding_size + image_size_a, padding_size: padding_size + image_size_a, :]
655
+ return pasted_image
656
+
657
+ def image_pasting_diff_batch(self, patch_image, cursor_position, window_size):
658
+ """
659
+ :param patch_img: (N, window_size, window_size, 1), [0.0-BG, 1.0-stroke]
660
+ :param cursor_position: (N, 1, 2), in large size
661
+ :return:
662
+ """
663
+ paddings1 = [[0, 0],
664
+ [1, 1],
665
+ [1, 1],
666
+ [0, 0]]
667
+ patch_image_pad1 = tf.pad(patch_image, paddings=paddings1, mode='CONSTANT',
668
+ constant_values=0.0) # (N, window_size+2, window_size+2, 1), [0.0-BG, 1.0-stroke]
669
+
670
+ cursor_x, cursor_y = cursor_position[:, :, 0:1], cursor_position[:, :, 1:2] # (N, 1, 1)
671
+ cursor_x_f, cursor_y_f = tf.floor(cursor_x), tf.floor(cursor_y)
672
+ patch_x, patch_y = 1.0 - (cursor_x - cursor_x_f), 1.0 - (cursor_y - cursor_y_f) # (N, 1, 1)
673
+
674
+ x_ones = tf.ones_like(patch_x, dtype=tf.float32) # (N, 1, 1)
675
+ x_ones = tf.tile(x_ones, [1, 1, window_size]) # (N, 1, window_size)
676
+ patch_x = tf.concat([patch_x, x_ones], axis=-1) # (N, 1, window_size + 1)
677
+ patch_x = tf.tile(patch_x, [1, window_size + 1, 1]) # (N, window_size + 1, window_size + 1)
678
+ patch_x = tf.cumsum(patch_x, axis=-1) # (N, window_size + 1, window_size + 1)
679
+ patch_x0 = tf.cast(tf.floor(patch_x), tf.int32) # (N, window_size + 1, window_size + 1)
680
+ patch_x1 = patch_x0 + 1 # (N, window_size + 1, window_size + 1)
681
+
682
+ y_ones = tf.ones_like(patch_y, dtype=tf.float32) # (N, 1, 1)
683
+ y_ones = tf.tile(y_ones, [1, window_size, 1]) # (N, window_size, 1)
684
+ patch_y = tf.concat([patch_y, y_ones], axis=1) # (N, window_size + 1, 1)
685
+ patch_y = tf.tile(patch_y, [1, 1, window_size + 1]) # (N, window_size + 1, window_size + 1)
686
+ patch_y = tf.cumsum(patch_y, axis=1) # (N, window_size + 1, window_size + 1)
687
+ patch_y0 = tf.cast(tf.floor(patch_y), tf.int32) # (N, window_size + 1, window_size + 1)
688
+ patch_y1 = patch_y0 + 1 # (N, window_size + 1, window_size + 1)
689
+
690
+ # get pixel value at corner coords
691
+ valid_canvas_patch_a = self.get_pixel_value(patch_image_pad1, patch_x0, patch_y0)
692
+ valid_canvas_patch_b = self.get_pixel_value(patch_image_pad1, patch_x0, patch_y1)
693
+ valid_canvas_patch_c = self.get_pixel_value(patch_image_pad1, patch_x1, patch_y0)
694
+ valid_canvas_patch_d = self.get_pixel_value(patch_image_pad1, patch_x1, patch_y1)
695
+ # (N, window_size + 1, window_size + 1, 1)
696
+
697
+ patch_x0 = tf.cast(patch_x0, tf.float32)
698
+ patch_x1 = tf.cast(patch_x1, tf.float32)
699
+ patch_y0 = tf.cast(patch_y0, tf.float32)
700
+ patch_y1 = tf.cast(patch_y1, tf.float32)
701
+
702
+ # calculate deltas
703
+ wa = (patch_x1 - patch_x) * (patch_y1 - patch_y)
704
+ wb = (patch_x1 - patch_x) * (patch_y - patch_y0)
705
+ wc = (patch_x - patch_x0) * (patch_y1 - patch_y)
706
+ wd = (patch_x - patch_x0) * (patch_y - patch_y0)
707
+ # (N, window_size + 1, window_size + 1)
708
+
709
+ # add dimension for addition
710
+ wa = tf.expand_dims(wa, axis=3)
711
+ wb = tf.expand_dims(wb, axis=3)
712
+ wc = tf.expand_dims(wc, axis=3)
713
+ wd = tf.expand_dims(wd, axis=3)
714
+ # (N, window_size + 1, window_size + 1, 1)
715
+
716
+ # compute output
717
+ valid_canvas_patch_ = tf.add_n([wa * valid_canvas_patch_a,
718
+ wb * valid_canvas_patch_b,
719
+ wc * valid_canvas_patch_c,
720
+ wd * valid_canvas_patch_d]) # (N, window_size + 1, window_size + 1, 1)
721
+ return valid_canvas_patch_
722
+
723
+ def image_pasting(self, cursor_position_norm, patch_img, image_size, window_sizes, is_differentiable=False):
724
+ """
725
+ paste the patch_img to padded size based on cursor_position
726
+ :param cursor_position_norm: (N, 1, 2), float type, in size [0.0, 1.0)
727
+ :param patch_img: (N, raster_size, raster_size), [0.0-BG, 1.0-stroke]
728
+ :param window_sizes: (N, 1, 1), float32, with grad
729
+ :return:
730
+ """
731
+ cursor_position = tf.multiply(cursor_position_norm, tf.cast(image_size, tf.float32)) # in large size
732
+ window_sizes_r = tf.round(window_sizes) # (N, 1, 1), no grad
733
+
734
+ patch_img_ = tf.expand_dims(patch_img, axis=-1) # (N, raster_size, raster_size, 1)
735
+ cursor_position_step = tf.reshape(cursor_position, (-1, 1, 1, 2)) # (N, 1, 1, 2)
736
+ cursor_position_step = tf.tile(cursor_position_step, [1, self.hps.raster_size, self.hps.raster_size,
737
+ 1]) # (N, raster_size, raster_size, 2)
738
+ image_size_tile = tf.reshape(tf.cast(image_size, tf.float32), (1, 1, 1, 1)) # (N, 1, 1, 1)
739
+ image_size_tile = tf.tile(image_size_tile, [self.hps.batch_size // self.total_loop, self.hps.raster_size,
740
+ self.hps.raster_size, 1])
741
+ window_sizes_tile = tf.reshape(window_sizes_r, (-1, 1, 1, 1)) # (N, 1, 1, 1)
742
+ window_sizes_tile = tf.tile(window_sizes_tile, [1, self.hps.raster_size, self.hps.raster_size, 1])
743
+
744
+ pasting_inputs = tf.concat([patch_img_, cursor_position_step, image_size_tile, window_sizes_tile],
745
+ axis=-1) # (N, raster_size, raster_size, 5)
746
+
747
+ if is_differentiable:
748
+ curr_paste_imgs = tf.map_fn(self.image_pasting_diff_single, pasting_inputs,
749
+ parallel_iterations=32) # (N, image_size, image_size, 1)
750
+ else:
751
+ curr_paste_imgs = tf.map_fn(self.image_pasting_nondiff_single, pasting_inputs,
752
+ parallel_iterations=32) # (N, image_size, image_size, 1)
753
+ curr_paste_imgs = tf.squeeze(curr_paste_imgs, axis=-1) # (N, image_size, image_size)
754
+ return curr_paste_imgs
755
+
756
+ def image_pasting_v3(self, cursor_position_norm, patch_img, image_size, window_sizes, is_differentiable=False):
757
+ """
758
+ paste the patch_img to padded size based on cursor_position
759
+ :param cursor_position_norm: (N, 1, 2), float type, in size [0.0, 1.0)
760
+ :param patch_img: (N, raster_size, raster_size), [0.0-BG, 1.0-stroke]
761
+ :param window_sizes: (N, 1, 1), float32, with grad
762
+ :return:
763
+ """
764
+ cursor_position = tf.multiply(cursor_position_norm, tf.cast(image_size, tf.float32)) # in large size
765
+
766
+ if is_differentiable:
767
+ patch_img_ = tf.expand_dims(patch_img, axis=-1) # (N, raster_size, raster_size, 1)
768
+ cursor_position_step = tf.reshape(cursor_position, (-1, 1, 1, 2)) # (N, 1, 1, 2)
769
+ cursor_position_step = tf.tile(cursor_position_step, [1, self.hps.raster_size, self.hps.raster_size,
770
+ 1]) # (N, raster_size, raster_size, 2)
771
+ image_size_tile = tf.reshape(tf.cast(image_size, tf.float32), (1, 1, 1, 1)) # (N, 1, 1, 1)
772
+ image_size_tile = tf.tile(image_size_tile, [self.hps.batch_size // self.total_loop, self.hps.raster_size,
773
+ self.hps.raster_size, 1])
774
+ window_sizes_tile = tf.reshape(window_sizes, (-1, 1, 1, 1)) # (N, 1, 1, 1)
775
+ window_sizes_tile = tf.tile(window_sizes_tile, [1, self.hps.raster_size, self.hps.raster_size, 1])
776
+
777
+ pasting_inputs = tf.concat([patch_img_, cursor_position_step, image_size_tile, window_sizes_tile],
778
+ axis=-1) # (N, raster_size, raster_size, 5)
779
+ curr_paste_imgs = tf.map_fn(self.image_pasting_diff_single_v3, pasting_inputs,
780
+ parallel_iterations=32) # (N, image_size, image_size, 1)
781
+ else:
782
+ raise Exception('Unfinished...')
783
+ curr_paste_imgs = tf.squeeze(curr_paste_imgs, axis=-1) # (N, image_size, image_size)
784
+ return curr_paste_imgs
785
+
786
+ def get_points_and_raster_image(self, initial_state, init_cursor, input_photo, image_size):
787
+ ## generate the other_params and pen_ras and raster image for raster loss
788
+ prev_state = initial_state # (N, dec_rnn_size * 3)
789
+
790
+ prev_width = self.init_width # (1)
791
+ prev_width = tf.expand_dims(tf.expand_dims(prev_width, axis=0), axis=0) # (1, 1, 1)
792
+ prev_width = tf.tile(prev_width, [self.hps.batch_size // self.total_loop, 1, 1]) # (N, 1, 1)
793
+
794
+ prev_scaling = tf.ones((self.hps.batch_size // self.total_loop, 1, 1)) # (N, 1, 1)
795
+ prev_window_size = tf.ones((self.hps.batch_size // self.total_loop, 1, 1),
796
+ dtype=tf.float32) * float(self.hps.raster_size) # (N, 1, 1)
797
+
798
+ cursor_position_temp = init_cursor
799
+ self.cursor_position = cursor_position_temp # (N, 1, 2), in size [0.0, 1.0)
800
+ cursor_position_loop = self.cursor_position
801
+
802
+ other_params_list = []
803
+ pen_ras_list = []
804
+
805
+ pos_before_max_min_list = []
806
+ win_size_before_max_min_list = []
807
+
808
+ curr_canvas_soft = tf.zeros_like(input_photo[:, :, :, 0]) # (N, image_size, image_size), [0.0-BG, 1.0-stroke]
809
+ curr_canvas_soft_rgb = tf.tile(tf.zeros_like(input_photo[:, :, :, 0:1]), [1, 1, 1, 3]) # (N, image_size, image_size, 3), [0.0-BG, 1.0-stroke]
810
+ curr_canvas_hard = tf.zeros_like(curr_canvas_soft) # [0.0-BG, 1.0-stroke]
811
+
812
+ #### sampling part - start ####
813
+ self.curr_canvas_hard = curr_canvas_hard
814
+
815
+ rasterizor_st = NeuralRasterizorStep(
816
+ raster_size=self.hps.raster_size,
817
+ position_format=self.hps.position_format)
818
+
819
+ if self.hps.cropping_type == 'v3':
820
+ cropping_func = self.image_cropping_v3
821
+ # elif self.hps.cropping_type == 'v2':
822
+ # cropping_func = self.image_cropping
823
+ else:
824
+ raise Exception('Unknown cropping_type', self.hps.cropping_type)
825
+
826
+ if self.hps.pasting_type == 'v3':
827
+ pasting_func = self.image_pasting_v3
828
+ # elif self.hps.pasting_type == 'v2':
829
+ # pasting_func = self.image_pasting
830
+ else:
831
+ raise Exception('Unknown pasting_type', self.hps.pasting_type)
832
+
833
+ for time_i in range(self.hps.max_seq_len):
834
+ cursor_position_non_grad = tf.stop_gradient(cursor_position_loop) # (N, 1, 2), in size [0.0, 1.0)
835
+
836
+ curr_window_size = tf.multiply(prev_scaling, tf.stop_gradient(prev_window_size)) # float, with grad
837
+ curr_window_size = tf.maximum(curr_window_size, tf.cast(self.hps.min_window_size, tf.float32))
838
+ curr_window_size = tf.minimum(curr_window_size, tf.cast(image_size, tf.float32))
839
+
840
+ ## patch-level encoding
841
+ # Here, we make the gradients from canvas_z to curr_canvas_hard be None to avoid recurrent gradient propagation.
842
+ curr_canvas_hard_non_grad = tf.stop_gradient(self.curr_canvas_hard)
843
+ curr_canvas_hard_non_grad = tf.expand_dims(curr_canvas_hard_non_grad, axis=-1)
844
+
845
+ # input_photo: (N, image_size, image_size, 1/3), [0.0-stroke, 1.0-BG]
846
+ crop_inputs = tf.concat([1.0 - input_photo, curr_canvas_hard_non_grad], axis=-1) # (N, H_p, W_p, 1/3+1)
847
+
848
+ cropped_outputs = cropping_func(cursor_position_non_grad, crop_inputs, image_size, curr_window_size)
849
+ index_offset = self.hps.input_channel - 1
850
+ curr_patch_inputs = cropped_outputs[:, :, :, 0:1 + index_offset] # [0.0-BG, 1.0-stroke]
851
+ curr_patch_canvas_hard_non_grad = cropped_outputs[:, :, :, 1 + index_offset:2 + index_offset]
852
+ # (N, raster_size, raster_size, 1), [0.0-BG, 1.0-stroke]
853
+
854
+ curr_patch_inputs = 1.0 - curr_patch_inputs # [0.0-stroke, 1.0-BG]
855
+ curr_patch_inputs = self.normalize_image_m1to1(curr_patch_inputs)
856
+ # (N, raster_size, raster_size, 1/3), [-1.0-stroke, 1.0-BG]
857
+
858
+ # Normalizing image
859
+ curr_patch_canvas_hard_non_grad = 1.0 - curr_patch_canvas_hard_non_grad # [0.0-stroke, 1.0-BG]
860
+ curr_patch_canvas_hard_non_grad = self.normalize_image_m1to1(curr_patch_canvas_hard_non_grad) # [-1.0-stroke, 1.0-BG]
861
+
862
+ ## image-level encoding
863
+ combined_z = self.build_combined_encoder(
864
+ curr_patch_canvas_hard_non_grad,
865
+ curr_patch_inputs,
866
+ 1.0 - curr_canvas_hard_non_grad,
867
+ input_photo,
868
+ cursor_position_non_grad,
869
+ image_size,
870
+ curr_window_size) # (N, z_size)
871
+ combined_z = tf.expand_dims(combined_z, axis=1) # (N, 1, z_size)
872
+
873
+ curr_window_size_top_side_norm_non_grad = \
874
+ tf.stop_gradient(curr_window_size / tf.cast(image_size, tf.float32))
875
+ curr_window_size_bottom_side_norm_non_grad = \
876
+ tf.stop_gradient(curr_window_size / tf.cast(self.hps.min_window_size, tf.float32))
877
+ if not self.hps.concat_win_size:
878
+ combined_z = tf.concat([tf.stop_gradient(prev_width), combined_z], 2) # (N, 1, 2+z_size)
879
+ else:
880
+ combined_z = tf.concat([tf.stop_gradient(prev_width),
881
+ curr_window_size_top_side_norm_non_grad,
882
+ curr_window_size_bottom_side_norm_non_grad,
883
+ combined_z],
884
+ 2) # (N, 1, 2+z_size)
885
+
886
+ if self.hps.concat_cursor:
887
+ prev_input_x = tf.concat([cursor_position_non_grad, combined_z], 2) # (N, 1, 2+2+z_size)
888
+ else:
889
+ prev_input_x = combined_z # (N, 1, 2+z_size)
890
+
891
+ h_output, next_state = self.build_seq_decoder(self.dec_cell, prev_input_x, prev_state)
892
+ # h_output: (N * 1, n_out), next_state: (N, dec_rnn_size * 3)
893
+ [o_other_params, o_pen_ras] = self.get_mixture_coef(h_output)
894
+ # o_other_params: (N * 1, 6)
895
+ # o_pen_ras: (N * 1, 2), after softmax
896
+
897
+ o_other_params = tf.reshape(o_other_params, [-1, 1, 6]) # (N, 1, 6)
898
+ o_pen_ras_raw = tf.reshape(o_pen_ras, [-1, 1, 2]) # (N, 1, 2)
899
+
900
+ other_params_list.append(o_other_params)
901
+ pen_ras_list.append(o_pen_ras_raw)
902
+
903
+ #### sampling part - end ####
904
+
905
+ if self.hps.model_mode == 'train' or self.hps.model_mode == 'eval' or self.hps.model_mode == 'eval_sample':
906
+ # use renderer here to convert the strokes to image
907
+ curr_other_params = tf.squeeze(o_other_params, axis=1) # (N, 6), (x1, y1)=[0.0, 1.0], (x2, y2)=[-1.0, 1.0]
908
+ x1y1, x2y2, width2, scaling = curr_other_params[:, 0:2], curr_other_params[:, 2:4],\
909
+ curr_other_params[:, 4:5], curr_other_params[:, 5:6]
910
+ x0y0 = tf.zeros_like(x2y2) # (N, 2), [-1.0, 1.0]
911
+ x0y0 = tf.div(tf.add(x0y0, 1.0), 2.0) # (N, 2), [0.0, 1.0]
912
+ x2y2 = tf.div(tf.add(x2y2, 1.0), 2.0) # (N, 2), [0.0, 1.0]
913
+ widths = tf.concat([tf.squeeze(prev_width, axis=1), width2], axis=1) # (N, 2)
914
+ curr_other_params = tf.concat([x0y0, x1y1, x2y2, widths], axis=-1) # (N, 8), (x0, y0)&(x2, y2)=[0.0, 1.0]
915
+ curr_stroke_image = rasterizor_st.raster_func_stroke_abs(curr_other_params)
916
+ # (N, raster_size, raster_size), [0.0-BG, 1.0-stroke]
917
+
918
+ curr_stroke_image_large = pasting_func(cursor_position_loop, curr_stroke_image,
919
+ image_size, curr_window_size,
920
+ is_differentiable=self.hps.pasting_diff)
921
+ # (N, image_size, image_size), [0.0-BG, 1.0-stroke]
922
+
923
+ ## soft
924
+ if not self.hps.use_softargmax:
925
+ curr_state_soft = o_pen_ras[:, 1:2] # (N, 1)
926
+ else:
927
+ curr_state_soft = self.differentiable_argmax(o_pen_ras, self.hps.soft_beta) # (N, 1)
928
+
929
+ curr_state_soft = tf.expand_dims(curr_state_soft, axis=1) # (N, 1, 1)
930
+
931
+ filter_curr_stroke_image_soft = tf.multiply(tf.subtract(1.0, curr_state_soft), curr_stroke_image_large)
932
+ # (N, image_size, image_size), [0.0-BG, 1.0-stroke]
933
+ curr_canvas_soft = tf.add(curr_canvas_soft, filter_curr_stroke_image_soft) # [0.0-BG, 1.0-stroke]
934
+
935
+ ## hard
936
+ curr_state_hard = tf.expand_dims(tf.cast(tf.argmax(o_pen_ras_raw, axis=-1), dtype=tf.float32),
937
+ axis=-1) # (N, 1, 1)
938
+ filter_curr_stroke_image_hard = tf.multiply(tf.subtract(1.0, curr_state_hard), curr_stroke_image_large)
939
+ # (N, image_size, image_size), [0.0-BG, 1.0-stroke]
940
+ self.curr_canvas_hard = tf.add(self.curr_canvas_hard, filter_curr_stroke_image_hard) # [0.0-BG, 1.0-stroke]
941
+ self.curr_canvas_hard = tf.clip_by_value(self.curr_canvas_hard, 0.0, 1.0) # [0.0-BG, 1.0-stroke]
942
+
943
+ next_width = o_other_params[:, :, 4:5]
944
+ next_scaling = o_other_params[:, :, 5:6]
945
+ next_window_size = tf.multiply(next_scaling, tf.stop_gradient(curr_window_size)) # float, with grad
946
+ window_size_before_max_min = next_window_size # (N, 1, 1), large-level
947
+ win_size_before_max_min_list.append(window_size_before_max_min)
948
+ next_window_size = tf.maximum(next_window_size, tf.cast(self.hps.min_window_size, tf.float32))
949
+ next_window_size = tf.minimum(next_window_size, tf.cast(image_size, tf.float32))
950
+
951
+ prev_state = next_state
952
+ prev_width = next_width * curr_window_size / next_window_size # (N, 1, 1)
953
+ prev_scaling = next_scaling # (N, 1, 1))
954
+ prev_window_size = curr_window_size
955
+
956
+ # update the cursor position
957
+ new_cursor_offsets = tf.multiply(o_other_params[:, :, 2:4],
958
+ tf.divide(curr_window_size, 2.0)) # (N, 1, 2), window-level
959
+ new_cursor_offset_next = new_cursor_offsets
960
+ new_cursor_offset_next = tf.concat([new_cursor_offset_next[:, :, 1:2], new_cursor_offset_next[:, :, 0:1]], axis=-1)
961
+
962
+ cursor_position_loop_large = tf.multiply(cursor_position_loop, tf.cast(image_size, tf.float32))
963
+
964
+ if self.hps.stop_accu_grad:
965
+ stroke_position_next = tf.stop_gradient(cursor_position_loop_large) + new_cursor_offset_next # (N, 1, 2), large-level
966
+ else:
967
+ stroke_position_next = cursor_position_loop_large + new_cursor_offset_next # (N, 1, 2), large-level
968
+
969
+ stroke_position_before_max_min = stroke_position_next # (N, 1, 2), large-level
970
+ pos_before_max_min_list.append(stroke_position_before_max_min)
971
+
972
+ if self.hps.cursor_type == 'next':
973
+ cursor_position_loop_large = stroke_position_next # (N, 1, 2), large-level
974
+ else:
975
+ raise Exception('Unknown cursor_type')
976
+
977
+ cursor_position_loop_large = tf.maximum(cursor_position_loop_large, 0.0)
978
+ cursor_position_loop_large = tf.minimum(cursor_position_loop_large, tf.cast(image_size - 1, tf.float32))
979
+ cursor_position_loop = tf.div(cursor_position_loop_large, tf.cast(image_size, tf.float32))
980
+
981
+ curr_canvas_soft = tf.clip_by_value(curr_canvas_soft, 0.0, 1.0) # (N, raster_size, raster_size), [0.0-BG, 1.0-stroke]
982
+
983
+ other_params_ = tf.reshape(tf.concat(other_params_list, axis=1), [-1, 6]) # (N * max_seq_len, 6)
984
+ pen_ras_ = tf.reshape(tf.concat(pen_ras_list, axis=1), [-1, 2]) # (N * max_seq_len, 2)
985
+ pos_before_max_min_ = tf.concat(pos_before_max_min_list, axis=1) # (N, max_seq_len, 2)
986
+ win_size_before_max_min_ = tf.concat(win_size_before_max_min_list, axis=1) # (N, max_seq_len, 1)
987
+
988
+ return other_params_, pen_ras_, prev_state, curr_canvas_soft, curr_canvas_soft_rgb, \
989
+ pos_before_max_min_, win_size_before_max_min_
990
+
991
+ def differentiable_argmax(self, input_pen, soft_beta):
992
+ """
993
+ Differentiable argmax trick.
994
+ :param input_pen: (N, n_class)
995
+ :return: pen_state: (N, 1)
996
+ """
997
+ def sign_onehot(x):
998
+ """
999
+ :param x: (N, n_class)
1000
+ :return: (N, n_class)
1001
+ """
1002
+ y = tf.sign(tf.reduce_max(x, axis=-1, keepdims=True) - x)
1003
+ y = (y - 1) * (-1)
1004
+ return y
1005
+
1006
+ def softargmax(x, beta=1e2):
1007
+ """
1008
+ :param x: (N, n_class)
1009
+ :param beta: 1e10 is the best. 1e2 is acceptable.
1010
+ :return: (N)
1011
+ """
1012
+ x_range = tf.cumsum(tf.ones_like(x), axis=1) # (N, 2)
1013
+ return tf.reduce_sum(tf.nn.softmax(x * beta) * x_range, axis=1) - 1
1014
+
1015
+ ## Better to use softargmax(beta=1e2). The sign_onehot's gradient is close to zero.
1016
+ # pen_onehot = sign_onehot(input_pen) # one-hot form, (N * max_seq_len, 2)
1017
+ # pen_state = pen_onehot[:, 1:2] # (N * max_seq_len, 1)
1018
+ pen_state = softargmax(input_pen, soft_beta)
1019
+ pen_state = tf.expand_dims(pen_state, axis=1) # (N * max_seq_len, 1)
1020
+ return pen_state
1021
+
1022
+ def build_losses(self, target_sketch, pred_raster_imgs, pred_params,
1023
+ pos_before_max_min, win_size_before_max_min, image_size):
1024
+ def get_raster_loss(pred_imgs, gt_imgs, loss_type):
1025
+ perc_layer_losses_raw = []
1026
+ perc_layer_losses_weighted = []
1027
+ perc_layer_losses_norm = []
1028
+
1029
+ if loss_type == 'l1':
1030
+ ras_cost = tf.reduce_mean(tf.abs(tf.subtract(gt_imgs, pred_imgs))) # ()
1031
+ elif loss_type == 'l1_small':
1032
+ gt_imgs_small = tf.image.resize_images(tf.expand_dims(gt_imgs, axis=3), (32, 32))
1033
+ pred_imgs_small = tf.image.resize_images(tf.expand_dims(pred_imgs, axis=3), (32, 32))
1034
+ ras_cost = tf.reduce_mean(tf.abs(tf.subtract(gt_imgs_small, pred_imgs_small))) # ()
1035
+ elif loss_type == 'mse':
1036
+ ras_cost = tf.reduce_mean(tf.pow(tf.subtract(gt_imgs, pred_imgs), 2)) # ()
1037
+ elif loss_type == 'perceptual':
1038
+ return_map_pred = vgg_net_slim(pred_imgs, image_size)
1039
+ return_map_gt = vgg_net_slim(gt_imgs, image_size)
1040
+ perc_loss_type = 'l1' # [l1, mse]
1041
+ weighted_map = {'ReLU1_1': 100.0, 'ReLU1_2': 100.0,
1042
+ 'ReLU2_1': 100.0, 'ReLU2_2': 100.0,
1043
+ 'ReLU3_1': 10.0, 'ReLU3_2': 10.0, 'ReLU3_3': 10.0,
1044
+ 'ReLU4_1': 1.0, 'ReLU4_2': 1.0, 'ReLU4_3': 1.0,
1045
+ 'ReLU5_1': 1.0, 'ReLU5_2': 1.0, 'ReLU5_3': 1.0}
1046
+
1047
+ for perc_layer in self.hps.perc_loss_layers:
1048
+ if perc_loss_type == 'l1':
1049
+ perc_layer_loss = tf.reduce_mean(tf.abs(tf.subtract(return_map_pred[perc_layer],
1050
+ return_map_gt[perc_layer]))) # ()
1051
+ elif perc_loss_type == 'mse':
1052
+ perc_layer_loss = tf.reduce_mean(tf.pow(tf.subtract(return_map_pred[perc_layer],
1053
+ return_map_gt[perc_layer]), 2)) # ()
1054
+ else:
1055
+ raise NameError('Unknown perceptual loss type:', perc_loss_type)
1056
+ perc_layer_losses_raw.append(perc_layer_loss)
1057
+
1058
+ assert perc_layer in weighted_map
1059
+ perc_layer_losses_weighted.append(perc_layer_loss * weighted_map[perc_layer])
1060
+
1061
+ for loop_i in range(len(self.hps.perc_loss_layers)):
1062
+ perc_relu_loss_raw = perc_layer_losses_raw[loop_i] # ()
1063
+
1064
+ if self.hps.model_mode == 'train':
1065
+ curr_relu_mean = (self.perc_loss_mean_list[loop_i] * self.last_step_num + perc_relu_loss_raw) / (self.last_step_num + 1.0)
1066
+ relu_cost_norm = perc_relu_loss_raw / curr_relu_mean
1067
+ else:
1068
+ relu_cost_norm = perc_relu_loss_raw
1069
+ perc_layer_losses_norm.append(relu_cost_norm)
1070
+
1071
+ perc_layer_losses_raw = tf.stack(perc_layer_losses_raw, axis=0)
1072
+ perc_layer_losses_norm = tf.stack(perc_layer_losses_norm, axis=0)
1073
+
1074
+ if self.hps.perc_loss_fuse_type == 'max':
1075
+ ras_cost = tf.reduce_max(perc_layer_losses_norm)
1076
+ elif self.hps.perc_loss_fuse_type == 'add':
1077
+ ras_cost = tf.reduce_mean(perc_layer_losses_norm)
1078
+ elif self.hps.perc_loss_fuse_type == 'raw_add':
1079
+ ras_cost = tf.reduce_mean(perc_layer_losses_raw)
1080
+ elif self.hps.perc_loss_fuse_type == 'weighted_sum':
1081
+ ras_cost = tf.reduce_mean(perc_layer_losses_weighted)
1082
+ else:
1083
+ raise NameError('Unknown perc_loss_fuse_type:', self.hps.perc_loss_fuse_type)
1084
+
1085
+ elif loss_type == 'triplet':
1086
+ raise Exception('Solution for triplet loss is coming soon.')
1087
+ else:
1088
+ raise NameError('Unknown loss type:', loss_type)
1089
+
1090
+ if loss_type != 'perceptual':
1091
+ for perc_layer_i in self.hps.perc_loss_layers:
1092
+ perc_layer_losses_raw.append(tf.constant(0.0))
1093
+ perc_layer_losses_norm.append(tf.constant(0.0))
1094
+
1095
+ perc_layer_losses_raw = tf.stack(perc_layer_losses_raw, axis=0)
1096
+ perc_layer_losses_norm = tf.stack(perc_layer_losses_norm, axis=0)
1097
+
1098
+ return ras_cost, perc_layer_losses_raw, perc_layer_losses_norm
1099
+
1100
+ gt_raster_images = tf.squeeze(target_sketch, axis=3) # (N, raster_h, raster_w), [0.0-stroke, 1.0-BG]
1101
+ raster_cost, perc_relu_losses_raw, perc_relu_losses_norm = \
1102
+ get_raster_loss(pred_raster_imgs, gt_raster_images, loss_type=self.hps.raster_loss_base_type)
1103
+
1104
+ def get_stroke_num_loss(input_strokes):
1105
+ ending_state = input_strokes[:, :, 0] # (N, seq_len)
1106
+ stroke_num_loss_pre = tf.reduce_mean(ending_state) # larger is better, [0.0, 1.0]
1107
+ stroke_num_loss = 1.0 - stroke_num_loss_pre # lower is better, [0.0, 1.0]
1108
+ return stroke_num_loss
1109
+
1110
+ stroke_num_cost = get_stroke_num_loss(pred_params) # lower is better
1111
+
1112
+ def get_pos_outside_loss(pos_before_max_min_):
1113
+ pos_after_max_min = tf.maximum(pos_before_max_min_, 0.0)
1114
+ pos_after_max_min = tf.minimum(pos_after_max_min, tf.cast(image_size - 1, tf.float32)) # (N, max_seq_len, 2)
1115
+ pos_outside_loss = tf.reduce_mean(tf.abs(pos_before_max_min_ - pos_after_max_min))
1116
+ return pos_outside_loss
1117
+
1118
+ pos_outside_cost = get_pos_outside_loss(pos_before_max_min) # lower is better
1119
+
1120
+ def get_win_size_outside_loss(win_size_before_max_min_, min_window_size):
1121
+ win_size_outside_top_loss = tf.divide(
1122
+ tf.maximum(win_size_before_max_min_ - tf.cast(image_size, tf.float32), 0.0),
1123
+ tf.cast(image_size, tf.float32)) # (N, max_seq_len, 1)
1124
+ win_size_outside_bottom_loss = tf.divide(
1125
+ tf.maximum(tf.cast(min_window_size, tf.float32) - win_size_before_max_min_, 0.0),
1126
+ tf.cast(min_window_size, tf.float32)) # (N, max_seq_len, 1)
1127
+ win_size_outside_loss = tf.reduce_mean(win_size_outside_top_loss + win_size_outside_bottom_loss)
1128
+ return win_size_outside_loss
1129
+
1130
+ win_size_outside_cost = get_win_size_outside_loss(win_size_before_max_min, self.hps.min_window_size) # lower is better
1131
+
1132
+ def get_early_pen_states_loss(input_strokes, curr_start, curr_end):
1133
+ # input_strokes: (N, max_seq_len, 7)
1134
+ pred_early_pen_states = input_strokes[:, curr_start:curr_end, 0] # (N, curr_early_len)
1135
+ pred_early_pen_states_min = tf.reduce_min(pred_early_pen_states, axis=1) # (N), should not be 1
1136
+ early_pen_states_loss = tf.reduce_mean(pred_early_pen_states_min) # lower is better
1137
+ return early_pen_states_loss
1138
+
1139
+ early_pen_states_cost = get_early_pen_states_loss(pred_params,
1140
+ self.early_pen_loss_start_idx, self.early_pen_loss_end_idx)
1141
+
1142
+ return raster_cost, stroke_num_cost, pos_outside_cost, win_size_outside_cost, \
1143
+ early_pen_states_cost, \
1144
+ perc_relu_losses_raw, perc_relu_losses_norm
1145
+
1146
+ def build_training_op_split(self, raster_cost, sn_cost, cursor_outside_cost, win_size_outside_cost,
1147
+ early_pen_states_cost):
1148
+ total_cost = self.hps.raster_loss_weight * raster_cost + \
1149
+ self.hps.early_pen_loss_weight * early_pen_states_cost + \
1150
+ self.stroke_num_loss_weight * sn_cost + \
1151
+ self.hps.outside_loss_weight * cursor_outside_cost + \
1152
+ self.hps.win_size_outside_loss_weight * win_size_outside_cost
1153
+
1154
+ tvars = [var for var in tf.trainable_variables()
1155
+ if 'raster_unit' not in var.op.name and 'VGG16' not in var.op.name]
1156
+ gvs = self.optimizer.compute_gradients(total_cost, var_list=tvars)
1157
+ return total_cost, gvs
1158
+
1159
+ def build_training_op(self, grad_list):
1160
+ with tf.variable_scope('train_op', reuse=tf.AUTO_REUSE):
1161
+ gvs = self.average_gradients(grad_list)
1162
+ g = self.hps.grad_clip
1163
+
1164
+ for grad, var in gvs:
1165
+ print('>>', var.op.name)
1166
+ if grad is None:
1167
+ print(' >> None value')
1168
+
1169
+ capped_gvs = [(tf.clip_by_value(grad, -g, g), var) for grad, var in gvs]
1170
+
1171
+ self.train_op = self.optimizer.apply_gradients(
1172
+ capped_gvs, global_step=self.global_step, name='train_step')
1173
+
1174
+ def average_gradients(self, grads_list):
1175
+ """
1176
+ Compute the average gradients.
1177
+ :param grads_list: list(of length N_GPU) of list(grad, var)
1178
+ :return:
1179
+ """
1180
+ avg_grads = []
1181
+ for grad_and_vars in zip(*grads_list):
1182
+ grads = []
1183
+ for g, _ in grad_and_vars:
1184
+ expanded_g = tf.expand_dims(g, 0)
1185
+ grads.append(expanded_g)
1186
+ grad = tf.concat(grads, axis=0)
1187
+ grad = tf.reduce_mean(grad, axis=0)
1188
+
1189
+ v = grad_and_vars[0][1]
1190
+ grad_and_var = (grad, v)
1191
+ avg_grads.append(grad_and_var)
1192
+
1193
+ return avg_grads
outputs/sampling/clean_line_drawings__pretrain_clean_line_drawings/muten_0_pred.png ADDED

Git LFS Details

  • SHA256: a8e55f7c655e24d1a862e3a87b16dc380c5c9135ce44e19e1034b9162f5354cf
  • Pointer size: 130 Bytes
  • Size of remote file: 54.4 kB
outputs/sampling/clean_line_drawings__pretrain_clean_line_drawings/muten_input.png ADDED

Git LFS Details

  • SHA256: 14558ccac28ead3dbf188fe4d1410969a1942c1489f93aaddfc9dd5ddfd739cb
  • Pointer size: 130 Bytes
  • Size of remote file: 22.6 kB
outputs/sampling/clean_line_drawings__pretrain_clean_line_drawings/order-compare/muten_0_pred.png ADDED

Git LFS Details

  • SHA256: 395dd2b8361aea30f6b4da07e07ebad64960c07ddb5bfad7f3f7a88ad0f3624c
  • Pointer size: 131 Bytes
  • Size of remote file: 185 kB
outputs/sampling/clean_line_drawings__pretrain_clean_line_drawings/order/muten_0_pred.png ADDED

Git LFS Details

  • SHA256: 27d279f46326c10071a679310734a518f178a2a9471a96f9af1751f47b3c9e3e
  • Pointer size: 131 Bytes
  • Size of remote file: 115 kB
outputs/sampling/clean_line_drawings__pretrain_clean_line_drawings/seq_data/muten_0.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:88b70ff82ac90ce05357d68fd4554ad7b785ba87fa0b5cda51a3e68387037536
3
+ size 52374
outputs/sampling/faces__pretrain_faces/1390_0_pred.png ADDED

Git LFS Details

  • SHA256: b3ae0eb5e8fbb261c70cdeeab635d34ccbc4182226114e1a7bdf16da2163c8cc
  • Pointer size: 129 Bytes
  • Size of remote file: 6.54 kB
outputs/sampling/faces__pretrain_faces/1390_input.png ADDED

Git LFS Details

  • SHA256: 3a0495693e1dfa07bcdfbeb5e8d45a2c7797758f39ddeebc7797b3e233605e1b
  • Pointer size: 130 Bytes
  • Size of remote file: 97.8 kB
outputs/sampling/faces__pretrain_faces/order-compare/1390_0_pred.png ADDED

Git LFS Details

  • SHA256: ecfee85706bc6d7c68d297ff6d260de30377592926905e75d3e55ba0568b2765
  • Pointer size: 131 Bytes
  • Size of remote file: 288 kB
outputs/sampling/faces__pretrain_faces/order/1390_0_pred.png ADDED

Git LFS Details

  • SHA256: 6fb1b0933f7f15eae8beb2a60e2ccdb9e626b9c74fab6c30281e7a5479c2e3e3
  • Pointer size: 130 Bytes
  • Size of remote file: 13.4 kB
outputs/sampling/faces__pretrain_faces/seq_data/1390_0.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:fc9fda3512b2bd4917d21e7a4f31504e77411311d1bbf11344f9ccce7bb0647e
3
+ size 6926
outputs/sampling/rough_sketches__pretrain_rough_sketches/order-compare/rocket_0_pred.png ADDED

Git LFS Details

  • SHA256: 172c1ecc9e9344d95808cc84e804b797f1565b606ec11c71906bf7851b171efb
  • Pointer size: 131 Bytes
  • Size of remote file: 364 kB
outputs/sampling/rough_sketches__pretrain_rough_sketches/order/rocket_0_pred.png ADDED

Git LFS Details

  • SHA256: b8f44fb9498d235e20c2a42ad33fcb285dadc6a7749bc17bd07ea36448ad4840
  • Pointer size: 130 Bytes
  • Size of remote file: 30.1 kB
outputs/sampling/rough_sketches__pretrain_rough_sketches/rocket_0_pred.png ADDED

Git LFS Details

  • SHA256: fc523c90cf7a8654e2ac52b7441168f2bbb78a2acdafd7b9ef706b08360d6e4d
  • Pointer size: 130 Bytes
  • Size of remote file: 12.8 kB
outputs/sampling/rough_sketches__pretrain_rough_sketches/rocket_input.png ADDED

Git LFS Details

  • SHA256: 53c5207ce96c715b852643aeab9490f939553b30f85223469afea32cda7dbe39
  • Pointer size: 131 Bytes
  • Size of remote file: 250 kB
outputs/sampling/rough_sketches__pretrain_rough_sketches/seq_data/rocket_0.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6dcaa3e3145b5d075b93c41ea2c761210a6b57edad87cf6895963b45cdaa39eb
3
+ size 13846
outputs/sampling/simplified/室内01/102-A_Proposed Site Plan__coarse_1/102-A_Proposed Site Plan__coarse_1_0.svg ADDED
outputs/sampling/simplified/室内01/102-A_Proposed Site Plan__coarse_1/102-A_Proposed Site Plan__coarse_1_0_pred.png ADDED

Git LFS Details

  • SHA256: 1e763c90a0a0183471857f2a5f5a1f7a59ab78335d933e6c13beaacd20306316
  • Pointer size: 130 Bytes
  • Size of remote file: 67.2 kB
outputs/sampling/simplified/室内01/102-A_Proposed Site Plan__coarse_1/102-A_Proposed Site Plan__coarse_1_input.png ADDED

Git LFS Details

  • SHA256: 0c74469b257878302b76c7f6a77595ce1f487a2f67a76eee3ea914ad65f24f49
  • Pointer size: 131 Bytes
  • Size of remote file: 239 kB
outputs/sampling/simplified/室内01/102-A_Proposed Site Plan__coarse_1/order-compare/102-A_Proposed Site Plan__coarse_1_0_pred.png ADDED

Git LFS Details

  • SHA256: 2494d9bfde41937eae94c3670c2d335adb6770d492a7d2260fa6c5aaffbd1340
  • Pointer size: 131 Bytes
  • Size of remote file: 223 kB