Akash James commited on
Commit
ef01fd7
1 Parent(s): 998185d

Initial commit

Browse files
Files changed (12) hide show
  1. .gitignore +135 -0
  2. LICENSE.md +177 -0
  3. README.md +57 -7
  4. app.py +50 -0
  5. models.py +297 -0
  6. models/photo_wct.pth +3 -0
  7. photo_gif.py +45 -0
  8. photo_smooth.py +101 -0
  9. photo_wct.py +171 -0
  10. process_stylization.py +195 -0
  11. requirements.txt +72 -0
  12. smooth_filter.py +405 -0
.gitignore ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ .Python
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ pip-wheel-metadata/
24
+ share/python-wheels/
25
+ *.egg-info/
26
+ .installed.cfg
27
+ *.egg
28
+ MANIFEST
29
+
30
+ # PyInstaller
31
+ # Usually these files are written by a python script from a template
32
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
33
+ *.manifest
34
+ *.spec
35
+
36
+ # Installer logs
37
+ pip-log.txt
38
+ pip-delete-this-directory.txt
39
+
40
+ # Unit test / coverage reports
41
+ htmlcov/
42
+ .tox/
43
+ .nox/
44
+ .coverage
45
+ .coverage.*
46
+ .cache
47
+ nosetests.xml
48
+ coverage.xml
49
+ *.cover
50
+ *.py,cover
51
+ .hypothesis/
52
+ .pytest_cache/
53
+
54
+ # Translations
55
+ *.mo
56
+ *.pot
57
+
58
+ # Django stuff:
59
+ *.log
60
+ local_settings.py
61
+ db.sqlite3
62
+ db.sqlite3-journal
63
+
64
+ # Flask stuff:
65
+ instance/
66
+ .webassets-cache
67
+
68
+ # Scrapy stuff:
69
+ .scrapy
70
+
71
+ # Sphinx documentation
72
+ docs/_build/
73
+
74
+ # PyBuilder
75
+ target/
76
+
77
+ # Jupyter Notebook
78
+ .ipynb_checkpoints
79
+
80
+ # IPython
81
+ profile_default/
82
+ ipython_config.py
83
+
84
+ # pyenv
85
+ .python-version
86
+
87
+ # pipenv
88
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
90
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
91
+ # install all needed dependencies.
92
+ #Pipfile.lock
93
+
94
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95
+ __pypackages__/
96
+
97
+ # Celery stuff
98
+ celerybeat-schedule
99
+ celerybeat.pid
100
+
101
+ # SageMath parsed files
102
+ *.sage.py
103
+
104
+ # Environments
105
+ .env
106
+ .venv
107
+ env/
108
+ venv/
109
+ ENV/
110
+ env.bak/
111
+ venv.bak/
112
+
113
+ # Spyder project settings
114
+ .spyderproject
115
+ .spyproject
116
+
117
+ # Rope project settings
118
+ .ropeproject
119
+
120
+ # mkdocs documentation
121
+ /site
122
+
123
+ # mypy
124
+ .mypy_cache/
125
+ .dmypy.json
126
+ dmypy.json
127
+
128
+ # Pyre type checker
129
+ .pyre/
130
+
131
+ # Banish Apple!
132
+ .DS_Store
133
+
134
+ # Dirs
135
+ flagged/
LICENSE.md ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## creative commons
2
+
3
+ # Attribution-NonCommercial-ShareAlike 4.0 International
4
+
5
+ Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
6
+
7
+ ### Using Creative Commons Public Licenses
8
+
9
+ Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
10
+
11
+ * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
12
+
13
+ * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
14
+
15
+ ## Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License
16
+
17
+ By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
18
+
19
+ ### Section 1 – Definitions.
20
+
21
+ a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
22
+
23
+ b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
24
+
25
+ c. __BY-NC-SA Compatible License__ means a license listed at [creativecommons.org/compatiblelicenses](http://creativecommons.org/compatiblelicenses), approved by Creative Commons as essentially the equivalent of this Public License.
26
+
27
+ d. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights.
28
+
29
+ e. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements.
30
+
31
+ f. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material.
32
+
33
+ g. __License Elements__ means the license attributes listed in the name of a Creative Commons Public License. The License Elements of this Public License are Attribution, NonCommercial, and ShareAlike.
34
+
35
+ h. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
36
+
37
+ i. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license.
38
+
39
+ h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
40
+
41
+ i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange.
42
+
43
+ j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them.
44
+
45
+ k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world.
46
+
47
+ l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
48
+
49
+ ### Section 2 – Scope.
50
+
51
+ a. ___License grant.___
52
+
53
+ 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
54
+
55
+ A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
56
+
57
+ B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
58
+
59
+ 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
60
+
61
+ 3. __Term.__ The term of this Public License is specified in Section 6(a).
62
+
63
+ 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
64
+
65
+ 5. __Downstream recipients.__
66
+
67
+ A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
68
+
69
+ B. __Additional offer from the Licensor – Adapted Material.__ Every recipient of Adapted Material from You automatically receives an offer from the Licensor to exercise the Licensed Rights in the Adapted Material under the conditions of the Adapter’s License You apply.
70
+
71
+ C. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
72
+
73
+ 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
74
+
75
+ b. ___Other rights.___
76
+
77
+ 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
78
+
79
+ 2. Patent and trademark rights are not licensed under this Public License.
80
+
81
+ 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
82
+
83
+ ### Section 3 – License Conditions.
84
+
85
+ Your exercise of the Licensed Rights is expressly made subject to the following conditions.
86
+
87
+ a. ___Attribution.___
88
+
89
+ 1. If You Share the Licensed Material (including in modified form), You must:
90
+
91
+ A. retain the following if it is supplied by the Licensor with the Licensed Material:
92
+
93
+ i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
94
+
95
+ ii. a copyright notice;
96
+
97
+ iii. a notice that refers to this Public License;
98
+
99
+ iv. a notice that refers to the disclaimer of warranties;
100
+
101
+ v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
102
+
103
+ B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
104
+
105
+ C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.
106
+
107
+ 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
108
+
109
+ 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
110
+
111
+ b. ___ShareAlike.___
112
+
113
+ In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
114
+
115
+ 1. The Adapter’s License You apply must be a Creative Commons license with the same License Elements, this version or later, or a BY-NC-SA Compatible License.
116
+
117
+ 2. You must include the text of, or the URI or hyperlink to, the Adapter's License You apply. You may satisfy this condition in any reasonable manner based on the medium, means, and context in which You Share Adapted Material.
118
+
119
+ 3. You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, Adapted Material that restrict exercise of the rights granted under the Adapter's License You apply.
120
+
121
+ ### Section 4 – Sui Generis Database Rights.
122
+
123
+ Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
124
+
125
+ a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
126
+
127
+ b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material, including for purposes of Section 3(b); and
128
+
129
+ c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.
130
+
131
+ For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
132
+
133
+ ### Section 5 – Disclaimer of Warranties and Limitation of Liability.
134
+
135
+ a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
136
+
137
+ b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
138
+
139
+ c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
140
+
141
+ ### Section 6 – Term and Termination.
142
+
143
+ a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
144
+
145
+ b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
146
+
147
+ 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
148
+
149
+ 2. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
150
+
151
+ For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
152
+
153
+ c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
154
+
155
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
156
+
157
+ ### Section 7 – Other Terms and Conditions.
158
+
159
+ a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
160
+
161
+ b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
162
+
163
+ ### Section 8 – Interpretation.
164
+
165
+ a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
166
+
167
+ b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
168
+
169
+ c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
170
+
171
+ d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
172
+
173
+ ```
174
+ Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses.
175
+
176
+ Creative Commons may be contacted at [creativecommons.org](http://creativecommons.org/).
177
+ ```
README.md CHANGED
@@ -1,13 +1,63 @@
1
  ---
2
- title: Photo Realistic Image Stylization
3
- emoji: 📊
4
- colorFrom: red
5
- colorTo: yellow
6
  sdk: gradio
7
- sdk_version: 3.6
8
  app_file: app.py
9
  pinned: false
10
- license: cc-by-sa-4.0
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Photo-Realistic-Image-Stylization
3
+ emoji: 🤯
4
+ colorFrom: indigo
5
+ colorTo: indigo
6
  sdk: gradio
7
+ sdk_version: 3.4.1
8
  app_file: app.py
9
  pinned: false
10
+ license: mit
11
  ---
12
 
13
+ [![License CC BY-NC-SA 4.0](https://img.shields.io/badge/license-CC4.0-blue.svg)](https://raw.githubusercontent.com/NVIDIA/FastPhotoStyle/master/LICENSE.md)
14
+
15
+ # Photo-Realistic-Image-Stylization
16
+
17
+ > Whitening and Colorization Transform from the paper "A Closed-form Solution to Photorealistic Image Stylization"
18
+
19
+ <br />
20
+
21
+ ---
22
+
23
+ ## Python dependencies
24
+
25
+ ```sh
26
+ pip3 install -r requirements.txt
27
+ ```
28
+
29
+ ---
30
+
31
+ <br />
32
+
33
+ ## Run the application
34
+
35
+ ```sh
36
+ python3 app.py
37
+ ```
38
+
39
+ On your terminal, you will see a prompt of the ipaddress to access -
40
+
41
+ ```sh
42
+ Running on local URL: http://127.0.0.1:7860
43
+ ```
44
+
45
+ <br />
46
+
47
+ ---
48
+
49
+ ## License
50
+ Copyright (C) 2018 NVIDIA Corporation. All rights reserved.
51
+ Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
52
+
53
+ <br />
54
+
55
+ ---
56
+
57
+ ## Citations
58
+
59
+ - [A Closed-form Solution to Photorealistic Image Stylization](https://arxiv.org/abs/1802.06474) <br>
60
+ [Yijun Li (UC Merced)](https://sites.google.com/site/yijunlimaverick/), [Ming-Yu Liu (NVIDIA)](http://mingyuliu.net/), [Xueting Li (UC Merced)](https://sunshineatnoon.github.io/), [Ming-Hsuan Yang (NVIDIA, UC Merced)](http://faculty.ucmerced.edu/mhyang/), [Jan Kautz (NVIDIA)](http://jankautz.com/) <br>
61
+
62
+ - [https://github.com/NVIDIA/FastPhotoStyle](https://github.com/NVIDIA/FastPhotoStyle) <br>
63
+
app.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import print_function
2
+ import torch
3
+ import process_stylization
4
+ from photo_wct import PhotoWCT
5
+ import gradio as gr
6
+
7
+ # Load model
8
+ model_path = './models/photo_wct.pth'
9
+ p_wct = PhotoWCT()
10
+ p_wct.load_state_dict(torch.load(model_path))
11
+
12
+ def run(content_img, style_img, cuda, post_processing, fast):
13
+ if fast == 0:
14
+ from photo_gif import GIFSmoothing
15
+ p_pro = GIFSmoothing(r=35, eps=0.001)
16
+ else:
17
+ from photo_smooth import Propagator
18
+ p_pro = Propagator()
19
+
20
+ if cuda:
21
+ p_wct.cuda(0)
22
+
23
+ output_img = process_stylization.stylization_gradio(
24
+ stylization_module=p_wct,
25
+ smoothing_module=p_pro,
26
+ content_image=content_img,
27
+ style_image=style_img,
28
+ cuda=cuda,
29
+ post_processing=post_processing
30
+ )
31
+
32
+ return output_img
33
+
34
+ if __name__ == '__main__':
35
+
36
+ style = gr.Interface(
37
+ fn=run,
38
+ inputs=[
39
+ gr.Image(label='Content Image'),
40
+ gr.Image(label='Stylize Image'),
41
+ gr.Checkbox(value=False, label='Use CUDA'),
42
+ gr.Checkbox(value=False, label='Post Processing'),
43
+ gr.Radio(choices=["Guided Image Filtering (Fast)", "Photorealisitic Smoothing (Slow)"], value="Guided Image Filtering (Fast)", type="index", label="Algorithm"),
44
+ ],
45
+ outputs=[gr.Image(
46
+ type="pil",
47
+ label="Result"),
48
+ ]
49
+ )
50
+ style.launch()
models.py ADDED
@@ -0,0 +1,297 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (C) 2018 NVIDIA Corporation. All rights reserved.
3
+ Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
4
+ """
5
+ import torch.nn as nn
6
+
7
+
8
+ class VGGEncoder(nn.Module):
9
+ def __init__(self, level):
10
+ super(VGGEncoder, self).__init__()
11
+ self.level = level
12
+
13
+ # 224 x 224
14
+ self.conv0 = nn.Conv2d(3, 3, 1, 1, 0)
15
+
16
+ self.pad1_1 = nn.ReflectionPad2d((1, 1, 1, 1))
17
+ # 226 x 226
18
+ self.conv1_1 = nn.Conv2d(3, 64, 3, 1, 0)
19
+ self.relu1_1 = nn.ReLU(inplace=True)
20
+ # 224 x 224
21
+
22
+ if level < 2: return
23
+
24
+ self.pad1_2 = nn.ReflectionPad2d((1, 1, 1, 1))
25
+ self.conv1_2 = nn.Conv2d(64, 64, 3, 1, 0)
26
+ self.relu1_2 = nn.ReLU(inplace=True)
27
+ # 224 x 224
28
+ self.maxpool1 = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)
29
+ # 112 x 112
30
+
31
+ self.pad2_1 = nn.ReflectionPad2d((1, 1, 1, 1))
32
+ self.conv2_1 = nn.Conv2d(64, 128, 3, 1, 0)
33
+ self.relu2_1 = nn.ReLU(inplace=True)
34
+ # 112 x 112
35
+
36
+ if level < 3: return
37
+
38
+ self.pad2_2 = nn.ReflectionPad2d((1, 1, 1, 1))
39
+ self.conv2_2 = nn.Conv2d(128, 128, 3, 1, 0)
40
+ self.relu2_2 = nn.ReLU(inplace=True)
41
+ # 112 x 112
42
+
43
+ self.maxpool2 = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)
44
+ # 56 x 56
45
+
46
+ self.pad3_1 = nn.ReflectionPad2d((1, 1, 1, 1))
47
+ self.conv3_1 = nn.Conv2d(128, 256, 3, 1, 0)
48
+ self.relu3_1 = nn.ReLU(inplace=True)
49
+ # 56 x 56
50
+
51
+ if level < 4: return
52
+
53
+ self.pad3_2 = nn.ReflectionPad2d((1, 1, 1, 1))
54
+ self.conv3_2 = nn.Conv2d(256, 256, 3, 1, 0)
55
+ self.relu3_2 = nn.ReLU(inplace=True)
56
+ # 56 x 56
57
+
58
+ self.pad3_3 = nn.ReflectionPad2d((1, 1, 1, 1))
59
+ self.conv3_3 = nn.Conv2d(256, 256, 3, 1, 0)
60
+ self.relu3_3 = nn.ReLU(inplace=True)
61
+ # 56 x 56
62
+
63
+ self.pad3_4 = nn.ReflectionPad2d((1, 1, 1, 1))
64
+ self.conv3_4 = nn.Conv2d(256, 256, 3, 1, 0)
65
+ self.relu3_4 = nn.ReLU(inplace=True)
66
+ # 56 x 56
67
+
68
+ self.maxpool3 = nn.MaxPool2d(kernel_size=2, stride=2, return_indices=True)
69
+ # 28 x 28
70
+
71
+ self.pad4_1 = nn.ReflectionPad2d((1, 1, 1, 1))
72
+ self.conv4_1 = nn.Conv2d(256, 512, 3, 1, 0)
73
+ self.relu4_1 = nn.ReLU(inplace=True)
74
+ # 28 x 28
75
+
76
+ def forward(self, x):
77
+ out = self.conv0(x)
78
+
79
+ out = self.pad1_1(out)
80
+ out = self.conv1_1(out)
81
+ out = self.relu1_1(out)
82
+
83
+ if self.level < 2:
84
+ return out
85
+
86
+ out = self.pad1_2(out)
87
+ out = self.conv1_2(out)
88
+ pool1 = self.relu1_2(out)
89
+
90
+ out, pool1_idx = self.maxpool1(pool1)
91
+
92
+ out = self.pad2_1(out)
93
+ out = self.conv2_1(out)
94
+ out = self.relu2_1(out)
95
+
96
+ if self.level < 3:
97
+ return out, pool1_idx, pool1.size()
98
+
99
+ out = self.pad2_2(out)
100
+ out = self.conv2_2(out)
101
+ pool2 = self.relu2_2(out)
102
+
103
+ out, pool2_idx = self.maxpool2(pool2)
104
+
105
+ out = self.pad3_1(out)
106
+ out = self.conv3_1(out)
107
+ out = self.relu3_1(out)
108
+
109
+ if self.level < 4:
110
+ return out, pool1_idx, pool1.size(), pool2_idx, pool2.size()
111
+
112
+ out = self.pad3_2(out)
113
+ out = self.conv3_2(out)
114
+ out = self.relu3_2(out)
115
+
116
+ out = self.pad3_3(out)
117
+ out = self.conv3_3(out)
118
+ out = self.relu3_3(out)
119
+
120
+ out = self.pad3_4(out)
121
+ out = self.conv3_4(out)
122
+ pool3 = self.relu3_4(out)
123
+ out, pool3_idx = self.maxpool3(pool3)
124
+
125
+ out = self.pad4_1(out)
126
+ out = self.conv4_1(out)
127
+ out = self.relu4_1(out)
128
+
129
+ return out, pool1_idx, pool1.size(), pool2_idx, pool2.size(), pool3_idx, pool3.size()
130
+
131
+ def forward_multiple(self, x):
132
+ out = self.conv0(x)
133
+
134
+ out = self.pad1_1(out)
135
+ out = self.conv1_1(out)
136
+ out = self.relu1_1(out)
137
+
138
+ if self.level < 2: return out
139
+
140
+ out1 = out
141
+
142
+ out = self.pad1_2(out)
143
+ out = self.conv1_2(out)
144
+ pool1 = self.relu1_2(out)
145
+
146
+ out, pool1_idx = self.maxpool1(pool1)
147
+
148
+ out = self.pad2_1(out)
149
+ out = self.conv2_1(out)
150
+ out = self.relu2_1(out)
151
+
152
+ if self.level < 3: return out, out1
153
+
154
+ out2 = out
155
+
156
+ out = self.pad2_2(out)
157
+ out = self.conv2_2(out)
158
+ pool2 = self.relu2_2(out)
159
+
160
+ out, pool2_idx = self.maxpool2(pool2)
161
+
162
+ out = self.pad3_1(out)
163
+ out = self.conv3_1(out)
164
+ out = self.relu3_1(out)
165
+
166
+ if self.level < 4: return out, out2, out1
167
+
168
+ out3 = out
169
+
170
+ out = self.pad3_2(out)
171
+ out = self.conv3_2(out)
172
+ out = self.relu3_2(out)
173
+
174
+ out = self.pad3_3(out)
175
+ out = self.conv3_3(out)
176
+ out = self.relu3_3(out)
177
+
178
+ out = self.pad3_4(out)
179
+ out = self.conv3_4(out)
180
+ pool3 = self.relu3_4(out)
181
+ out, pool3_idx = self.maxpool3(pool3)
182
+
183
+ out = self.pad4_1(out)
184
+ out = self.conv4_1(out)
185
+ out = self.relu4_1(out)
186
+
187
+ return out, out3, out2, out1
188
+
189
+
190
+ class VGGDecoder(nn.Module):
191
+ def __init__(self, level):
192
+ super(VGGDecoder, self).__init__()
193
+ self.level = level
194
+
195
+ if level > 3:
196
+ self.pad4_1 = nn.ReflectionPad2d((1, 1, 1, 1))
197
+ self.conv4_1 = nn.Conv2d(512, 256, 3, 1, 0)
198
+ self.relu4_1 = nn.ReLU(inplace=True)
199
+ # 28 x 28
200
+
201
+ self.unpool3 = nn.MaxUnpool2d(kernel_size=2, stride=2)
202
+ # 56 x 56
203
+
204
+ self.pad3_4 = nn.ReflectionPad2d((1, 1, 1, 1))
205
+ self.conv3_4 = nn.Conv2d(256, 256, 3, 1, 0)
206
+ self.relu3_4 = nn.ReLU(inplace=True)
207
+ # 56 x 56
208
+
209
+ self.pad3_3 = nn.ReflectionPad2d((1, 1, 1, 1))
210
+ self.conv3_3 = nn.Conv2d(256, 256, 3, 1, 0)
211
+ self.relu3_3 = nn.ReLU(inplace=True)
212
+ # 56 x 56
213
+
214
+ self.pad3_2 = nn.ReflectionPad2d((1, 1, 1, 1))
215
+ self.conv3_2 = nn.Conv2d(256, 256, 3, 1, 0)
216
+ self.relu3_2 = nn.ReLU(inplace=True)
217
+ # 56 x 56
218
+
219
+ if level > 2:
220
+ self.pad3_1 = nn.ReflectionPad2d((1, 1, 1, 1))
221
+ self.conv3_1 = nn.Conv2d(256, 128, 3, 1, 0)
222
+ self.relu3_1 = nn.ReLU(inplace=True)
223
+ # 56 x 56
224
+
225
+ self.unpool2 = nn.MaxUnpool2d(kernel_size=2, stride=2)
226
+ # 112 x 112
227
+
228
+ self.pad2_2 = nn.ReflectionPad2d((1, 1, 1, 1))
229
+ self.conv2_2 = nn.Conv2d(128, 128, 3, 1, 0)
230
+ self.relu2_2 = nn.ReLU(inplace=True)
231
+ # 112 x 112
232
+
233
+ if level > 1:
234
+ self.pad2_1 = nn.ReflectionPad2d((1, 1, 1, 1))
235
+ self.conv2_1 = nn.Conv2d(128, 64, 3, 1, 0)
236
+ self.relu2_1 = nn.ReLU(inplace=True)
237
+ # 112 x 112
238
+
239
+ self.unpool1 = nn.MaxUnpool2d(kernel_size=2, stride=2)
240
+ # 224 x 224
241
+
242
+ self.pad1_2 = nn.ReflectionPad2d((1, 1, 1, 1))
243
+ self.conv1_2 = nn.Conv2d(64, 64, 3, 1, 0)
244
+ self.relu1_2 = nn.ReLU(inplace=True)
245
+ # 224 x 224
246
+
247
+ if level > 0:
248
+ self.pad1_1 = nn.ReflectionPad2d((1, 1, 1, 1))
249
+ self.conv1_1 = nn.Conv2d(64, 3, 3, 1, 0)
250
+
251
+ def forward(self, x, pool1_idx=None, pool1_size=None, pool2_idx=None, pool2_size=None, pool3_idx=None,
252
+ pool3_size=None):
253
+ out = x
254
+
255
+ if self.level > 3:
256
+ out = self.pad4_1(out)
257
+ out = self.conv4_1(out)
258
+ out = self.relu4_1(out)
259
+ out = self.unpool3(out, pool3_idx, output_size=pool3_size)
260
+
261
+ out = self.pad3_4(out)
262
+ out = self.conv3_4(out)
263
+ out = self.relu3_4(out)
264
+
265
+ out = self.pad3_3(out)
266
+ out = self.conv3_3(out)
267
+ out = self.relu3_3(out)
268
+
269
+ out = self.pad3_2(out)
270
+ out = self.conv3_2(out)
271
+ out = self.relu3_2(out)
272
+
273
+ if self.level > 2:
274
+ out = self.pad3_1(out)
275
+ out = self.conv3_1(out)
276
+ out = self.relu3_1(out)
277
+ out = self.unpool2(out, pool2_idx, output_size=pool2_size)
278
+
279
+ out = self.pad2_2(out)
280
+ out = self.conv2_2(out)
281
+ out = self.relu2_2(out)
282
+
283
+ if self.level > 1:
284
+ out = self.pad2_1(out)
285
+ out = self.conv2_1(out)
286
+ out = self.relu2_1(out)
287
+ out = self.unpool1(out, pool1_idx, output_size=pool1_size)
288
+
289
+ out = self.pad1_2(out)
290
+ out = self.conv1_2(out)
291
+ out = self.relu1_2(out)
292
+
293
+ if self.level > 0:
294
+ out = self.pad1_1(out)
295
+ out = self.conv1_1(out)
296
+
297
+ return out
models/photo_wct.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:bedc114a83833de79e92b7166b37bc522db71a30bbfa13d0c4f36387789c8af5
3
+ size 33410469
photo_gif.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (C) 2018 NVIDIA Corporation. All rights reserved.
3
+ Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
4
+ """
5
+ from __future__ import division
6
+ from PIL import Image
7
+ from torch import nn
8
+ import numpy as np
9
+ import cv2
10
+ from cv2.ximgproc import guidedFilter
11
+
12
+
13
+ class GIFSmoothing(nn.Module):
14
+ def forward(self, *input):
15
+ pass
16
+
17
+ def __init__(self, r, eps):
18
+ super(GIFSmoothing, self).__init__()
19
+ self.r = r
20
+ self.eps = eps
21
+
22
+ def process(self, initImg, contentImg):
23
+ return self.process_opencv(initImg, contentImg)
24
+
25
+ def process_opencv(self, initImg, contentImg):
26
+ '''
27
+ :param initImg: intermediate output. Either image path or PIL Image
28
+ :param contentImg: content image output. Either path or PIL Image
29
+ :return: stylized output image. PIL Image
30
+ '''
31
+ if type(initImg) == str:
32
+ init_img = cv2.imread(initImg)
33
+ init_img = init_img[2:-2,2:-2,:]
34
+ else:
35
+ init_img = np.array(initImg)[:, :, ::-1].copy()
36
+
37
+ if type(contentImg) == str:
38
+ cont_img = cv2.imread(contentImg)
39
+ else:
40
+ cont_img = np.array(contentImg)[:, :, ::-1].copy()
41
+
42
+ output_img = guidedFilter(guide=cont_img, src=init_img, radius=self.r, eps=self.eps)
43
+ output_img = cv2.cvtColor(output_img, cv2.COLOR_BGR2RGB)
44
+ output_img = Image.fromarray(output_img)
45
+ return output_img
photo_smooth.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (C) 2018 NVIDIA Corporation. All rights reserved.
3
+ Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
4
+ """
5
+ from __future__ import division
6
+ import torch.nn as nn
7
+ import scipy.misc
8
+ import numpy as np
9
+ import scipy.sparse
10
+ import scipy.sparse.linalg
11
+ from numpy.lib.stride_tricks import as_strided
12
+ from PIL import Image
13
+ import cv2
14
+
15
+ class Propagator(nn.Module):
16
+ def __init__(self, beta=0.9999):
17
+ super(Propagator, self).__init__()
18
+ self.beta = beta
19
+
20
+ def process(self, initImg, contentImg):
21
+
22
+ if type(contentImg) == str:
23
+ content = cv2.imread(contentImg)
24
+ content = cv2.cvtColor(np.content, cv2.COLOR_BGR2RGB)
25
+ else:
26
+ content = np.array(contentImg, dtype=np.float64)
27
+
28
+ if type(initImg) == str:
29
+ B = cv2.imread(initImg)
30
+ B = cv2.cvtColor(B, cv2.COLOR_BGR2RGB)
31
+ B /= 255
32
+ else:
33
+ B = np.array(initImg, dtype=np.float64)
34
+ B /= 255
35
+
36
+ h1,w1,k = B.shape
37
+ h = h1 - 4
38
+ w = w1 - 4
39
+ B = B[int((h1-h)/2):int((h1-h)/2+h),int((w1-w)/2):int((w1-w)/2+w),:]
40
+ content = cv2.resize(content, (w, h))
41
+ B = self.__replication_padding(B,2)
42
+ content = self.__replication_padding(content,2)
43
+ content = content.astype(np.float64)/255
44
+ B = np.reshape(B,(h1*w1,k))
45
+ W = self.__compute_laplacian(content)
46
+ W = W.tocsc()
47
+ dd = W.sum(0)
48
+ dd = np.sqrt(np.power(dd,-1))
49
+ dd = dd.A.squeeze()
50
+ D = scipy.sparse.csc_matrix((dd, (np.arange(0,w1*h1), np.arange(0,w1*h1)))) # 0.026
51
+ S = D.dot(W).dot(D)
52
+ A = scipy.sparse.identity(w1*h1) - self.beta*S
53
+ A = A.tocsc()
54
+ solver = scipy.sparse.linalg.factorized(A)
55
+ V = np.zeros((h1*w1,k))
56
+ V[:,0] = solver(B[:,0])
57
+ V[:,1] = solver(B[:,1])
58
+ V[:,2] = solver(B[:,2])
59
+ V = V*(1-self.beta)
60
+ V = V.reshape(h1,w1,k)
61
+ V = V[2:2+h,2:2+w,:]
62
+
63
+ img = Image.fromarray(np.uint8(np.clip(V * 255., 0, 255.)))
64
+ return img
65
+
66
+ # Returns sparse matting laplacian
67
+ # The implementation of the function is heavily borrowed from
68
+ # https://github.com/MarcoForte/closed-form-matting/blob/master/closed_form_matting.py
69
+ # We thank Marco Forte for sharing his code.
70
+ def __compute_laplacian(self, img, eps=10**(-7), win_rad=1):
71
+ win_size = (win_rad*2+1)**2
72
+ h, w, d = img.shape
73
+ c_h, c_w = h - 2*win_rad, w - 2*win_rad
74
+ win_diam = win_rad*2+1
75
+ indsM = np.arange(h*w).reshape((h, w))
76
+ ravelImg = img.reshape(h*w, d)
77
+ win_inds = self.__rolling_block(indsM, block=(win_diam, win_diam))
78
+ win_inds = win_inds.reshape(c_h, c_w, win_size)
79
+ winI = ravelImg[win_inds]
80
+ win_mu = np.mean(winI, axis=2, keepdims=True)
81
+ win_var = np.einsum('...ji,...jk ->...ik', winI, winI)/win_size - np.einsum('...ji,...jk ->...ik', win_mu, win_mu)
82
+ inv = np.linalg.inv(win_var + (eps/win_size)*np.eye(3))
83
+ X = np.einsum('...ij,...jk->...ik', winI - win_mu, inv)
84
+ vals = (1/win_size)*(1 + np.einsum('...ij,...kj->...ik', X, winI - win_mu))
85
+ nz_indsCol = np.tile(win_inds, win_size).ravel()
86
+ nz_indsRow = np.repeat(win_inds, win_size).ravel()
87
+ nz_indsVal = vals.ravel()
88
+ L = scipy.sparse.coo_matrix((nz_indsVal, (nz_indsRow, nz_indsCol)), shape=(h*w, h*w))
89
+ return L
90
+
91
+ def __replication_padding(self, arr,pad):
92
+ h,w,c = arr.shape
93
+ ans = np.zeros((h+pad*2,w+pad*2,c))
94
+ for i in range(c):
95
+ ans[:,:,i] = np.pad(arr[:,:,i],pad_width=(pad,pad),mode='edge')
96
+ return ans
97
+
98
+ def __rolling_block(self, A, block=(3, 3)):
99
+ shape = (A.shape[0] - block[0] + 1, A.shape[1] - block[1] + 1) + block
100
+ strides = (A.strides[0], A.strides[1]) + A.strides
101
+ return as_strided(A, shape=shape, strides=strides)
photo_wct.py ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (C) 2018 NVIDIA Corporation. All rights reserved.
3
+ Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
4
+ """
5
+
6
+ import numpy as np
7
+ from PIL import Image
8
+ import torch
9
+ import torch.nn as nn
10
+ from models import VGGEncoder, VGGDecoder
11
+
12
+
13
+ class PhotoWCT(nn.Module):
14
+ def __init__(self):
15
+ super(PhotoWCT, self).__init__()
16
+ self.e1 = VGGEncoder(1)
17
+ self.d1 = VGGDecoder(1)
18
+ self.e2 = VGGEncoder(2)
19
+ self.d2 = VGGDecoder(2)
20
+ self.e3 = VGGEncoder(3)
21
+ self.d3 = VGGDecoder(3)
22
+ self.e4 = VGGEncoder(4)
23
+ self.d4 = VGGDecoder(4)
24
+
25
+ def transform(self, cont_img, styl_img, cont_seg, styl_seg):
26
+ self.__compute_label_info(cont_seg, styl_seg)
27
+
28
+ sF4, sF3, sF2, sF1 = self.e4.forward_multiple(styl_img)
29
+
30
+ cF4, cpool_idx, cpool1, cpool_idx2, cpool2, cpool_idx3, cpool3 = self.e4(cont_img)
31
+ sF4 = sF4.data.squeeze(0)
32
+ cF4 = cF4.data.squeeze(0)
33
+ # print(cont_seg)
34
+ csF4 = self.__feature_wct(cF4, sF4, cont_seg, styl_seg)
35
+ Im4 = self.d4(csF4, cpool_idx, cpool1, cpool_idx2, cpool2, cpool_idx3, cpool3)
36
+
37
+ cF3, cpool_idx, cpool1, cpool_idx2, cpool2 = self.e3(Im4)
38
+ sF3 = sF3.data.squeeze(0)
39
+ cF3 = cF3.data.squeeze(0)
40
+ csF3 = self.__feature_wct(cF3, sF3, cont_seg, styl_seg)
41
+ Im3 = self.d3(csF3, cpool_idx, cpool1, cpool_idx2, cpool2)
42
+
43
+ cF2, cpool_idx, cpool = self.e2(Im3)
44
+ sF2 = sF2.data.squeeze(0)
45
+ cF2 = cF2.data.squeeze(0)
46
+ csF2 = self.__feature_wct(cF2, sF2, cont_seg, styl_seg)
47
+ Im2 = self.d2(csF2, cpool_idx, cpool)
48
+
49
+ cF1 = self.e1(Im2)
50
+ sF1 = sF1.data.squeeze(0)
51
+ cF1 = cF1.data.squeeze(0)
52
+ csF1 = self.__feature_wct(cF1, sF1, cont_seg, styl_seg)
53
+ Im1 = self.d1(csF1)
54
+ return Im1
55
+
56
+ def __compute_label_info(self, cont_seg, styl_seg):
57
+ if cont_seg.size == False or styl_seg.size == False:
58
+ return
59
+ max_label = np.max(cont_seg) + 1
60
+ self.label_set = np.unique(cont_seg)
61
+ self.label_indicator = np.zeros(max_label)
62
+ for l in self.label_set:
63
+ # if l==0:
64
+ # continue
65
+ is_valid = lambda a, b: a > 10 and b > 10 and a / b < 100 and b / a < 100
66
+ o_cont_mask = np.where(cont_seg.reshape(cont_seg.shape[0] * cont_seg.shape[1]) == l)
67
+ o_styl_mask = np.where(styl_seg.reshape(styl_seg.shape[0] * styl_seg.shape[1]) == l)
68
+ self.label_indicator[l] = is_valid(o_cont_mask[0].size, o_styl_mask[0].size)
69
+
70
+ def __feature_wct(self, cont_feat, styl_feat, cont_seg, styl_seg):
71
+ cont_c, cont_h, cont_w = cont_feat.size(0), cont_feat.size(1), cont_feat.size(2)
72
+ styl_c, styl_h, styl_w = styl_feat.size(0), styl_feat.size(1), styl_feat.size(2)
73
+ cont_feat_view = cont_feat.view(cont_c, -1).clone()
74
+ styl_feat_view = styl_feat.view(styl_c, -1).clone()
75
+
76
+ if cont_seg.size == False or styl_seg.size == False:
77
+ target_feature = self.__wct_core(cont_feat_view, styl_feat_view)
78
+ else:
79
+ target_feature = cont_feat.view(cont_c, -1).clone()
80
+ if len(cont_seg.shape) == 2:
81
+ t_cont_seg = np.asarray(Image.fromarray(cont_seg).resize((cont_w, cont_h), Image.NEAREST))
82
+ else:
83
+ t_cont_seg = np.asarray(Image.fromarray(cont_seg, mode='RGB').resize((cont_w, cont_h), Image.NEAREST))
84
+ if len(styl_seg.shape) == 2:
85
+ t_styl_seg = np.asarray(Image.fromarray(styl_seg).resize((styl_w, styl_h), Image.NEAREST))
86
+ else:
87
+ t_styl_seg = np.asarray(Image.fromarray(styl_seg, mode='RGB').resize((styl_w, styl_h), Image.NEAREST))
88
+
89
+ for l in self.label_set:
90
+ if self.label_indicator[l] == 0:
91
+ continue
92
+ cont_mask = np.where(t_cont_seg.reshape(t_cont_seg.shape[0] * t_cont_seg.shape[1]) == l)
93
+ styl_mask = np.where(t_styl_seg.reshape(t_styl_seg.shape[0] * t_styl_seg.shape[1]) == l)
94
+ if cont_mask[0].size <= 0 or styl_mask[0].size <= 0:
95
+ continue
96
+
97
+ cont_indi = torch.LongTensor(cont_mask[0])
98
+ styl_indi = torch.LongTensor(styl_mask[0])
99
+ if self.is_cuda:
100
+ cont_indi = cont_indi.cuda(0)
101
+ styl_indi = styl_indi.cuda(0)
102
+
103
+ cFFG = torch.index_select(cont_feat_view, 1, cont_indi)
104
+ sFFG = torch.index_select(styl_feat_view, 1, styl_indi)
105
+ # print(len(cont_indi))
106
+ # print(len(styl_indi))
107
+ tmp_target_feature = self.__wct_core(cFFG, sFFG)
108
+ # print(tmp_target_feature.size())
109
+ if torch.__version__ >= "0.4.0":
110
+ # This seems to be a bug in PyTorch 0.4.0 to me.
111
+ new_target_feature = torch.transpose(target_feature, 1, 0)
112
+ new_target_feature.index_copy_(0, cont_indi, \
113
+ torch.transpose(tmp_target_feature,1,0))
114
+ target_feature = torch.transpose(new_target_feature, 1, 0)
115
+ else:
116
+ target_feature.index_copy_(1, cont_indi, tmp_target_feature)
117
+
118
+ target_feature = target_feature.view_as(cont_feat)
119
+ ccsF = target_feature.float().unsqueeze(0)
120
+ return ccsF
121
+
122
+ def __wct_core(self, cont_feat, styl_feat):
123
+ cFSize = cont_feat.size()
124
+ c_mean = torch.mean(cont_feat, 1) # c x (h x w)
125
+ c_mean = c_mean.unsqueeze(1).expand_as(cont_feat)
126
+ cont_feat = cont_feat - c_mean
127
+
128
+ iden = torch.eye(cFSize[0]) # .double()
129
+ if self.is_cuda:
130
+ iden = iden.cuda()
131
+
132
+ contentConv = torch.mm(cont_feat, cont_feat.t()).div(cFSize[1] - 1) + iden
133
+ # del iden
134
+ c_u, c_e, c_v = torch.svd(contentConv, some=False)
135
+ # c_e2, c_v = torch.eig(contentConv, True)
136
+ # c_e = c_e2[:,0]
137
+
138
+ k_c = cFSize[0]
139
+ for i in range(cFSize[0] - 1, -1, -1):
140
+ if c_e[i] >= 0.00001:
141
+ k_c = i + 1
142
+ break
143
+
144
+ sFSize = styl_feat.size()
145
+ s_mean = torch.mean(styl_feat, 1)
146
+ styl_feat = styl_feat - s_mean.unsqueeze(1).expand_as(styl_feat)
147
+ styleConv = torch.mm(styl_feat, styl_feat.t()).div(sFSize[1] - 1)
148
+ s_u, s_e, s_v = torch.svd(styleConv, some=False)
149
+
150
+ k_s = sFSize[0]
151
+ for i in range(sFSize[0] - 1, -1, -1):
152
+ if s_e[i] >= 0.00001:
153
+ k_s = i + 1
154
+ break
155
+
156
+ c_d = (c_e[0:k_c]).pow(-0.5)
157
+ step1 = torch.mm(c_v[:, 0:k_c], torch.diag(c_d))
158
+ step2 = torch.mm(step1, (c_v[:, 0:k_c].t()))
159
+ whiten_cF = torch.mm(step2, cont_feat)
160
+
161
+ s_d = (s_e[0:k_s]).pow(0.5)
162
+ targetFeature = torch.mm(torch.mm(torch.mm(s_v[:, 0:k_s], torch.diag(s_d)), (s_v[:, 0:k_s].t())), whiten_cF)
163
+ targetFeature = targetFeature + s_mean.unsqueeze(1).expand_as(targetFeature)
164
+ return targetFeature
165
+
166
+ @property
167
+ def is_cuda(self):
168
+ return next(self.parameters()).is_cuda
169
+
170
+ def forward(self, *input):
171
+ pass
process_stylization.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (C) 2018 NVIDIA Corporation. All rights reserved.
3
+ Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
4
+ """
5
+ from __future__ import print_function
6
+ import time
7
+ import numpy as np
8
+ from PIL import Image
9
+ from torch.autograd import Variable
10
+ import torchvision.transforms as transforms
11
+ import torchvision.utils as utils
12
+ import torch.nn as nn
13
+ import torch
14
+
15
+ class ReMapping:
16
+ def __init__(self):
17
+ self.remapping = []
18
+
19
+ def process(self, seg):
20
+ new_seg = seg.copy()
21
+ for k, v in self.remapping.items():
22
+ new_seg[seg == k] = v
23
+ return new_seg
24
+
25
+
26
+ class Timer:
27
+ def __init__(self, msg):
28
+ self.msg = msg
29
+ self.start_time = None
30
+
31
+ def __enter__(self):
32
+ self.start_time = time.time()
33
+
34
+ def __exit__(self, exc_type, exc_value, exc_tb):
35
+ print(self.msg % (time.time() - self.start_time))
36
+
37
+
38
+ def memory_limit_image_resize(cont_img):
39
+ # prevent too small or too big images
40
+ MINSIZE=256
41
+ MAXSIZE=960
42
+ orig_width = cont_img.width
43
+ orig_height = cont_img.height
44
+ if max(cont_img.width,cont_img.height) < MINSIZE:
45
+ if cont_img.width > cont_img.height:
46
+ cont_img.thumbnail((int(cont_img.width*1.0/cont_img.height*MINSIZE), MINSIZE), Image.BICUBIC)
47
+ else:
48
+ cont_img.thumbnail((MINSIZE, int(cont_img.height*1.0/cont_img.width*MINSIZE)), Image.BICUBIC)
49
+ if min(cont_img.width,cont_img.height) > MAXSIZE:
50
+ if cont_img.width > cont_img.height:
51
+ cont_img.thumbnail((MAXSIZE, int(cont_img.height*1.0/cont_img.width*MAXSIZE)), Image.BICUBIC)
52
+ else:
53
+ cont_img.thumbnail(((int(cont_img.width*1.0/cont_img.height*MAXSIZE), MAXSIZE)), Image.BICUBIC)
54
+ print("Resize image: (%d,%d)->(%d,%d)" % (orig_width, orig_height, cont_img.width, cont_img.height))
55
+ return cont_img.width, cont_img.height
56
+
57
+
58
+ def stylization(stylization_module, smoothing_module, content_image_path, style_image_path, content_seg_path, style_seg_path, output_image_path,
59
+ cuda, save_intermediate, no_post, cont_seg_remapping=None, styl_seg_remapping=None):
60
+ # Load image
61
+ with torch.no_grad():
62
+ cont_img = Image.open(content_image_path).convert('RGB')
63
+ styl_img = Image.open(style_image_path).convert('RGB')
64
+
65
+ new_cw, new_ch = memory_limit_image_resize(cont_img)
66
+ new_sw, new_sh = memory_limit_image_resize(styl_img)
67
+ cont_pilimg = cont_img.copy()
68
+ cw = cont_pilimg.width
69
+ ch = cont_pilimg.height
70
+ try:
71
+ cont_seg = Image.open(content_seg_path)
72
+ styl_seg = Image.open(style_seg_path)
73
+ cont_seg.resize((new_cw,new_ch),Image.NEAREST)
74
+ styl_seg.resize((new_sw,new_sh),Image.NEAREST)
75
+
76
+ except:
77
+ cont_seg = []
78
+ styl_seg = []
79
+
80
+ cont_img = transforms.ToTensor()(cont_img).unsqueeze(0)
81
+ styl_img = transforms.ToTensor()(styl_img).unsqueeze(0)
82
+
83
+ if cuda:
84
+ cont_img = cont_img.cuda(0)
85
+ styl_img = styl_img.cuda(0)
86
+ stylization_module.cuda(0)
87
+
88
+ # cont_img = Variable(cont_img, volatile=True)
89
+ # styl_img = Variable(styl_img, volatile=True)
90
+
91
+ cont_seg = np.asarray(cont_seg)
92
+ styl_seg = np.asarray(styl_seg)
93
+ if cont_seg_remapping is not None:
94
+ cont_seg = cont_seg_remapping.process(cont_seg)
95
+ if styl_seg_remapping is not None:
96
+ styl_seg = styl_seg_remapping.process(styl_seg)
97
+
98
+ if save_intermediate:
99
+ with Timer("Elapsed time in stylization: %f"):
100
+ stylized_img = stylization_module.transform(cont_img, styl_img, cont_seg, styl_seg)
101
+ if ch != new_ch or cw != new_cw:
102
+ print("De-resize image: (%d,%d)->(%d,%d)" %(new_cw,new_ch,cw,ch))
103
+ stylized_img = nn.functional.upsample(stylized_img, size=(ch,cw), mode='bilinear')
104
+ utils.save_image(stylized_img.data.cpu().float(), output_image_path, nrow=1, padding=0)
105
+
106
+ with Timer("Elapsed time in propagation: %f"):
107
+ out_img = smoothing_module.process(output_image_path, content_image_path)
108
+ out_img.save(output_image_path)
109
+
110
+ if not cuda:
111
+ print("NotImplemented: The CPU version of smooth filter has not been implemented currently.")
112
+ return
113
+
114
+ if no_post is False:
115
+ with Timer("Elapsed time in post processing: %f"):
116
+ from smooth_filter import smooth_filter
117
+ out_img = smooth_filter(output_image_path, content_image_path, f_radius=15, f_edge=1e-1)
118
+ out_img.save(output_image_path)
119
+ else:
120
+ with Timer("Elapsed time in stylization: %f"):
121
+ stylized_img = stylization_module.transform(cont_img, styl_img, cont_seg, styl_seg)
122
+ if ch != new_ch or cw != new_cw:
123
+ print("De-resize image: (%d,%d)->(%d,%d)" %(new_cw,new_ch,cw,ch))
124
+ stylized_img = nn.functional.upsample(stylized_img, size=(ch,cw), mode='bilinear')
125
+ grid = utils.make_grid(stylized_img.data, nrow=1, padding=0)
126
+ ndarr = grid.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()
127
+ out_img = Image.fromarray(ndarr)
128
+
129
+ with Timer("Elapsed time in propagation: %f"):
130
+ out_img = smoothing_module.process(out_img, cont_pilimg)
131
+
132
+ if no_post is False:
133
+ with Timer("Elapsed time in post processing: %f"):
134
+ from smooth_filter import smooth_filter
135
+ out_img = smooth_filter(out_img, cont_pilimg, f_radius=15, f_edge=1e-1)
136
+ out_img.save(output_image_path)
137
+
138
+ def stylization_gradio(
139
+ stylization_module,
140
+ smoothing_module,
141
+ content_image,
142
+ style_image,
143
+ cuda,
144
+ post_processing,
145
+ cont_seg_remapping=None,
146
+ styl_seg_remapping=None):
147
+
148
+ # Load image
149
+ with torch.no_grad():
150
+ cont_img = Image.fromarray(content_image).convert('RGB')
151
+ styl_img = Image.fromarray(style_image).convert('RGB')
152
+
153
+ new_cw, new_ch = memory_limit_image_resize(cont_img)
154
+ new_sw, new_sh = memory_limit_image_resize(styl_img)
155
+ cont_pilimg = cont_img.copy()
156
+ cw = cont_pilimg.width
157
+ ch = cont_pilimg.height
158
+
159
+ cont_seg = []
160
+ styl_seg = []
161
+
162
+ cont_img = transforms.ToTensor()(cont_img).unsqueeze(0)
163
+ styl_img = transforms.ToTensor()(styl_img).unsqueeze(0)
164
+
165
+ if cuda:
166
+ cont_img = cont_img.cuda(0)
167
+ styl_img = styl_img.cuda(0)
168
+ stylization_module.cuda(0)
169
+
170
+ cont_seg = np.asarray(cont_seg)
171
+ styl_seg = np.asarray(styl_seg)
172
+ if cont_seg_remapping is not None:
173
+ cont_seg = cont_seg_remapping.process(cont_seg)
174
+ if styl_seg_remapping is not None:
175
+ styl_seg = styl_seg_remapping.process(styl_seg)
176
+
177
+ with Timer("Elapsed time in stylization: %f"):
178
+ stylized_img = stylization_module.transform(cont_img, styl_img, cont_seg, styl_seg)
179
+ if ch != new_ch or cw != new_cw:
180
+ print("De-resize image: (%d,%d)->(%d,%d)" %(new_cw,new_ch,cw,ch))
181
+ stylized_img = nn.functional.upsample(stylized_img, size=(ch,cw), mode='bilinear')
182
+ grid = utils.make_grid(stylized_img.data, nrow=1, padding=0)
183
+ ndarr = grid.mul(255).clamp(0, 255).byte().permute(1, 2, 0).cpu().numpy()
184
+ out_img = Image.fromarray(ndarr)
185
+
186
+ with Timer("Elapsed time in propagation: %f"):
187
+ out_img = smoothing_module.process(out_img, cont_pilimg)
188
+
189
+ if post_processing:
190
+ with Timer("Elapsed time in post processing: %f"):
191
+ from smooth_filter import smooth_filter
192
+ out_img = smooth_filter(out_img, cont_pilimg, f_radius=15, f_edge=1e-1)
193
+
194
+ return out_img
195
+
requirements.txt ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ aiohttp==3.8.3
2
+ aiosignal==1.2.0
3
+ anyio==3.6.1
4
+ async-timeout==4.0.2
5
+ attrs==22.1.0
6
+ bcrypt==4.0.1
7
+ certifi==2022.9.24
8
+ cffi==1.15.1
9
+ charset-normalizer==2.1.1
10
+ click==8.1.3
11
+ contourpy==1.0.5
12
+ cryptography==38.0.1
13
+ cycler==0.11.0
14
+ fastapi==0.85.0
15
+ fastrlock==0.8
16
+ ffmpy==0.3.0
17
+ fonttools==4.37.4
18
+ frozenlist==1.3.1
19
+ fsspec==2022.8.2
20
+ gradio==3.4.1
21
+ h11==0.12.0
22
+ httpcore==0.15.0
23
+ httpx==0.23.0
24
+ idna==3.4
25
+ imageio==2.22.1
26
+ Jinja2==3.1.2
27
+ kiwisolver==1.4.4
28
+ linkify-it-py==1.0.3
29
+ markdown-it-py==2.1.0
30
+ MarkupSafe==2.1.1
31
+ matplotlib==3.6.1
32
+ mdit-py-plugins==0.3.1
33
+ mdurl==0.1.2
34
+ multidict==6.0.2
35
+ networkx==2.8.7
36
+ numpy==1.23.3
37
+ opencv-contrib-python==4.6.0.66
38
+ opencv-python==4.6.0.66
39
+ orjson==3.8.0
40
+ packaging==21.3
41
+ pandas==1.5.0
42
+ paramiko==2.11.0
43
+ Pillow==9.2.0
44
+ pycparser==2.21
45
+ pycryptodome==3.15.0
46
+ pydantic==1.10.2
47
+ pydub==0.25.1
48
+ PyNaCl==1.5.0
49
+ pyparsing==3.0.9
50
+ python-dateutil==2.8.2
51
+ python-multipart==0.0.5
52
+ pytz==2022.4
53
+ PyWavelets==1.4.1
54
+ PyYAML==6.0
55
+ requests==2.28.1
56
+ rfc3986==1.5.0
57
+ scikit-image==0.19.3
58
+ scipy==1.9.2
59
+ six==1.16.0
60
+ sniffio==1.3.0
61
+ starlette==0.20.4
62
+ tifffile==2022.10.10
63
+ torch==1.12.1
64
+ torchvision==0.13.1
65
+ typing_extensions==4.4.0
66
+ uc-micro-py==1.0.1
67
+ urllib3==1.26.12
68
+ uvicorn==0.18.3
69
+ websockets==10.3
70
+ yarl==1.8.1
71
+ # cupy==11.2.0
72
+ # pynvrtc==9.2
smooth_filter.py ADDED
@@ -0,0 +1,405 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Copyright (C) 2018 NVIDIA Corporation. All rights reserved.
3
+ Licensed under the CC BY-NC-SA 4.0 license (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode).
4
+ """
5
+ src = '''
6
+ #include "/usr/local/cuda/include/math_functions.h"
7
+ #define TB 256
8
+ #define EPS 1e-7
9
+
10
+ __device__ bool InverseMat4x4(double m_in[4][4], double inv_out[4][4]) {
11
+ double m[16], inv[16];
12
+ for (int i = 0; i < 4; i++) {
13
+ for (int j = 0; j < 4; j++) {
14
+ m[i * 4 + j] = m_in[i][j];
15
+ }
16
+ }
17
+
18
+ inv[0] = m[5] * m[10] * m[15] -
19
+ m[5] * m[11] * m[14] -
20
+ m[9] * m[6] * m[15] +
21
+ m[9] * m[7] * m[14] +
22
+ m[13] * m[6] * m[11] -
23
+ m[13] * m[7] * m[10];
24
+
25
+ inv[4] = -m[4] * m[10] * m[15] +
26
+ m[4] * m[11] * m[14] +
27
+ m[8] * m[6] * m[15] -
28
+ m[8] * m[7] * m[14] -
29
+ m[12] * m[6] * m[11] +
30
+ m[12] * m[7] * m[10];
31
+
32
+ inv[8] = m[4] * m[9] * m[15] -
33
+ m[4] * m[11] * m[13] -
34
+ m[8] * m[5] * m[15] +
35
+ m[8] * m[7] * m[13] +
36
+ m[12] * m[5] * m[11] -
37
+ m[12] * m[7] * m[9];
38
+
39
+ inv[12] = -m[4] * m[9] * m[14] +
40
+ m[4] * m[10] * m[13] +
41
+ m[8] * m[5] * m[14] -
42
+ m[8] * m[6] * m[13] -
43
+ m[12] * m[5] * m[10] +
44
+ m[12] * m[6] * m[9];
45
+
46
+ inv[1] = -m[1] * m[10] * m[15] +
47
+ m[1] * m[11] * m[14] +
48
+ m[9] * m[2] * m[15] -
49
+ m[9] * m[3] * m[14] -
50
+ m[13] * m[2] * m[11] +
51
+ m[13] * m[3] * m[10];
52
+
53
+ inv[5] = m[0] * m[10] * m[15] -
54
+ m[0] * m[11] * m[14] -
55
+ m[8] * m[2] * m[15] +
56
+ m[8] * m[3] * m[14] +
57
+ m[12] * m[2] * m[11] -
58
+ m[12] * m[3] * m[10];
59
+
60
+ inv[9] = -m[0] * m[9] * m[15] +
61
+ m[0] * m[11] * m[13] +
62
+ m[8] * m[1] * m[15] -
63
+ m[8] * m[3] * m[13] -
64
+ m[12] * m[1] * m[11] +
65
+ m[12] * m[3] * m[9];
66
+
67
+ inv[13] = m[0] * m[9] * m[14] -
68
+ m[0] * m[10] * m[13] -
69
+ m[8] * m[1] * m[14] +
70
+ m[8] * m[2] * m[13] +
71
+ m[12] * m[1] * m[10] -
72
+ m[12] * m[2] * m[9];
73
+
74
+ inv[2] = m[1] * m[6] * m[15] -
75
+ m[1] * m[7] * m[14] -
76
+ m[5] * m[2] * m[15] +
77
+ m[5] * m[3] * m[14] +
78
+ m[13] * m[2] * m[7] -
79
+ m[13] * m[3] * m[6];
80
+
81
+ inv[6] = -m[0] * m[6] * m[15] +
82
+ m[0] * m[7] * m[14] +
83
+ m[4] * m[2] * m[15] -
84
+ m[4] * m[3] * m[14] -
85
+ m[12] * m[2] * m[7] +
86
+ m[12] * m[3] * m[6];
87
+
88
+ inv[10] = m[0] * m[5] * m[15] -
89
+ m[0] * m[7] * m[13] -
90
+ m[4] * m[1] * m[15] +
91
+ m[4] * m[3] * m[13] +
92
+ m[12] * m[1] * m[7] -
93
+ m[12] * m[3] * m[5];
94
+
95
+ inv[14] = -m[0] * m[5] * m[14] +
96
+ m[0] * m[6] * m[13] +
97
+ m[4] * m[1] * m[14] -
98
+ m[4] * m[2] * m[13] -
99
+ m[12] * m[1] * m[6] +
100
+ m[12] * m[2] * m[5];
101
+
102
+ inv[3] = -m[1] * m[6] * m[11] +
103
+ m[1] * m[7] * m[10] +
104
+ m[5] * m[2] * m[11] -
105
+ m[5] * m[3] * m[10] -
106
+ m[9] * m[2] * m[7] +
107
+ m[9] * m[3] * m[6];
108
+
109
+ inv[7] = m[0] * m[6] * m[11] -
110
+ m[0] * m[7] * m[10] -
111
+ m[4] * m[2] * m[11] +
112
+ m[4] * m[3] * m[10] +
113
+ m[8] * m[2] * m[7] -
114
+ m[8] * m[3] * m[6];
115
+
116
+ inv[11] = -m[0] * m[5] * m[11] +
117
+ m[0] * m[7] * m[9] +
118
+ m[4] * m[1] * m[11] -
119
+ m[4] * m[3] * m[9] -
120
+ m[8] * m[1] * m[7] +
121
+ m[8] * m[3] * m[5];
122
+
123
+ inv[15] = m[0] * m[5] * m[10] -
124
+ m[0] * m[6] * m[9] -
125
+ m[4] * m[1] * m[10] +
126
+ m[4] * m[2] * m[9] +
127
+ m[8] * m[1] * m[6] -
128
+ m[8] * m[2] * m[5];
129
+
130
+ double det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
131
+
132
+ if (abs(det) < 1e-9) {
133
+ return false;
134
+ }
135
+
136
+
137
+ det = 1.0 / det;
138
+
139
+ for (int i = 0; i < 4; i++) {
140
+ for (int j = 0; j < 4; j++) {
141
+ inv_out[i][j] = inv[i * 4 + j] * det;
142
+ }
143
+ }
144
+
145
+ return true;
146
+ }
147
+
148
+ extern "C"
149
+ __global__ void best_local_affine_kernel(
150
+ float *output, float *input, float *affine_model,
151
+ int h, int w, float epsilon, int kernel_radius
152
+ )
153
+ {
154
+ int size = h * w;
155
+ int id = blockIdx.x * blockDim.x + threadIdx.x;
156
+
157
+ if (id < size) {
158
+ int x = id % w, y = id / w;
159
+
160
+ double Mt_M[4][4] = {}; // 4x4
161
+ double invMt_M[4][4] = {};
162
+ double Mt_S[3][4] = {}; // RGB -> 1x4
163
+ double A[3][4] = {};
164
+ for (int i = 0; i < 4; i++)
165
+ for (int j = 0; j < 4; j++) {
166
+ Mt_M[i][j] = 0, invMt_M[i][j] = 0;
167
+ if (i != 3) {
168
+ Mt_S[i][j] = 0, A[i][j] = 0;
169
+ if (i == j)
170
+ Mt_M[i][j] = 1e-3;
171
+ }
172
+ }
173
+
174
+ for (int dy = -kernel_radius; dy <= kernel_radius; dy++) {
175
+ for (int dx = -kernel_radius; dx <= kernel_radius; dx++) {
176
+
177
+ int xx = x + dx, yy = y + dy;
178
+ int id2 = yy * w + xx;
179
+
180
+ if (0 <= xx && xx < w && 0 <= yy && yy < h) {
181
+
182
+ Mt_M[0][0] += input[id2 + 2*size] * input[id2 + 2*size];
183
+ Mt_M[0][1] += input[id2 + 2*size] * input[id2 + size];
184
+ Mt_M[0][2] += input[id2 + 2*size] * input[id2];
185
+ Mt_M[0][3] += input[id2 + 2*size];
186
+
187
+ Mt_M[1][0] += input[id2 + size] * input[id2 + 2*size];
188
+ Mt_M[1][1] += input[id2 + size] * input[id2 + size];
189
+ Mt_M[1][2] += input[id2 + size] * input[id2];
190
+ Mt_M[1][3] += input[id2 + size];
191
+
192
+ Mt_M[2][0] += input[id2] * input[id2 + 2*size];
193
+ Mt_M[2][1] += input[id2] * input[id2 + size];
194
+ Mt_M[2][2] += input[id2] * input[id2];
195
+ Mt_M[2][3] += input[id2];
196
+
197
+ Mt_M[3][0] += input[id2 + 2*size];
198
+ Mt_M[3][1] += input[id2 + size];
199
+ Mt_M[3][2] += input[id2];
200
+ Mt_M[3][3] += 1;
201
+
202
+ Mt_S[0][0] += input[id2 + 2*size] * output[id2 + 2*size];
203
+ Mt_S[0][1] += input[id2 + size] * output[id2 + 2*size];
204
+ Mt_S[0][2] += input[id2] * output[id2 + 2*size];
205
+ Mt_S[0][3] += output[id2 + 2*size];
206
+
207
+ Mt_S[1][0] += input[id2 + 2*size] * output[id2 + size];
208
+ Mt_S[1][1] += input[id2 + size] * output[id2 + size];
209
+ Mt_S[1][2] += input[id2] * output[id2 + size];
210
+ Mt_S[1][3] += output[id2 + size];
211
+
212
+ Mt_S[2][0] += input[id2 + 2*size] * output[id2];
213
+ Mt_S[2][1] += input[id2 + size] * output[id2];
214
+ Mt_S[2][2] += input[id2] * output[id2];
215
+ Mt_S[2][3] += output[id2];
216
+ }
217
+ }
218
+ }
219
+
220
+ bool success = InverseMat4x4(Mt_M, invMt_M);
221
+
222
+ for (int i = 0; i < 3; i++) {
223
+ for (int j = 0; j < 4; j++) {
224
+ for (int k = 0; k < 4; k++) {
225
+ A[i][j] += invMt_M[j][k] * Mt_S[i][k];
226
+ }
227
+ }
228
+ }
229
+
230
+ for (int i = 0; i < 3; i++) {
231
+ for (int j = 0; j < 4; j++) {
232
+ int affine_id = i * 4 + j;
233
+ affine_model[12 * id + affine_id] = A[i][j];
234
+ }
235
+ }
236
+ }
237
+ return ;
238
+ }
239
+
240
+ extern "C"
241
+ __global__ void bilateral_smooth_kernel(
242
+ float *affine_model, float *filtered_affine_model, float *guide,
243
+ int h, int w, int kernel_radius, float sigma1, float sigma2
244
+ )
245
+ {
246
+ int id = blockIdx.x * blockDim.x + threadIdx.x;
247
+ int size = h * w;
248
+ if (id < size) {
249
+ int x = id % w;
250
+ int y = id / w;
251
+
252
+ double sum_affine[12] = {};
253
+ double sum_weight = 0;
254
+ for (int dx = -kernel_radius; dx <= kernel_radius; dx++) {
255
+ for (int dy = -kernel_radius; dy <= kernel_radius; dy++) {
256
+ int yy = y + dy, xx = x + dx;
257
+ int id2 = yy * w + xx;
258
+ if (0 <= xx && xx < w && 0 <= yy && yy < h) {
259
+ float color_diff1 = guide[yy*w + xx] - guide[y*w + x];
260
+ float color_diff2 = guide[yy*w + xx + size] - guide[y*w + x + size];
261
+ float color_diff3 = guide[yy*w + xx + 2*size] - guide[y*w + x + 2*size];
262
+ float color_diff_sqr =
263
+ (color_diff1*color_diff1 + color_diff2*color_diff2 + color_diff3*color_diff3) / 3;
264
+
265
+ float v1 = exp(-(dx * dx + dy * dy) / (2 * sigma1 * sigma1));
266
+ float v2 = exp(-(color_diff_sqr) / (2 * sigma2 * sigma2));
267
+ float weight = v1 * v2;
268
+
269
+ for (int i = 0; i < 3; i++) {
270
+ for (int j = 0; j < 4; j++) {
271
+ int affine_id = i * 4 + j;
272
+ sum_affine[affine_id] += weight * affine_model[id2*12 + affine_id];
273
+ }
274
+ }
275
+ sum_weight += weight;
276
+ }
277
+ }
278
+ }
279
+
280
+ for (int i = 0; i < 3; i++) {
281
+ for (int j = 0; j < 4; j++) {
282
+ int affine_id = i * 4 + j;
283
+ filtered_affine_model[id*12 + affine_id] = sum_affine[affine_id] / sum_weight;
284
+ }
285
+ }
286
+ }
287
+ return ;
288
+ }
289
+
290
+
291
+ extern "C"
292
+ __global__ void reconstruction_best_kernel(
293
+ float *input, float *filtered_affine_model, float *filtered_best_output,
294
+ int h, int w
295
+ )
296
+ {
297
+ int id = blockIdx.x * blockDim.x + threadIdx.x;
298
+ int size = h * w;
299
+ if (id < size) {
300
+ double out1 =
301
+ input[id + 2*size] * filtered_affine_model[id*12 + 0] + // A[0][0] +
302
+ input[id + size] * filtered_affine_model[id*12 + 1] + // A[0][1] +
303
+ input[id] * filtered_affine_model[id*12 + 2] + // A[0][2] +
304
+ filtered_affine_model[id*12 + 3]; //A[0][3];
305
+ double out2 =
306
+ input[id + 2*size] * filtered_affine_model[id*12 + 4] + //A[1][0] +
307
+ input[id + size] * filtered_affine_model[id*12 + 5] + //A[1][1] +
308
+ input[id] * filtered_affine_model[id*12 + 6] + //A[1][2] +
309
+ filtered_affine_model[id*12 + 7]; //A[1][3];
310
+ double out3 =
311
+ input[id + 2*size] * filtered_affine_model[id*12 + 8] + //A[2][0] +
312
+ input[id + size] * filtered_affine_model[id*12 + 9] + //A[2][1] +
313
+ input[id] * filtered_affine_model[id*12 + 10] + //A[2][2] +
314
+ filtered_affine_model[id*12 + 11]; // A[2][3];
315
+
316
+ filtered_best_output[id] = out1;
317
+ filtered_best_output[id + size] = out2;
318
+ filtered_best_output[id + 2*size] = out3;
319
+ }
320
+ return ;
321
+ }
322
+ '''
323
+
324
+ import torch
325
+ import numpy as np
326
+ from PIL import Image
327
+ from cupy.cuda import function
328
+ from pynvrtc.compiler import Program
329
+ from collections import namedtuple
330
+
331
+
332
+ def smooth_local_affine(output_cpu, input_cpu, epsilon, patch, h, w, f_r, f_e):
333
+ # program = Program(src.encode('utf-8'), 'best_local_affine_kernel.cu'.encode('utf-8'))
334
+ # ptx = program.compile(['-I/usr/local/cuda/include'.encode('utf-8')])
335
+ program = Program(src, 'best_local_affine_kernel.cu')
336
+ ptx = program.compile(['-I/usr/local/cuda/include'])
337
+ m = function.Module()
338
+ m.load(bytes(ptx.encode()))
339
+
340
+ _reconstruction_best_kernel = m.get_function('reconstruction_best_kernel')
341
+ _bilateral_smooth_kernel = m.get_function('bilateral_smooth_kernel')
342
+ _best_local_affine_kernel = m.get_function('best_local_affine_kernel')
343
+ Stream = namedtuple('Stream', ['ptr'])
344
+ s = Stream(ptr=torch.cuda.current_stream().cuda_stream)
345
+
346
+ filter_radius = f_r
347
+ sigma1 = filter_radius / 3
348
+ sigma2 = f_e
349
+ radius = (patch - 1) / 2
350
+
351
+ filtered_best_output = torch.zeros(np.shape(input_cpu)).cuda()
352
+ affine_model = torch.zeros((h * w, 12)).cuda()
353
+ filtered_affine_model =torch.zeros((h * w, 12)).cuda()
354
+
355
+ input_ = torch.from_numpy(input_cpu).cuda()
356
+ output_ = torch.from_numpy(output_cpu).cuda()
357
+ _best_local_affine_kernel(
358
+ grid=(int((h * w) / 256 + 1), 1),
359
+ block=(256, 1, 1),
360
+ args=[output_.data_ptr(), input_.data_ptr(), affine_model.data_ptr(),
361
+ np.int32(h), np.int32(w), np.float32(epsilon), np.int32(radius)], stream=s
362
+ )
363
+
364
+ _bilateral_smooth_kernel(
365
+ grid=(int((h * w) / 256 + 1), 1),
366
+ block=(256, 1, 1),
367
+ args=[affine_model.data_ptr(), filtered_affine_model.data_ptr(), input_.data_ptr(), np.int32(h), np.int32(w), np.int32(f_r), np.float32(sigma1), np.float32(sigma2)], stream=s
368
+ )
369
+
370
+ _reconstruction_best_kernel(
371
+ grid=(int((h * w) / 256 + 1), 1),
372
+ block=(256, 1, 1),
373
+ args=[input_.data_ptr(), filtered_affine_model.data_ptr(), filtered_best_output.data_ptr(),
374
+ np.int32(h), np.int32(w)], stream=s
375
+ )
376
+ numpy_filtered_best_output = filtered_best_output.cpu().numpy()
377
+ return numpy_filtered_best_output
378
+
379
+
380
+ def smooth_filter(initImg, contentImg, f_radius=15,f_edge=1e-1):
381
+ '''
382
+ :param initImg: intermediate output. Either image path or PIL Image
383
+ :param contentImg: content image output. Either path or PIL Image
384
+ :return: stylized output image. PIL Image
385
+ '''
386
+ if type(initImg) == str:
387
+ initImg = Image.open(initImg).convert("RGB")
388
+ best_image_bgr = np.array(initImg, dtype=np.float32)
389
+ bW, bH, bC = best_image_bgr.shape
390
+ best_image_bgr = best_image_bgr[:, :, ::-1]
391
+ best_image_bgr = best_image_bgr.transpose((2, 0, 1))
392
+
393
+ if type(contentImg) == str:
394
+ contentImg = Image.open(contentImg).convert("RGB")
395
+ content_input = contentImg.resize((bH,bW))
396
+ content_input = np.array(content_input, dtype=np.float32)
397
+ content_input = content_input[:, :, ::-1]
398
+ content_input = content_input.transpose((2, 0, 1))
399
+ input_ = np.ascontiguousarray(content_input, dtype=np.float32) / 255.
400
+ _, H, W = np.shape(input_)
401
+ output_ = np.ascontiguousarray(best_image_bgr, dtype=np.float32) / 255.
402
+ best_ = smooth_local_affine(output_, input_, 1e-7, 3, H, W, f_radius, f_edge)
403
+ best_ = best_.transpose(1, 2, 0)
404
+ result = Image.fromarray(np.uint8(np.clip(best_ * 255., 0, 255.)))
405
+ return result