Upload 18 files
Browse files- .DS_Store +0 -0
- .amlignore +6 -0
- .amlignore.amltmp +6 -0
- .gitattributes +45 -38
- .gitignore +31 -0
- LICENSE +107 -0
- README.md +70 -3
- app.py +353 -0
- app.py.amltmp +353 -0
- app_api.py +111 -0
- app_api.py.amltmp +111 -0
- eval.py +163 -0
- index.html +339 -0
- inference.py +327 -0
- preprocess_agnostic_mask.py +65 -0
- requirements.txt +91 -0
- simplified.py +42 -0
- utils.py +508 -0
.DS_Store
ADDED
Binary file (10.2 kB). View file
|
|
.amlignore
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## This file was auto generated by the Azure Machine Learning Studio. Please do not remove.
|
2 |
+
## Read more about the .amlignore file here: https://docs.microsoft.com/azure/machine-learning/how-to-save-write-experiment-files#storage-limits-of-experiment-snapshots
|
3 |
+
|
4 |
+
.ipynb_aml_checkpoints/
|
5 |
+
*.amltmp
|
6 |
+
*.amltemp
|
.amlignore.amltmp
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
## This file was auto generated by the Azure Machine Learning Studio. Please do not remove.
|
2 |
+
## Read more about the .amlignore file here: https://docs.microsoft.com/azure/machine-learning/how-to-save-write-experiment-files#storage-limits-of-experiment-snapshots
|
3 |
+
|
4 |
+
.ipynb_aml_checkpoints/
|
5 |
+
*.amltmp
|
6 |
+
*.amltemp
|
.gitattributes
CHANGED
@@ -1,38 +1,45 @@
|
|
1 |
-
*.
|
2 |
-
*.
|
3 |
-
*.
|
4 |
-
*.
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
*.
|
12 |
-
*.
|
13 |
-
*.
|
14 |
-
*.
|
15 |
-
*.
|
16 |
-
*.
|
17 |
-
*.
|
18 |
-
*.
|
19 |
-
*.
|
20 |
-
*.
|
21 |
-
*.
|
22 |
-
*.
|
23 |
-
*.
|
24 |
-
*.
|
25 |
-
*.
|
26 |
-
|
27 |
-
*.
|
28 |
-
|
29 |
-
|
30 |
-
*.
|
31 |
-
*.
|
32 |
-
*.
|
33 |
-
*.
|
34 |
-
*.
|
35 |
-
|
36 |
-
|
37 |
-
|
38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
*.py eol=lf
|
2 |
+
*.js eol=lf
|
3 |
+
*.jsx eol=lf
|
4 |
+
*.json eol=lf
|
5 |
+
# .gitattributes snippet to force users to use same line endings for project.
|
6 |
+
# Handle line endings automatically for files detected as text
|
7 |
+
# and leave all files detected as binary untouched.
|
8 |
+
* text=auto
|
9 |
+
# The above will handle all files NOT found below
|
10 |
+
# These files are text and should be normalized (Convert crlf => lf)
|
11 |
+
*.php text
|
12 |
+
*.css text
|
13 |
+
*.js text
|
14 |
+
*.json text
|
15 |
+
*.htm text
|
16 |
+
*.html text
|
17 |
+
*.xml text
|
18 |
+
*.txt text
|
19 |
+
*.ini text
|
20 |
+
*.inc text
|
21 |
+
*.pl text
|
22 |
+
*.rb text
|
23 |
+
*.py text
|
24 |
+
*.scm text
|
25 |
+
*.sql text
|
26 |
+
.htaccess text
|
27 |
+
*.sh text
|
28 |
+
# These files are binary and should be left untouched
|
29 |
+
# (binary is a macro for -text -diff)
|
30 |
+
*.png binary
|
31 |
+
*.jpg binary
|
32 |
+
*.jpeg binary
|
33 |
+
*.gif binary
|
34 |
+
*.ico binary
|
35 |
+
*.mov binary
|
36 |
+
*.mp4 binary
|
37 |
+
*.mp3 binary
|
38 |
+
*.flv binary
|
39 |
+
*.fla binary
|
40 |
+
*.swf binary
|
41 |
+
*.gz binary
|
42 |
+
*.zip binary
|
43 |
+
*.7z binary
|
44 |
+
*.ttf binary
|
45 |
+
*.pyc binary
|
.gitignore
ADDED
@@ -0,0 +1,31 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
.env
|
2 |
+
.vscode
|
3 |
+
.idea
|
4 |
+
.venv
|
5 |
+
venv
|
6 |
+
vm
|
7 |
+
*.pyc
|
8 |
+
*.egg-info
|
9 |
+
__pycache__
|
10 |
+
.ebextensions
|
11 |
+
.spyproject
|
12 |
+
node_modules
|
13 |
+
bak
|
14 |
+
baks
|
15 |
+
logs
|
16 |
+
myTestes
|
17 |
+
myHelpers
|
18 |
+
conf
|
19 |
+
.requirements.txt.bak
|
20 |
+
USE.INFO
|
21 |
+
templates/src
|
22 |
+
dabolinux-clients-demo-32103b022bf6.json
|
23 |
+
media/
|
24 |
+
MANIFEST
|
25 |
+
build
|
26 |
+
dist
|
27 |
+
docs/_build
|
28 |
+
docs/_static
|
29 |
+
npm-debug.log
|
30 |
+
setup.cfg
|
31 |
+
pyproject.toml
|
LICENSE
ADDED
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
|
2 |
+
|
3 |
+
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.
|
4 |
+
|
5 |
+
Using Creative Commons Public Licenses
|
6 |
+
|
7 |
+
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.
|
8 |
+
|
9 |
+
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 : wiki.creativecommons.org/Considerations_for_licensors
|
10 |
+
|
11 |
+
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 : wiki.creativecommons.org/Considerations_for_licensees
|
12 |
+
|
13 |
+
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License
|
14 |
+
|
15 |
+
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.
|
16 |
+
|
17 |
+
Section 1 – Definitions.
|
18 |
+
|
19 |
+
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.
|
20 |
+
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.
|
21 |
+
c. BY-NC-SA Compatible License means a license listed at creativecommons.org/compatiblelicenses, approved by Creative Commons as essentially the equivalent of this Public License.
|
22 |
+
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.
|
23 |
+
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.
|
24 |
+
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.
|
25 |
+
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.
|
26 |
+
h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
27 |
+
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.
|
28 |
+
j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.
|
29 |
+
k. 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.
|
30 |
+
l. 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.
|
31 |
+
m. 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.
|
32 |
+
n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
|
33 |
+
Section 2 – Scope.
|
34 |
+
|
35 |
+
a. License grant.
|
36 |
+
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:
|
37 |
+
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
|
38 |
+
B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
|
39 |
+
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.
|
40 |
+
3. Term. The term of this Public License is specified in Section 6(a).
|
41 |
+
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.
|
42 |
+
5. Downstream recipients.
|
43 |
+
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.
|
44 |
+
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.
|
45 |
+
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.
|
46 |
+
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).
|
47 |
+
b. Other rights.
|
48 |
+
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.
|
49 |
+
2. Patent and trademark rights are not licensed under this Public License.
|
50 |
+
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.
|
51 |
+
Section 3 – License Conditions.
|
52 |
+
|
53 |
+
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
54 |
+
|
55 |
+
a. Attribution.
|
56 |
+
1. If You Share the Licensed Material (including in modified form), You must:
|
57 |
+
A. retain the following if it is supplied by the Licensor with the Licensed Material:
|
58 |
+
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);
|
59 |
+
ii. a copyright notice;
|
60 |
+
iii. a notice that refers to this Public License;
|
61 |
+
iv. a notice that refers to the disclaimer of warranties;
|
62 |
+
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
63 |
+
|
64 |
+
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
65 |
+
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.
|
66 |
+
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.
|
67 |
+
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.
|
68 |
+
b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.
|
69 |
+
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.
|
70 |
+
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.
|
71 |
+
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.
|
72 |
+
Section 4 – Sui Generis Database Rights.
|
73 |
+
|
74 |
+
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
|
75 |
+
|
76 |
+
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;
|
77 |
+
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
|
78 |
+
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.
|
79 |
+
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.
|
80 |
+
Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
81 |
+
|
82 |
+
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.
|
83 |
+
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.
|
84 |
+
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.
|
85 |
+
Section 6 – Term and Termination.
|
86 |
+
|
87 |
+
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.
|
88 |
+
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
|
89 |
+
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
|
90 |
+
2. upon express reinstatement by the Licensor.
|
91 |
+
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.
|
92 |
+
|
93 |
+
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.
|
94 |
+
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
|
95 |
+
Section 7 – Other Terms and Conditions.
|
96 |
+
|
97 |
+
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
|
98 |
+
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.
|
99 |
+
Section 8 – Interpretation.
|
100 |
+
|
101 |
+
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.
|
102 |
+
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.
|
103 |
+
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.
|
104 |
+
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.
|
105 |
+
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." The text of the Creative Commons public licenses is dedicated to the public domain under the CC0 Public Domain Dedication. 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, 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.
|
106 |
+
|
107 |
+
Creative Commons may be contacted at creativecommons.org.
|
README.md
CHANGED
@@ -1,3 +1,70 @@
|
|
1 |
-
|
2 |
-
|
3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Fashibles
|
2 |
+
|
3 |
+
|
4 |
+
|
5 |
+
|
6 |
+
## Installation
|
7 |
+
|
8 |
+
Create a conda environment & Install requirments
|
9 |
+
```shell
|
10 |
+
conda create -n catvton python==3.9.0
|
11 |
+
conda activate catvton
|
12 |
+
cd CatVTON-fashable # or your path to CatVTON project dir
|
13 |
+
pip install -r requirements.txt
|
14 |
+
```
|
15 |
+
|
16 |
+
## Run the Project First Init
|
17 |
+
This will full the pretrained freeze models
|
18 |
+
```shell
|
19 |
+
python app.py \
|
20 |
+
--output_dir="resource/demo/output" \
|
21 |
+
--mixed_precision="bf16" \
|
22 |
+
--allow_tf32
|
23 |
+
```
|
24 |
+
|
25 |
+
## Run as an API Server
|
26 |
+
```shell
|
27 |
+
python app_api.py
|
28 |
+
```
|
29 |
+
|
30 |
+
## API Call Sample Payload
|
31 |
+
```js
|
32 |
+
import axios from "axios";
|
33 |
+
|
34 |
+
const form = new FormData();
|
35 |
+
form.append("person_image", "/Users/ahmadabdulnasirshuaib/wsp/ml-al/clothChanger/assets/istockphoto-521071031-612x612.jpg");
|
36 |
+
form.append("cloth_image", "/Users/ahmadabdulnasirshuaib/wsp/ml-al/clothChanger/resource/demo/example/condition/upper/24083449_54173465_2048.jpg");
|
37 |
+
form.append("cloth_type", "upper");
|
38 |
+
|
39 |
+
const options = {
|
40 |
+
method: 'POST',
|
41 |
+
url: 'http://127.0.0.1:8000/process_images',
|
42 |
+
headers: {
|
43 |
+
'Content-Type': 'multipart/form-data; boundary=---011000010111000001101001',
|
44 |
+
'User-Agent': 'insomnia/9.3.3'
|
45 |
+
},
|
46 |
+
data: '[form]'
|
47 |
+
};
|
48 |
+
|
49 |
+
axios.request(options).then(function (response) {
|
50 |
+
console.log(response.data);
|
51 |
+
}).catch(function (error) {
|
52 |
+
console.error(error);
|
53 |
+
});
|
54 |
+
|
55 |
+
```
|
56 |
+
### Gradio App
|
57 |
+
|
58 |
+
To deploy the Gradio App for CatVTON on your machine, run the following command, and checkpoints will be automatically downloaded from HuggingFace.
|
59 |
+
|
60 |
+
```shell
|
61 |
+
CUDA_VISIBLE_DEVICES=0 python app.py \
|
62 |
+
--output_dir="resource/demo/output" \
|
63 |
+
--mixed_precision="bf16" \
|
64 |
+
--allow_tf32
|
65 |
+
```
|
66 |
+
|
67 |
+
When using `bf16` precision, generating results with a resolution of `1024x768` only requires about `8G` VRAM.
|
68 |
+
|
69 |
+
|
70 |
+
##
|
app.py
ADDED
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
from datetime import datetime
|
4 |
+
|
5 |
+
import gradio as gr
|
6 |
+
import numpy as np
|
7 |
+
import torch
|
8 |
+
device = torch.device('cpu') # Explicitly use CPU if desired
|
9 |
+
|
10 |
+
from diffusers.image_processor import VaeImageProcessor
|
11 |
+
from huggingface_hub import snapshot_download
|
12 |
+
from PIL import Image
|
13 |
+
|
14 |
+
from model.cloth_masker import AutoMasker, vis_mask
|
15 |
+
from model.pipeline import CatVTONPipeline
|
16 |
+
from utils import init_weight_dtype, resize_and_crop, resize_and_padding
|
17 |
+
|
18 |
+
def parse_args():
|
19 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
20 |
+
parser.add_argument(
|
21 |
+
"--base_model_path",
|
22 |
+
type=str,
|
23 |
+
default="Abhilashvj/stable-diffusion-inpainting-copy", #"runwayml/stable-diffusion-inpainting",
|
24 |
+
help=(
|
25 |
+
"The path to the base model to use for evaluation. This can be a local path or a model identifier from the Model Hub."
|
26 |
+
),
|
27 |
+
)
|
28 |
+
parser.add_argument(
|
29 |
+
"--resume_path",
|
30 |
+
type=str,
|
31 |
+
default="zhengchong/CatVTON",
|
32 |
+
help=(
|
33 |
+
"The Path to the checkpoint of trained tryon model."
|
34 |
+
),
|
35 |
+
)
|
36 |
+
parser.add_argument(
|
37 |
+
"--output_dir",
|
38 |
+
type=str,
|
39 |
+
default="resource/demo/output",
|
40 |
+
help="The output directory where the model predictions will be written.",
|
41 |
+
)
|
42 |
+
|
43 |
+
parser.add_argument(
|
44 |
+
"--width",
|
45 |
+
type=int,
|
46 |
+
default=768,
|
47 |
+
help=(
|
48 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
49 |
+
" resolution"
|
50 |
+
),
|
51 |
+
)
|
52 |
+
parser.add_argument(
|
53 |
+
"--height",
|
54 |
+
type=int,
|
55 |
+
default=1024,
|
56 |
+
help=(
|
57 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
58 |
+
" resolution"
|
59 |
+
),
|
60 |
+
)
|
61 |
+
parser.add_argument(
|
62 |
+
"--repaint",
|
63 |
+
action="store_true",
|
64 |
+
help="Whether to repaint the result image with the original background."
|
65 |
+
)
|
66 |
+
parser.add_argument(
|
67 |
+
"--allow_tf32",
|
68 |
+
action="store_true",
|
69 |
+
default=True,
|
70 |
+
help=(
|
71 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
72 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
73 |
+
),
|
74 |
+
)
|
75 |
+
parser.add_argument(
|
76 |
+
"--mixed_precision",
|
77 |
+
type=str,
|
78 |
+
default="bf16",
|
79 |
+
choices=["no", "fp16", "bf16"],
|
80 |
+
help=(
|
81 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
82 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
83 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
84 |
+
),
|
85 |
+
)
|
86 |
+
|
87 |
+
args = parser.parse_args()
|
88 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
89 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
90 |
+
args.local_rank = env_local_rank
|
91 |
+
|
92 |
+
return args
|
93 |
+
|
94 |
+
def image_grid(imgs, rows, cols):
|
95 |
+
assert len(imgs) == rows * cols
|
96 |
+
|
97 |
+
w, h = imgs[0].size
|
98 |
+
grid = Image.new("RGB", size=(cols * w, rows * h))
|
99 |
+
|
100 |
+
for i, img in enumerate(imgs):
|
101 |
+
grid.paste(img, box=(i % cols * w, i // cols * h))
|
102 |
+
return grid
|
103 |
+
|
104 |
+
|
105 |
+
args = parse_args()
|
106 |
+
repo_path = snapshot_download(repo_id=args.resume_path)
|
107 |
+
# Pipeline
|
108 |
+
pipeline = CatVTONPipeline(
|
109 |
+
base_ckpt=args.base_model_path,
|
110 |
+
attn_ckpt=repo_path,
|
111 |
+
attn_ckpt_version="mix",
|
112 |
+
weight_dtype=init_weight_dtype(args.mixed_precision),
|
113 |
+
use_tf32=args.allow_tf32,
|
114 |
+
# device='cuda'
|
115 |
+
device='cpu'
|
116 |
+
)
|
117 |
+
# AutoMasker
|
118 |
+
mask_processor = VaeImageProcessor(vae_scale_factor=8, do_normalize=False, do_binarize=True, do_convert_grayscale=True)
|
119 |
+
automasker = AutoMasker(
|
120 |
+
densepose_ckpt=os.path.join(repo_path, "DensePose"),
|
121 |
+
schp_ckpt=os.path.join(repo_path, "SCHP"),
|
122 |
+
# device='cuda',
|
123 |
+
device='cpu'
|
124 |
+
)
|
125 |
+
|
126 |
+
def submit_function(
|
127 |
+
person_image,
|
128 |
+
cloth_image,
|
129 |
+
cloth_type,
|
130 |
+
num_inference_steps,
|
131 |
+
guidance_scale,
|
132 |
+
seed,
|
133 |
+
show_type
|
134 |
+
):
|
135 |
+
person_image, mask = person_image["background"], person_image["layers"][0]
|
136 |
+
mask = Image.open(mask).convert("L")
|
137 |
+
if len(np.unique(np.array(mask))) == 1:
|
138 |
+
mask = None
|
139 |
+
else:
|
140 |
+
mask = np.array(mask)
|
141 |
+
mask[mask > 0] = 255
|
142 |
+
mask = Image.fromarray(mask)
|
143 |
+
|
144 |
+
tmp_folder = args.output_dir
|
145 |
+
date_str = datetime.now().strftime("%Y%m%d%H%M%S")
|
146 |
+
result_save_path = os.path.join(tmp_folder, date_str[:8], date_str[8:] + ".png")
|
147 |
+
if not os.path.exists(os.path.join(tmp_folder, date_str[:8])):
|
148 |
+
os.makedirs(os.path.join(tmp_folder, date_str[:8]))
|
149 |
+
|
150 |
+
generator = None
|
151 |
+
if seed != -1:
|
152 |
+
# generator = torch.Generator(device='cuda').manual_seed(seed)
|
153 |
+
generator = torch.Generator(device='cpu').manual_seed(seed)
|
154 |
+
|
155 |
+
person_image = Image.open(person_image).convert("RGB")
|
156 |
+
cloth_image = Image.open(cloth_image).convert("RGB")
|
157 |
+
person_image = resize_and_crop(person_image, (args.width, args.height))
|
158 |
+
cloth_image = resize_and_padding(cloth_image, (args.width, args.height))
|
159 |
+
|
160 |
+
# Process mask
|
161 |
+
if mask is not None:
|
162 |
+
mask = resize_and_crop(mask, (args.width, args.height))
|
163 |
+
else:
|
164 |
+
mask = automasker(
|
165 |
+
person_image,
|
166 |
+
cloth_type
|
167 |
+
)['mask']
|
168 |
+
mask = mask_processor.blur(mask, blur_factor=9)
|
169 |
+
|
170 |
+
# Inference
|
171 |
+
# try:
|
172 |
+
result_image = pipeline(
|
173 |
+
image=person_image,
|
174 |
+
condition_image=cloth_image,
|
175 |
+
mask=mask,
|
176 |
+
num_inference_steps=num_inference_steps,
|
177 |
+
guidance_scale=guidance_scale,
|
178 |
+
generator=generator
|
179 |
+
)[0]
|
180 |
+
# except Exception as e:
|
181 |
+
# raise gr.Error(
|
182 |
+
# "An error occurred. Please try again later: {}".format(e)
|
183 |
+
# )
|
184 |
+
|
185 |
+
# Post-process
|
186 |
+
masked_person = vis_mask(person_image, mask)
|
187 |
+
save_result_image = image_grid([person_image, masked_person, cloth_image, result_image], 1, 4)
|
188 |
+
save_result_image.save(result_save_path)
|
189 |
+
if show_type == "result only":
|
190 |
+
return result_image
|
191 |
+
else:
|
192 |
+
width, height = person_image.size
|
193 |
+
if show_type == "input & result":
|
194 |
+
condition_width = width // 2
|
195 |
+
conditions = image_grid([person_image, cloth_image], 2, 1)
|
196 |
+
else:
|
197 |
+
condition_width = width // 3
|
198 |
+
conditions = image_grid([person_image, masked_person , cloth_image], 3, 1)
|
199 |
+
conditions = conditions.resize((condition_width, height), Image.NEAREST)
|
200 |
+
new_result_image = Image.new("RGB", (width + condition_width + 5, height))
|
201 |
+
new_result_image.paste(conditions, (0, 0))
|
202 |
+
new_result_image.paste(result_image, (condition_width + 5, 0))
|
203 |
+
return new_result_image
|
204 |
+
|
205 |
+
|
206 |
+
def person_example_fn(image_path):
|
207 |
+
return image_path
|
208 |
+
|
209 |
+
HEADER = """
|
210 |
+
<h1 style="text-align: center;">
|
211 |
+
Fashioble
|
212 |
+
</h1>
|
213 |
+
|
214 |
+
"""
|
215 |
+
|
216 |
+
def app_gradio():
|
217 |
+
with gr.Blocks(title="CatVTON") as demo:
|
218 |
+
gr.Markdown(HEADER)
|
219 |
+
with gr.Row():
|
220 |
+
with gr.Column(scale=1, min_width=350):
|
221 |
+
with gr.Row():
|
222 |
+
image_path = gr.Image(
|
223 |
+
type="filepath",
|
224 |
+
interactive=True,
|
225 |
+
visible=False,
|
226 |
+
)
|
227 |
+
person_image = gr.ImageEditor(
|
228 |
+
interactive=True, label="Person Image", type="filepath"
|
229 |
+
)
|
230 |
+
|
231 |
+
with gr.Row():
|
232 |
+
with gr.Column(scale=1, min_width=230):
|
233 |
+
cloth_image = gr.Image(
|
234 |
+
interactive=True, label="Condition Image", type="filepath"
|
235 |
+
)
|
236 |
+
with gr.Column(scale=1, min_width=120):
|
237 |
+
gr.Markdown(
|
238 |
+
'<span style="color: #808080; font-size: small;">Two ways to provide Mask:<br>1. Upload the person image and use the `🖌️` above to draw the Mask (higher priority)<br>2. Select the `Try-On Cloth Type` to generate automatically </span>'
|
239 |
+
)
|
240 |
+
cloth_type = gr.Radio(
|
241 |
+
label="Try-On Cloth Type",
|
242 |
+
choices=["upper", "lower", "overall"],
|
243 |
+
value="upper",
|
244 |
+
)
|
245 |
+
|
246 |
+
|
247 |
+
submit = gr.Button("Submit")
|
248 |
+
gr.Markdown(
|
249 |
+
'<center><span style="color: #FF0000">!!! Click only Once, Wait for Delay !!!</span></center>'
|
250 |
+
)
|
251 |
+
|
252 |
+
gr.Markdown(
|
253 |
+
'<span style="color: #808080; font-size: small;">Advanced options can adjust details:<br>1. `Inference Step` may enhance details;<br>2. `CFG` is highly correlated with saturation;<br>3. `Random seed` may improve pseudo-shadow.</span>'
|
254 |
+
)
|
255 |
+
with gr.Accordion("Advanced Options", open=False):
|
256 |
+
num_inference_steps = gr.Slider(
|
257 |
+
label="Inference Step", minimum=10, maximum=100, step=5, value=50
|
258 |
+
)
|
259 |
+
# Guidence Scale
|
260 |
+
guidance_scale = gr.Slider(
|
261 |
+
label="CFG Strenth", minimum=0.0, maximum=7.5, step=0.5, value=2.5
|
262 |
+
)
|
263 |
+
# Random Seed
|
264 |
+
seed = gr.Slider(
|
265 |
+
label="Seed", minimum=-1, maximum=10000, step=1, value=42
|
266 |
+
)
|
267 |
+
show_type = gr.Radio(
|
268 |
+
label="Show Type",
|
269 |
+
choices=["result only", "input & result", "input & mask & result"],
|
270 |
+
value="input & mask & result",
|
271 |
+
)
|
272 |
+
|
273 |
+
with gr.Column(scale=2, min_width=500):
|
274 |
+
result_image = gr.Image(interactive=False, label="Result")
|
275 |
+
with gr.Row():
|
276 |
+
# Photo Examples
|
277 |
+
root_path = "resource/demo/example"
|
278 |
+
with gr.Column():
|
279 |
+
men_exm = gr.Examples(
|
280 |
+
examples=[
|
281 |
+
os.path.join(root_path, "person", "men", _)
|
282 |
+
for _ in os.listdir(os.path.join(root_path, "person", "men"))
|
283 |
+
],
|
284 |
+
examples_per_page=4,
|
285 |
+
inputs=image_path,
|
286 |
+
label="Person Examples ①",
|
287 |
+
)
|
288 |
+
women_exm = gr.Examples(
|
289 |
+
examples=[
|
290 |
+
os.path.join(root_path, "person", "women", _)
|
291 |
+
for _ in os.listdir(os.path.join(root_path, "person", "women"))
|
292 |
+
],
|
293 |
+
examples_per_page=4,
|
294 |
+
inputs=image_path,
|
295 |
+
label="Person Examples ②",
|
296 |
+
)
|
297 |
+
gr.Markdown(
|
298 |
+
'<span style="color: #808080; font-size: small;">*Person examples come from the demos of <a href="https://huggingface.co/spaces/levihsu/OOTDiffusion">OOTDiffusion</a> and <a href="https://www.outfitanyone.org">OutfitAnyone</a>. </span>'
|
299 |
+
)
|
300 |
+
with gr.Column():
|
301 |
+
condition_upper_exm = gr.Examples(
|
302 |
+
examples=[
|
303 |
+
os.path.join(root_path, "condition", "upper", _)
|
304 |
+
for _ in os.listdir(os.path.join(root_path, "condition", "upper"))
|
305 |
+
],
|
306 |
+
examples_per_page=4,
|
307 |
+
inputs=cloth_image,
|
308 |
+
label="Condition Upper Examples",
|
309 |
+
)
|
310 |
+
condition_overall_exm = gr.Examples(
|
311 |
+
examples=[
|
312 |
+
os.path.join(root_path, "condition", "overall", _)
|
313 |
+
for _ in os.listdir(os.path.join(root_path, "condition", "overall"))
|
314 |
+
],
|
315 |
+
examples_per_page=4,
|
316 |
+
inputs=cloth_image,
|
317 |
+
label="Condition Overall Examples",
|
318 |
+
)
|
319 |
+
condition_person_exm = gr.Examples(
|
320 |
+
examples=[
|
321 |
+
os.path.join(root_path, "condition", "person", _)
|
322 |
+
for _ in os.listdir(os.path.join(root_path, "condition", "person"))
|
323 |
+
],
|
324 |
+
examples_per_page=4,
|
325 |
+
inputs=cloth_image,
|
326 |
+
label="Condition Reference Person Examples",
|
327 |
+
)
|
328 |
+
gr.Markdown(
|
329 |
+
'<span style="color: #808080; font-size: small;">*Condition examples come from the Internet. </span>'
|
330 |
+
)
|
331 |
+
|
332 |
+
image_path.change(
|
333 |
+
person_example_fn, inputs=image_path, outputs=person_image
|
334 |
+
)
|
335 |
+
|
336 |
+
submit.click(
|
337 |
+
submit_function,
|
338 |
+
[
|
339 |
+
person_image,
|
340 |
+
cloth_image,
|
341 |
+
cloth_type,
|
342 |
+
num_inference_steps,
|
343 |
+
guidance_scale,
|
344 |
+
seed,
|
345 |
+
show_type,
|
346 |
+
],
|
347 |
+
result_image,
|
348 |
+
)
|
349 |
+
demo.queue().launch(share=True, show_error=True)
|
350 |
+
|
351 |
+
|
352 |
+
if __name__ == "__main__":
|
353 |
+
app_gradio()
|
app.py.amltmp
ADDED
@@ -0,0 +1,353 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
from datetime import datetime
|
4 |
+
|
5 |
+
import gradio as gr
|
6 |
+
import numpy as np
|
7 |
+
import torch
|
8 |
+
device = torch.device('cpu') # Explicitly use CPU if desired
|
9 |
+
|
10 |
+
from diffusers.image_processor import VaeImageProcessor
|
11 |
+
from huggingface_hub import snapshot_download
|
12 |
+
from PIL import Image
|
13 |
+
|
14 |
+
from model.cloth_masker import AutoMasker, vis_mask
|
15 |
+
from model.pipeline import CatVTONPipeline
|
16 |
+
from utils import init_weight_dtype, resize_and_crop, resize_and_padding
|
17 |
+
|
18 |
+
def parse_args():
|
19 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
20 |
+
parser.add_argument(
|
21 |
+
"--base_model_path",
|
22 |
+
type=str,
|
23 |
+
default="Abhilashvj/stable-diffusion-inpainting-copy", #"runwayml/stable-diffusion-inpainting",
|
24 |
+
help=(
|
25 |
+
"The path to the base model to use for evaluation. This can be a local path or a model identifier from the Model Hub."
|
26 |
+
),
|
27 |
+
)
|
28 |
+
parser.add_argument(
|
29 |
+
"--resume_path",
|
30 |
+
type=str,
|
31 |
+
default="zhengchong/CatVTON",
|
32 |
+
help=(
|
33 |
+
"The Path to the checkpoint of trained tryon model."
|
34 |
+
),
|
35 |
+
)
|
36 |
+
parser.add_argument(
|
37 |
+
"--output_dir",
|
38 |
+
type=str,
|
39 |
+
default="resource/demo/output",
|
40 |
+
help="The output directory where the model predictions will be written.",
|
41 |
+
)
|
42 |
+
|
43 |
+
parser.add_argument(
|
44 |
+
"--width",
|
45 |
+
type=int,
|
46 |
+
default=768,
|
47 |
+
help=(
|
48 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
49 |
+
" resolution"
|
50 |
+
),
|
51 |
+
)
|
52 |
+
parser.add_argument(
|
53 |
+
"--height",
|
54 |
+
type=int,
|
55 |
+
default=1024,
|
56 |
+
help=(
|
57 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
58 |
+
" resolution"
|
59 |
+
),
|
60 |
+
)
|
61 |
+
parser.add_argument(
|
62 |
+
"--repaint",
|
63 |
+
action="store_true",
|
64 |
+
help="Whether to repaint the result image with the original background."
|
65 |
+
)
|
66 |
+
parser.add_argument(
|
67 |
+
"--allow_tf32",
|
68 |
+
action="store_true",
|
69 |
+
default=True,
|
70 |
+
help=(
|
71 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
72 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
73 |
+
),
|
74 |
+
)
|
75 |
+
parser.add_argument(
|
76 |
+
"--mixed_precision",
|
77 |
+
type=str,
|
78 |
+
default="bf16",
|
79 |
+
choices=["no", "fp16", "bf16"],
|
80 |
+
help=(
|
81 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
82 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
83 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
84 |
+
),
|
85 |
+
)
|
86 |
+
|
87 |
+
args = parser.parse_args()
|
88 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
89 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
90 |
+
args.local_rank = env_local_rank
|
91 |
+
|
92 |
+
return args
|
93 |
+
|
94 |
+
def image_grid(imgs, rows, cols):
|
95 |
+
assert len(imgs) == rows * cols
|
96 |
+
|
97 |
+
w, h = imgs[0].size
|
98 |
+
grid = Image.new("RGB", size=(cols * w, rows * h))
|
99 |
+
|
100 |
+
for i, img in enumerate(imgs):
|
101 |
+
grid.paste(img, box=(i % cols * w, i // cols * h))
|
102 |
+
return grid
|
103 |
+
|
104 |
+
|
105 |
+
args = parse_args()
|
106 |
+
repo_path = snapshot_download(repo_id=args.resume_path)
|
107 |
+
# Pipeline
|
108 |
+
pipeline = CatVTONPipeline(
|
109 |
+
base_ckpt=args.base_model_path,
|
110 |
+
attn_ckpt=repo_path,
|
111 |
+
attn_ckpt_version="mix",
|
112 |
+
weight_dtype=init_weight_dtype(args.mixed_precision),
|
113 |
+
use_tf32=args.allow_tf32,
|
114 |
+
# device='cuda'
|
115 |
+
device='cpu'
|
116 |
+
)
|
117 |
+
# AutoMasker
|
118 |
+
mask_processor = VaeImageProcessor(vae_scale_factor=8, do_normalize=False, do_binarize=True, do_convert_grayscale=True)
|
119 |
+
automasker = AutoMasker(
|
120 |
+
densepose_ckpt=os.path.join(repo_path, "DensePose"),
|
121 |
+
schp_ckpt=os.path.join(repo_path, "SCHP"),
|
122 |
+
# device='cuda',
|
123 |
+
device='cpu'
|
124 |
+
)
|
125 |
+
|
126 |
+
def submit_function(
|
127 |
+
person_image,
|
128 |
+
cloth_image,
|
129 |
+
cloth_type,
|
130 |
+
num_inference_steps,
|
131 |
+
guidance_scale,
|
132 |
+
seed,
|
133 |
+
show_type
|
134 |
+
):
|
135 |
+
person_image, mask = person_image["background"], person_image["layers"][0]
|
136 |
+
mask = Image.open(mask).convert("L")
|
137 |
+
if len(np.unique(np.array(mask))) == 1:
|
138 |
+
mask = None
|
139 |
+
else:
|
140 |
+
mask = np.array(mask)
|
141 |
+
mask[mask > 0] = 255
|
142 |
+
mask = Image.fromarray(mask)
|
143 |
+
|
144 |
+
tmp_folder = args.output_dir
|
145 |
+
date_str = datetime.now().strftime("%Y%m%d%H%M%S")
|
146 |
+
result_save_path = os.path.join(tmp_folder, date_str[:8], date_str[8:] + ".png")
|
147 |
+
if not os.path.exists(os.path.join(tmp_folder, date_str[:8])):
|
148 |
+
os.makedirs(os.path.join(tmp_folder, date_str[:8]))
|
149 |
+
|
150 |
+
generator = None
|
151 |
+
if seed != -1:
|
152 |
+
# generator = torch.Generator(device='cuda').manual_seed(seed)
|
153 |
+
generator = torch.Generator(device='cpu').manual_seed(seed)
|
154 |
+
|
155 |
+
person_image = Image.open(person_image).convert("RGB")
|
156 |
+
cloth_image = Image.open(cloth_image).convert("RGB")
|
157 |
+
person_image = resize_and_crop(person_image, (args.width, args.height))
|
158 |
+
cloth_image = resize_and_padding(cloth_image, (args.width, args.height))
|
159 |
+
|
160 |
+
# Process mask
|
161 |
+
if mask is not None:
|
162 |
+
mask = resize_and_crop(mask, (args.width, args.height))
|
163 |
+
else:
|
164 |
+
mask = automasker(
|
165 |
+
person_image,
|
166 |
+
cloth_type
|
167 |
+
)['mask']
|
168 |
+
mask = mask_processor.blur(mask, blur_factor=9)
|
169 |
+
|
170 |
+
# Inference
|
171 |
+
# try:
|
172 |
+
result_image = pipeline(
|
173 |
+
image=person_image,
|
174 |
+
condition_image=cloth_image,
|
175 |
+
mask=mask,
|
176 |
+
num_inference_steps=num_inference_steps,
|
177 |
+
guidance_scale=guidance_scale,
|
178 |
+
generator=generator
|
179 |
+
)[0]
|
180 |
+
# except Exception as e:
|
181 |
+
# raise gr.Error(
|
182 |
+
# "An error occurred. Please try again later: {}".format(e)
|
183 |
+
# )
|
184 |
+
|
185 |
+
# Post-process
|
186 |
+
masked_person = vis_mask(person_image, mask)
|
187 |
+
save_result_image = image_grid([person_image, masked_person, cloth_image, result_image], 1, 4)
|
188 |
+
save_result_image.save(result_save_path)
|
189 |
+
if show_type == "result only":
|
190 |
+
return result_image
|
191 |
+
else:
|
192 |
+
width, height = person_image.size
|
193 |
+
if show_type == "input & result":
|
194 |
+
condition_width = width // 2
|
195 |
+
conditions = image_grid([person_image, cloth_image], 2, 1)
|
196 |
+
else:
|
197 |
+
condition_width = width // 3
|
198 |
+
conditions = image_grid([person_image, masked_person , cloth_image], 3, 1)
|
199 |
+
conditions = conditions.resize((condition_width, height), Image.NEAREST)
|
200 |
+
new_result_image = Image.new("RGB", (width + condition_width + 5, height))
|
201 |
+
new_result_image.paste(conditions, (0, 0))
|
202 |
+
new_result_image.paste(result_image, (condition_width + 5, 0))
|
203 |
+
return new_result_image
|
204 |
+
|
205 |
+
|
206 |
+
def person_example_fn(image_path):
|
207 |
+
return image_path
|
208 |
+
|
209 |
+
HEADER = """
|
210 |
+
<h1 style="text-align: center;">
|
211 |
+
Fashioble
|
212 |
+
</h1>
|
213 |
+
|
214 |
+
"""
|
215 |
+
|
216 |
+
def app_gradio():
|
217 |
+
with gr.Blocks(title="CatVTON") as demo:
|
218 |
+
gr.Markdown(HEADER)
|
219 |
+
with gr.Row():
|
220 |
+
with gr.Column(scale=1, min_width=350):
|
221 |
+
with gr.Row():
|
222 |
+
image_path = gr.Image(
|
223 |
+
type="filepath",
|
224 |
+
interactive=True,
|
225 |
+
visible=False,
|
226 |
+
)
|
227 |
+
person_image = gr.ImageEditor(
|
228 |
+
interactive=True, label="Person Image", type="filepath"
|
229 |
+
)
|
230 |
+
|
231 |
+
with gr.Row():
|
232 |
+
with gr.Column(scale=1, min_width=230):
|
233 |
+
cloth_image = gr.Image(
|
234 |
+
interactive=True, label="Condition Image", type="filepath"
|
235 |
+
)
|
236 |
+
with gr.Column(scale=1, min_width=120):
|
237 |
+
gr.Markdown(
|
238 |
+
'<span style="color: #808080; font-size: small;">Two ways to provide Mask:<br>1. Upload the person image and use the `🖌️` above to draw the Mask (higher priority)<br>2. Select the `Try-On Cloth Type` to generate automatically </span>'
|
239 |
+
)
|
240 |
+
cloth_type = gr.Radio(
|
241 |
+
label="Try-On Cloth Type",
|
242 |
+
choices=["upper", "lower", "overall"],
|
243 |
+
value="upper",
|
244 |
+
)
|
245 |
+
|
246 |
+
|
247 |
+
submit = gr.Button("Submit")
|
248 |
+
gr.Markdown(
|
249 |
+
'<center><span style="color: #FF0000">!!! Click only Once, Wait for Delay !!!</span></center>'
|
250 |
+
)
|
251 |
+
|
252 |
+
gr.Markdown(
|
253 |
+
'<span style="color: #808080; font-size: small;">Advanced options can adjust details:<br>1. `Inference Step` may enhance details;<br>2. `CFG` is highly correlated with saturation;<br>3. `Random seed` may improve pseudo-shadow.</span>'
|
254 |
+
)
|
255 |
+
with gr.Accordion("Advanced Options", open=False):
|
256 |
+
num_inference_steps = gr.Slider(
|
257 |
+
label="Inference Step", minimum=10, maximum=100, step=5, value=50
|
258 |
+
)
|
259 |
+
# Guidence Scale
|
260 |
+
guidance_scale = gr.Slider(
|
261 |
+
label="CFG Strenth", minimum=0.0, maximum=7.5, step=0.5, value=2.5
|
262 |
+
)
|
263 |
+
# Random Seed
|
264 |
+
seed = gr.Slider(
|
265 |
+
label="Seed", minimum=-1, maximum=10000, step=1, value=42
|
266 |
+
)
|
267 |
+
show_type = gr.Radio(
|
268 |
+
label="Show Type",
|
269 |
+
choices=["result only", "input & result", "input & mask & result"],
|
270 |
+
value="input & mask & result",
|
271 |
+
)
|
272 |
+
|
273 |
+
with gr.Column(scale=2, min_width=500):
|
274 |
+
result_image = gr.Image(interactive=False, label="Result")
|
275 |
+
with gr.Row():
|
276 |
+
# Photo Examples
|
277 |
+
root_path = "resource/demo/example"
|
278 |
+
with gr.Column():
|
279 |
+
men_exm = gr.Examples(
|
280 |
+
examples=[
|
281 |
+
os.path.join(root_path, "person", "men", _)
|
282 |
+
for _ in os.listdir(os.path.join(root_path, "person", "men"))
|
283 |
+
],
|
284 |
+
examples_per_page=4,
|
285 |
+
inputs=image_path,
|
286 |
+
label="Person Examples ①",
|
287 |
+
)
|
288 |
+
women_exm = gr.Examples(
|
289 |
+
examples=[
|
290 |
+
os.path.join(root_path, "person", "women", _)
|
291 |
+
for _ in os.listdir(os.path.join(root_path, "person", "women"))
|
292 |
+
],
|
293 |
+
examples_per_page=4,
|
294 |
+
inputs=image_path,
|
295 |
+
label="Person Examples ②",
|
296 |
+
)
|
297 |
+
gr.Markdown(
|
298 |
+
'<span style="color: #808080; font-size: small;">*Person examples come from the demos of <a href="https://huggingface.co/spaces/levihsu/OOTDiffusion">OOTDiffusion</a> and <a href="https://www.outfitanyone.org">OutfitAnyone</a>. </span>'
|
299 |
+
)
|
300 |
+
with gr.Column():
|
301 |
+
condition_upper_exm = gr.Examples(
|
302 |
+
examples=[
|
303 |
+
os.path.join(root_path, "condition", "upper", _)
|
304 |
+
for _ in os.listdir(os.path.join(root_path, "condition", "upper"))
|
305 |
+
],
|
306 |
+
examples_per_page=4,
|
307 |
+
inputs=cloth_image,
|
308 |
+
label="Condition Upper Examples",
|
309 |
+
)
|
310 |
+
condition_overall_exm = gr.Examples(
|
311 |
+
examples=[
|
312 |
+
os.path.join(root_path, "condition", "overall", _)
|
313 |
+
for _ in os.listdir(os.path.join(root_path, "condition", "overall"))
|
314 |
+
],
|
315 |
+
examples_per_page=4,
|
316 |
+
inputs=cloth_image,
|
317 |
+
label="Condition Overall Examples",
|
318 |
+
)
|
319 |
+
condition_person_exm = gr.Examples(
|
320 |
+
examples=[
|
321 |
+
os.path.join(root_path, "condition", "person", _)
|
322 |
+
for _ in os.listdir(os.path.join(root_path, "condition", "person"))
|
323 |
+
],
|
324 |
+
examples_per_page=4,
|
325 |
+
inputs=cloth_image,
|
326 |
+
label="Condition Reference Person Examples",
|
327 |
+
)
|
328 |
+
gr.Markdown(
|
329 |
+
'<span style="color: #808080; font-size: small;">*Condition examples come from the Internet. </span>'
|
330 |
+
)
|
331 |
+
|
332 |
+
image_path.change(
|
333 |
+
person_example_fn, inputs=image_path, outputs=person_image
|
334 |
+
)
|
335 |
+
|
336 |
+
submit.click(
|
337 |
+
submit_function,
|
338 |
+
[
|
339 |
+
person_image,
|
340 |
+
cloth_image,
|
341 |
+
cloth_type,
|
342 |
+
num_inference_steps,
|
343 |
+
guidance_scale,
|
344 |
+
seed,
|
345 |
+
show_type,
|
346 |
+
],
|
347 |
+
result_image,
|
348 |
+
)
|
349 |
+
demo.queue().launch(share=True, show_error=True)
|
350 |
+
|
351 |
+
|
352 |
+
if __name__ == "__main__":
|
353 |
+
app_gradio()
|
app_api.py
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
# -*- coding: utf-8 -*-
|
3 |
+
"""
|
4 |
+
__author__ = 'Ahmad Abdulnasir Shuaib <[email protected]>'
|
5 |
+
__homepage__ = https://ahmadabdulnasir.com.ng
|
6 |
+
__copyright__ = 'Copyright (c) 2024, salafi'
|
7 |
+
__version__ = "0.01t"
|
8 |
+
"""
|
9 |
+
from fastapi import FastAPI, File, UploadFile, Form
|
10 |
+
from fastapi.responses import FileResponse
|
11 |
+
# from pydantic import BaseSettings
|
12 |
+
from pydantic_settings import BaseSettings
|
13 |
+
|
14 |
+
|
15 |
+
from PIL import Image
|
16 |
+
import io
|
17 |
+
import os
|
18 |
+
from datetime import datetime
|
19 |
+
import torch
|
20 |
+
import numpy as np
|
21 |
+
from diffusers.image_processor import VaeImageProcessor
|
22 |
+
from huggingface_hub import snapshot_download
|
23 |
+
from model.cloth_masker import AutoMasker
|
24 |
+
from model.pipeline import CatVTONPipeline
|
25 |
+
from utils import init_weight_dtype, resize_and_crop, resize_and_padding
|
26 |
+
|
27 |
+
class Settings(BaseSettings):
|
28 |
+
base_model_path: str = "Abhilashvj/stable-diffusion-inpainting-copy" #"runwayml/stable-diffusion-inpainting" #
|
29 |
+
resume_path: str = "abubakar123456/CatVTON" #"zhengchong/CatVTON"
|
30 |
+
output_dir: str = "resource/demo/output"
|
31 |
+
width: int = 768
|
32 |
+
height: int = 1024
|
33 |
+
allow_tf32: bool = True
|
34 |
+
mixed_precision: str = "bf16"
|
35 |
+
|
36 |
+
class Config:
|
37 |
+
env_file = ".env"
|
38 |
+
|
39 |
+
settings = Settings()
|
40 |
+
|
41 |
+
app = FastAPI()
|
42 |
+
|
43 |
+
# Initialize your models and processors here
|
44 |
+
repo_path = snapshot_download(repo_id=settings.resume_path)
|
45 |
+
|
46 |
+
pipeline = CatVTONPipeline(
|
47 |
+
base_ckpt=settings.base_model_path,
|
48 |
+
attn_ckpt=repo_path,
|
49 |
+
attn_ckpt_version="mix",
|
50 |
+
weight_dtype=init_weight_dtype(settings.mixed_precision),
|
51 |
+
use_tf32=settings.allow_tf32,
|
52 |
+
device='cpu'
|
53 |
+
)
|
54 |
+
|
55 |
+
mask_processor = VaeImageProcessor(vae_scale_factor=8, do_normalize=False, do_binarize=True, do_convert_grayscale=True)
|
56 |
+
automasker = AutoMasker(
|
57 |
+
densepose_ckpt=os.path.join(repo_path, "DensePose"),
|
58 |
+
schp_ckpt=os.path.join(repo_path, "SCHP"),
|
59 |
+
device='cpu'
|
60 |
+
)
|
61 |
+
|
62 |
+
@app.post("/process_images/")
|
63 |
+
async def process_images(
|
64 |
+
person_image: UploadFile = File(...),
|
65 |
+
cloth_image: UploadFile = File(...),
|
66 |
+
cloth_type: str = Form(...),
|
67 |
+
num_inference_steps: int = Form(50),
|
68 |
+
guidance_scale: float = Form(2.5),
|
69 |
+
seed: int = Form(42)
|
70 |
+
):
|
71 |
+
# Read and process the uploaded images
|
72 |
+
person_img = Image.open(io.BytesIO(await person_image.read())).convert("RGB")
|
73 |
+
cloth_img = Image.open(io.BytesIO(await cloth_image.read())).convert("RGB")
|
74 |
+
|
75 |
+
person_img = resize_and_crop(person_img, (settings.width, settings.height))
|
76 |
+
cloth_img = resize_and_padding(cloth_img, (settings.width, settings.height))
|
77 |
+
|
78 |
+
# Generate mask
|
79 |
+
mask = automasker(person_img, cloth_type)['mask']
|
80 |
+
mask = mask_processor.blur(mask, blur_factor=9)
|
81 |
+
|
82 |
+
# Set up generator for reproducibility
|
83 |
+
generator = torch.Generator(device='cpu').manual_seed(seed) if seed != -1 else None
|
84 |
+
|
85 |
+
# Run inference
|
86 |
+
result_image = pipeline(
|
87 |
+
image=person_img,
|
88 |
+
condition_image=cloth_img,
|
89 |
+
mask=mask,
|
90 |
+
num_inference_steps=num_inference_steps,
|
91 |
+
guidance_scale=guidance_scale,
|
92 |
+
generator=generator
|
93 |
+
)[0]
|
94 |
+
|
95 |
+
# Save the result
|
96 |
+
tmp_folder = settings.output_dir
|
97 |
+
date_str = datetime.now().strftime("%Y%m%d%H%M%S")
|
98 |
+
result_save_path = os.path.join(tmp_folder, date_str[:8], date_str[8:] + ".png")
|
99 |
+
os.makedirs(os.path.dirname(result_save_path), exist_ok=True)
|
100 |
+
result_image.save(result_save_path)
|
101 |
+
|
102 |
+
# Return the result image
|
103 |
+
return FileResponse(result_save_path, media_type="image/png")
|
104 |
+
|
105 |
+
|
106 |
+
def boot():
|
107 |
+
import uvicorn
|
108 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
109 |
+
|
110 |
+
if __name__ == "__main__":
|
111 |
+
boot()
|
app_api.py.amltmp
ADDED
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
# -*- coding: utf-8 -*-
|
3 |
+
"""
|
4 |
+
__author__ = 'Ahmad Abdulnasir Shuaib <[email protected]>'
|
5 |
+
__homepage__ = https://ahmadabdulnasir.com.ng
|
6 |
+
__copyright__ = 'Copyright (c) 2024, salafi'
|
7 |
+
__version__ = "0.01t"
|
8 |
+
"""
|
9 |
+
from fastapi import FastAPI, File, UploadFile, Form
|
10 |
+
from fastapi.responses import FileResponse
|
11 |
+
# from pydantic import BaseSettings
|
12 |
+
from pydantic_settings import BaseSettings
|
13 |
+
|
14 |
+
|
15 |
+
from PIL import Image
|
16 |
+
import io
|
17 |
+
import os
|
18 |
+
from datetime import datetime
|
19 |
+
import torch
|
20 |
+
import numpy as np
|
21 |
+
from diffusers.image_processor import VaeImageProcessor
|
22 |
+
from huggingface_hub import snapshot_download
|
23 |
+
from model.cloth_masker import AutoMasker
|
24 |
+
from model.pipeline import CatVTONPipeline
|
25 |
+
from utils import init_weight_dtype, resize_and_crop, resize_and_padding
|
26 |
+
|
27 |
+
class Settings(BaseSettings):
|
28 |
+
base_model_path: str = "Abhilashvj/stable-diffusion-inpainting-copy" #"runwayml/stable-diffusion-inpainting" #
|
29 |
+
resume_path: str = "abubakar123456/CatVTON" #"zhengchong/CatVTON"
|
30 |
+
output_dir: str = "resource/demo/output"
|
31 |
+
width: int = 768
|
32 |
+
height: int = 1024
|
33 |
+
allow_tf32: bool = True
|
34 |
+
mixed_precision: str = "bf16"
|
35 |
+
|
36 |
+
class Config:
|
37 |
+
env_file = ".env"
|
38 |
+
|
39 |
+
settings = Settings()
|
40 |
+
|
41 |
+
app = FastAPI()
|
42 |
+
|
43 |
+
# Initialize your models and processors here
|
44 |
+
repo_path = snapshot_download(repo_id=settings.resume_path)
|
45 |
+
|
46 |
+
pipeline = CatVTONPipeline(
|
47 |
+
base_ckpt=settings.base_model_path,
|
48 |
+
attn_ckpt=repo_path,
|
49 |
+
attn_ckpt_version="mix",
|
50 |
+
weight_dtype=init_weight_dtype(settings.mixed_precision),
|
51 |
+
use_tf32=settings.allow_tf32,
|
52 |
+
device='cpu'
|
53 |
+
)
|
54 |
+
|
55 |
+
mask_processor = VaeImageProcessor(vae_scale_factor=8, do_normalize=False, do_binarize=True, do_convert_grayscale=True)
|
56 |
+
automasker = AutoMasker(
|
57 |
+
densepose_ckpt=os.path.join(repo_path, "DensePose"),
|
58 |
+
schp_ckpt=os.path.join(repo_path, "SCHP"),
|
59 |
+
device='cpu'
|
60 |
+
)
|
61 |
+
|
62 |
+
@app.post("/process_images/")
|
63 |
+
async def process_images(
|
64 |
+
person_image: UploadFile = File(...),
|
65 |
+
cloth_image: UploadFile = File(...),
|
66 |
+
cloth_type: str = Form(...),
|
67 |
+
num_inference_steps: int = Form(50),
|
68 |
+
guidance_scale: float = Form(2.5),
|
69 |
+
seed: int = Form(42)
|
70 |
+
):
|
71 |
+
# Read and process the uploaded images
|
72 |
+
person_img = Image.open(io.BytesIO(await person_image.read())).convert("RGB")
|
73 |
+
cloth_img = Image.open(io.BytesIO(await cloth_image.read())).convert("RGB")
|
74 |
+
|
75 |
+
person_img = resize_and_crop(person_img, (settings.width, settings.height))
|
76 |
+
cloth_img = resize_and_padding(cloth_img, (settings.width, settings.height))
|
77 |
+
|
78 |
+
# Generate mask
|
79 |
+
mask = automasker(person_img, cloth_type)['mask']
|
80 |
+
mask = mask_processor.blur(mask, blur_factor=9)
|
81 |
+
|
82 |
+
# Set up generator for reproducibility
|
83 |
+
generator = torch.Generator(device='cpu').manual_seed(seed) if seed != -1 else None
|
84 |
+
|
85 |
+
# Run inference
|
86 |
+
result_image = pipeline(
|
87 |
+
image=person_img,
|
88 |
+
condition_image=cloth_img,
|
89 |
+
mask=mask,
|
90 |
+
num_inference_steps=num_inference_steps,
|
91 |
+
guidance_scale=guidance_scale,
|
92 |
+
generator=generator
|
93 |
+
)[0]
|
94 |
+
|
95 |
+
# Save the result
|
96 |
+
tmp_folder = settings.output_dir
|
97 |
+
date_str = datetime.now().strftime("%Y%m%d%H%M%S")
|
98 |
+
result_save_path = os.path.join(tmp_folder, date_str[:8], date_str[8:] + ".png")
|
99 |
+
os.makedirs(os.path.dirname(result_save_path), exist_ok=True)
|
100 |
+
result_image.save(result_save_path)
|
101 |
+
|
102 |
+
# Return the result image
|
103 |
+
return FileResponse(result_save_path, media_type="image/png")
|
104 |
+
|
105 |
+
|
106 |
+
def boot():
|
107 |
+
import uvicorn
|
108 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
109 |
+
|
110 |
+
if __name__ == "__main__":
|
111 |
+
boot()
|
eval.py
ADDED
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
from cleanfid import fid as FID
|
4 |
+
from PIL import Image
|
5 |
+
from torch.utils.data import Dataset
|
6 |
+
from torchmetrics.image import StructuralSimilarityIndexMeasure
|
7 |
+
from torchmetrics.image.lpip import LearnedPerceptualImagePatchSimilarity
|
8 |
+
from torchvision import transforms
|
9 |
+
from tqdm import tqdm
|
10 |
+
|
11 |
+
from utils import scan_files_in_dir
|
12 |
+
from prettytable import PrettyTable
|
13 |
+
|
14 |
+
class EvalDataset(Dataset):
|
15 |
+
def __init__(self, gt_folder, pred_folder, height=1024):
|
16 |
+
self.gt_folder = gt_folder
|
17 |
+
self.pred_folder = pred_folder
|
18 |
+
self.height = height
|
19 |
+
self.data = self.prepare_data()
|
20 |
+
self.to_tensor = transforms.ToTensor()
|
21 |
+
|
22 |
+
def extract_id_from_filename(self, filename):
|
23 |
+
# find first number in filename
|
24 |
+
start_i = None
|
25 |
+
for i, c in enumerate(filename):
|
26 |
+
if c.isdigit():
|
27 |
+
start_i = i
|
28 |
+
break
|
29 |
+
if start_i is None:
|
30 |
+
assert False, f"Cannot find number in filename {filename}"
|
31 |
+
return filename[start_i:start_i+8]
|
32 |
+
|
33 |
+
def prepare_data(self):
|
34 |
+
gt_files = scan_files_in_dir(self.gt_folder, postfix={'.jpg', '.png'})
|
35 |
+
gt_dict = {self.extract_id_from_filename(file.name): file for file in gt_files}
|
36 |
+
pred_files = scan_files_in_dir(self.pred_folder, postfix={'.jpg', '.png'})
|
37 |
+
|
38 |
+
tuples = []
|
39 |
+
for pred_file in pred_files:
|
40 |
+
pred_id = self.extract_id_from_filename(pred_file.name)
|
41 |
+
if pred_id not in gt_dict:
|
42 |
+
print(f"Cannot find gt file for {pred_file}")
|
43 |
+
else:
|
44 |
+
tuples.append((gt_dict[pred_id].path, pred_file.path))
|
45 |
+
return tuples
|
46 |
+
|
47 |
+
def resize(self, img):
|
48 |
+
w, h = img.size
|
49 |
+
new_w = int(w * self.height / h)
|
50 |
+
return img.resize((new_w, self.height), Image.LANCZOS)
|
51 |
+
|
52 |
+
def __len__(self):
|
53 |
+
return len(self.data)
|
54 |
+
|
55 |
+
def __getitem__(self, idx):
|
56 |
+
gt_path, pred_path = self.data[idx]
|
57 |
+
gt, pred = self.resize(Image.open(gt_path)), self.resize(Image.open(pred_path))
|
58 |
+
if gt.height != self.height:
|
59 |
+
gt = self.resize(gt)
|
60 |
+
if pred.height != self.height:
|
61 |
+
pred = self.resize(pred)
|
62 |
+
gt = self.to_tensor(gt)
|
63 |
+
pred = self.to_tensor(pred)
|
64 |
+
return gt, pred
|
65 |
+
|
66 |
+
|
67 |
+
def copy_resize_gt(gt_folder, height):
|
68 |
+
new_folder = f"{gt_folder}_{height}"
|
69 |
+
if not os.path.exists(new_folder):
|
70 |
+
os.makedirs(new_folder, exist_ok=True)
|
71 |
+
for file in tqdm(os.listdir(gt_folder)):
|
72 |
+
if os.path.exists(os.path.join(new_folder, file)):
|
73 |
+
continue
|
74 |
+
img = Image.open(os.path.join(gt_folder, file))
|
75 |
+
w, h = img.size
|
76 |
+
new_w = int(w * height / h)
|
77 |
+
img = img.resize((new_w, height), Image.LANCZOS)
|
78 |
+
img.save(os.path.join(new_folder, file))
|
79 |
+
return new_folder
|
80 |
+
|
81 |
+
|
82 |
+
@torch.no_grad()
|
83 |
+
def ssim(dataloader):
|
84 |
+
ssim_score = 0
|
85 |
+
# ssim = StructuralSimilarityIndexMeasure(data_range=1.0).to("cuda")
|
86 |
+
ssim = StructuralSimilarityIndexMeasure(data_range=1.0).to("cpu")
|
87 |
+
for gt, pred in tqdm(dataloader, desc="Calculating SSIM"):
|
88 |
+
batch_size = gt.size(0)
|
89 |
+
# gt, pred = gt.to("cuda"), pred.to("cuda")
|
90 |
+
gt, pred = gt.to("cpu"), pred.to("cpu")
|
91 |
+
ssim_score += ssim(pred, gt) * batch_size
|
92 |
+
return ssim_score / len(dataloader.dataset)
|
93 |
+
|
94 |
+
|
95 |
+
@torch.no_grad()
|
96 |
+
def lpips(dataloader):
|
97 |
+
# lpips_score = LearnedPerceptualImagePatchSimilarity(net_type='squeeze').to("cuda")
|
98 |
+
lpips_score = LearnedPerceptualImagePatchSimilarity(net_type='squeeze').to("cpu")
|
99 |
+
score = 0
|
100 |
+
for gt, pred in tqdm(dataloader, desc="Calculating LPIPS"):
|
101 |
+
batch_size = gt.size(0)
|
102 |
+
# pred = pred.to("cuda")
|
103 |
+
pred = pred.to("cpu")
|
104 |
+
# gt = gt.to("cuda")
|
105 |
+
gt = gt.to("cpu")
|
106 |
+
# LPIPS needs the images to be in the [-1, 1] range.
|
107 |
+
gt = (gt * 2) - 1
|
108 |
+
pred = (pred * 2) - 1
|
109 |
+
score += lpips_score(gt, pred) * batch_size
|
110 |
+
return score / len(dataloader.dataset)
|
111 |
+
|
112 |
+
|
113 |
+
def eval(args):
|
114 |
+
# Check gt_folder has images with target height, resize if not
|
115 |
+
pred_sample = os.listdir(args.pred_folder)[0]
|
116 |
+
gt_sample = os.listdir(args.gt_folder)[0]
|
117 |
+
img = Image.open(os.path.join(args.pred_folder, pred_sample))
|
118 |
+
gt_img = Image.open(os.path.join(args.gt_folder, gt_sample))
|
119 |
+
if img.height != gt_img.height:
|
120 |
+
title = "--"*30 + "Resizing GT Images to height {img.height}" + "--"*30
|
121 |
+
print(title)
|
122 |
+
args.gt_folder = copy_resize_gt(args.gt_folder, img.height)
|
123 |
+
print("-"*len(title))
|
124 |
+
|
125 |
+
# Form dataset
|
126 |
+
dataset = EvalDataset(args.gt_folder, args.pred_folder, img.height)
|
127 |
+
dataloader = torch.utils.data.DataLoader(
|
128 |
+
dataset, batch_size=args.batch_size, num_workers=args.num_workers, shuffle=False, drop_last=False
|
129 |
+
)
|
130 |
+
|
131 |
+
# Calculate Metrics
|
132 |
+
header = []
|
133 |
+
row = []
|
134 |
+
header = ["FID", "KID"]
|
135 |
+
fid_ = FID.compute_fid(args.gt_folder, args.pred_folder)
|
136 |
+
kid_ = FID.compute_kid(args.gt_folder, args.pred_folder) * 1000
|
137 |
+
row = [fid_, kid_]
|
138 |
+
if args.paired:
|
139 |
+
header += ["SSIM", "LPIPS"]
|
140 |
+
ssim_ = ssim(dataloader).item()
|
141 |
+
lpips_ = lpips(dataloader).item()
|
142 |
+
row += [ssim_, lpips_]
|
143 |
+
|
144 |
+
# Print Results
|
145 |
+
print("GT Folder : ", args.gt_folder)
|
146 |
+
print("Pred Folder: ", args.pred_folder)
|
147 |
+
table = PrettyTable()
|
148 |
+
table.field_names = header
|
149 |
+
table.add_row(row)
|
150 |
+
print(table)
|
151 |
+
|
152 |
+
|
153 |
+
if __name__ == "__main__":
|
154 |
+
import argparse
|
155 |
+
parser = argparse.ArgumentParser()
|
156 |
+
parser.add_argument("--gt_folder", type=str, required=True)
|
157 |
+
parser.add_argument("--pred_folder", type=str, required=True)
|
158 |
+
parser.add_argument("--paired", action="store_true")
|
159 |
+
parser.add_argument("--batch_size", type=int, default=16)
|
160 |
+
parser.add_argument("--num_workers", type=int, default=4)
|
161 |
+
args = parser.parse_args()
|
162 |
+
|
163 |
+
eval(args)
|
index.html
ADDED
@@ -0,0 +1,339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
<!DOCTYPE html>
|
2 |
+
<html>
|
3 |
+
<head>
|
4 |
+
<meta charset="utf-8">
|
5 |
+
<meta name="description"
|
6 |
+
content="🐈 CatVTON: Concatenation Is All You Need for Virtual Try-On with Diffusion Models">
|
7 |
+
<meta name="keywords" content="">
|
8 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
9 |
+
|
10 |
+
<title>🐈 CatVTON: Concatenation Is All You Need for Virtual Try-On with Diffusion Models</title>
|
11 |
+
<script async src="https://www.googletagmanager.com/gtag/js?id=G-PYVRSFMDRL"></script>
|
12 |
+
<script>
|
13 |
+
window.dataLayer = window.dataLayer || [];
|
14 |
+
function gtag() {
|
15 |
+
dataLayer.push(arguments);
|
16 |
+
}
|
17 |
+
gtag('js', new Date());
|
18 |
+
gtag('config', 'G-PYVRSFMDRL');
|
19 |
+
</script>
|
20 |
+
|
21 |
+
|
22 |
+
<link href="https://fonts.googleapis.com/css?family=Google+Sans|Noto+Sans|Castoro"
|
23 |
+
rel="stylesheet">
|
24 |
+
<link rel="stylesheet" href="resource/css/bulma.min.css">
|
25 |
+
<link rel="stylesheet" href="resource/css/bulma-carousel.min.css">
|
26 |
+
<link rel="stylesheet" href="resource/css/bulma-slider.min.css">
|
27 |
+
<link rel="stylesheet" href="resource/css/fontawesome.all.min.css">
|
28 |
+
<link rel="stylesheet"
|
29 |
+
href="https://cdn.jsdelivr.net/gh/jpswalsh/academicons@1/css/academicons.min.css">
|
30 |
+
<link rel="stylesheet" href="resource/css/index.css">
|
31 |
+
<link rel="icon" href="resource/images/favicon.svg">
|
32 |
+
|
33 |
+
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
|
34 |
+
<script defer src="resource/js/fontawesome.all.min.js"></script>
|
35 |
+
<script src="resource/js/bulma-carousel.min.js"></script>
|
36 |
+
<script src="resource/js/bulma-slider.min.js"></script>
|
37 |
+
<script src="resource/js/index.js"></script>
|
38 |
+
</head>
|
39 |
+
<body>
|
40 |
+
|
41 |
+
|
42 |
+
<section class="hero">
|
43 |
+
<div class="hero-body">
|
44 |
+
<div class="container is-max-desktop">
|
45 |
+
<div class="columns is-centered">
|
46 |
+
<div class="column has-text-centered">
|
47 |
+
<h1 class="title is-1 publication-title">🐈 CatVTON: Concatenation Is All You Need for Virtual Try-On with Diffusion Models</h1>
|
48 |
+
<div class="is-size-5 publication-authors">
|
49 |
+
<span class="author-block">
|
50 |
+
<a href="">Zheng Chong</a><sup>1,3</sup>,</span>
|
51 |
+
<span class="author-block">
|
52 |
+
<a href="">Xiao Dong</a><sup>1</sup>,</span>
|
53 |
+
<span class="author-block">
|
54 |
+
<a href="">Haoxiang Li</a><sup>2</sup>,</span>
|
55 |
+
<span class="author-block">
|
56 |
+
<a href="">Shiyue Zhang</a><sup>1</sup>,
|
57 |
+
</span>
|
58 |
+
<span class="author-block">
|
59 |
+
<a href="">Wenqing Zhang</a><sup>1</sup>,
|
60 |
+
</span>
|
61 |
+
<span class="author-block">
|
62 |
+
<a href="">Xujie Zhang</a><sup>1</sup>,
|
63 |
+
</span>
|
64 |
+
<span class="author-block">
|
65 |
+
<a href="">Hanqing Zhao</a><sup>3,4</sup>,
|
66 |
+
</span>
|
67 |
+
<span class="author-block">
|
68 |
+
<a href="">Xiaodan Liang</a><sup>*1,3</sup>,
|
69 |
+
</span>
|
70 |
+
</div>
|
71 |
+
<div class="is-size-5 publication-authors">
|
72 |
+
<span class="author-block"><sup>1</sup>Sun Yat-Sen University,</span>
|
73 |
+
<span class="author-block"><sup>2</sup>Pixocial Technology,</span>
|
74 |
+
<span class="author-block"><sup>3</sup>Peng Cheng Laboratory,</span>
|
75 |
+
<span class="author-block"><sup>4</sup>SIAT</span>
|
76 |
+
|
77 |
+
</div>
|
78 |
+
|
79 |
+
<div class="column has-text-centered">
|
80 |
+
<div class="publication-links">
|
81 |
+
<!-- PDF Link. -->
|
82 |
+
<span class="link-block">
|
83 |
+
<a href="https://arxiv.org/pdf/2407.15886"
|
84 |
+
class="external-link button is-normal is-rounded is-dark">
|
85 |
+
<span class="icon">
|
86 |
+
<i class="fas fa-file-pdf"></i>
|
87 |
+
</span>
|
88 |
+
<span>Paper</span>
|
89 |
+
</a>
|
90 |
+
</span>
|
91 |
+
<!-- Arxiv Link. -->
|
92 |
+
<span class="link-block">
|
93 |
+
<a href="http://arxiv.org/abs/2407.15886"
|
94 |
+
class="external-link button is-normal is-rounded is-dark">
|
95 |
+
<span class="icon">
|
96 |
+
<i class="ai ai-arxiv"></i>
|
97 |
+
</span>
|
98 |
+
<span>arXiv</span>
|
99 |
+
</a>
|
100 |
+
</span>
|
101 |
+
<!-- Demo Link. -->
|
102 |
+
<span class="link-block">
|
103 |
+
<a href="http://120.76.142.206:8888"
|
104 |
+
class="external-link button is-normal is-rounded is-dark">
|
105 |
+
<span class="icon">
|
106 |
+
<i class="fas fa-gamepad"></i>
|
107 |
+
</span>
|
108 |
+
<span>Demo</span>
|
109 |
+
</a>
|
110 |
+
</span>
|
111 |
+
<!-- Demo Link. -->
|
112 |
+
<span class="link-block">
|
113 |
+
<a href="https://huggingface.co/spaces/zhengchong/CatVTON"
|
114 |
+
class="external-link button is-normal is-rounded is-dark">
|
115 |
+
<span class="icon">
|
116 |
+
<i class="fas fa-gamepad"></i>
|
117 |
+
</span>
|
118 |
+
<span>Space</span>
|
119 |
+
</a>
|
120 |
+
</span>
|
121 |
+
<!-- Models Link. -->
|
122 |
+
<span class="link-block">
|
123 |
+
<a href="https://huggingface.co/zhengchong/CatVTON"
|
124 |
+
class="external-link button is-normal is-rounded is-dark">
|
125 |
+
<span class="icon">
|
126 |
+
<i class="fas fa-cube"></i>
|
127 |
+
</span>
|
128 |
+
<span>Models</span>
|
129 |
+
</a>
|
130 |
+
</span>
|
131 |
+
<!-- Code Link. -->
|
132 |
+
<span class="link-block">
|
133 |
+
<a href="https://github.com/Zheng-Chong/CatVTON"
|
134 |
+
class="external-link button is-normal is-rounded is-dark">
|
135 |
+
<span class="icon">
|
136 |
+
<i class="fab fa-github"></i>
|
137 |
+
</span>
|
138 |
+
<span>Code</span>
|
139 |
+
</a>
|
140 |
+
</span>
|
141 |
+
</div>
|
142 |
+
</div>
|
143 |
+
</div>
|
144 |
+
</div>
|
145 |
+
</div>
|
146 |
+
</div>
|
147 |
+
</section>
|
148 |
+
|
149 |
+
<section class="hero teaser">
|
150 |
+
<div class="container is-max-desktop">
|
151 |
+
<div class="hero-body">
|
152 |
+
<img src="resource/img/teaser.jpg" alt="teaser">
|
153 |
+
<p>
|
154 |
+
CatVTON is a simple and efficient virtual try-on diffusion model with 1) Lightweight Network (899.06M parameters totally),
|
155 |
+
2) Parameter-Efficient Training (49.57M parameters trainable) and 3) Simplified Inference (< 8G VRAM for 1024X768
|
156 |
+
resolution).
|
157 |
+
</p>
|
158 |
+
</div>
|
159 |
+
</div>
|
160 |
+
</section>
|
161 |
+
|
162 |
+
<!-- Abstract -->
|
163 |
+
<section class="section">
|
164 |
+
<div class="container is-max-desktop">
|
165 |
+
<!-- Abstract. -->
|
166 |
+
<div class="columns is-centered has-text-centered">
|
167 |
+
<div class="column is-four-fifths">
|
168 |
+
<h2 class="title is-3">Abstract</h2>
|
169 |
+
<div class="content has-text-justified">
|
170 |
+
<p>
|
171 |
+
Virtual try-on methods based on diffusion models achieve realistic try-on effects but replicate the backbone network
|
172 |
+
as a ReferenceNet or leverage additional image encoders to process condition inputs, resulting in high training and
|
173 |
+
inference costs.
|
174 |
+
In this work, we rethink the necessity of ReferenceNet and image encoders and innovate the interaction between garment
|
175 |
+
and person, proposing CatVTON, a simple and efficient virtual try-on diffusion model. It facilitates the seamless
|
176 |
+
transfer of in-shop or worn garments of arbitrary categories to target persons by simply concatenating them in spatial
|
177 |
+
dimensions as inputs. The efficiency of our model is demonstrated in three aspects:
|
178 |
+
|
179 |
+
(1) Lightweight network. Only the original diffusion modules are used, without additional network modules. The text
|
180 |
+
encoder and cross attentions for text injection in the backbone are removed, further reducing the parameters by 167.02M.
|
181 |
+
|
182 |
+
(2) Parameter-efficient training. We identified the try-on relevant modules through experiments and achieved
|
183 |
+
high-quality try-on effects by training only 49.57M parameters (~5.51% of the backbone network’s parameters).
|
184 |
+
|
185 |
+
(3) Simplified inference. CatVTON eliminates all unnecessary conditions and preprocessing steps, including
|
186 |
+
pose estimation, human parsing, and text input, requiring only garment reference, target person image, and mask for
|
187 |
+
the virtual try-on process.
|
188 |
+
|
189 |
+
Extensive experiments demonstrate that CatVTON achieves superior qualitative and
|
190 |
+
quantitative results with fewer prerequisites and trainable parameters than baseline methods. Furthermore,
|
191 |
+
CatVTON shows good generalization in in-the-wild scenarios despite using open-source datasets with only 73K samples.
|
192 |
+
</p>
|
193 |
+
</div>
|
194 |
+
</div>
|
195 |
+
</div>
|
196 |
+
<!--/ Abstract. -->
|
197 |
+
</div>
|
198 |
+
</section>
|
199 |
+
|
200 |
+
|
201 |
+
<section class="section">
|
202 |
+
<div class="container is-max-desktop">
|
203 |
+
<!-- Architecture. -->
|
204 |
+
<div class="columns is-centered">
|
205 |
+
<div class="column is-full-width">
|
206 |
+
<h2 class="title is-3">Architecture</h2>
|
207 |
+
<div class="content has-text-justified">
|
208 |
+
<img src="resource/img/architecture.jpg">
|
209 |
+
<p>
|
210 |
+
Our method achieves the high-quality try-on by simply concatenating the conditional image (garment or reference person)
|
211 |
+
with the target person image in the spatial dimension, ensuring they remain in the same feature space throughout the
|
212 |
+
diffusion process. Only the self-attention parameters, which provide global interaction, are learnable during training.
|
213 |
+
Unnecessary cross-attention for text interaction is omitted, and no additional conditions, such as pose and parsing,
|
214 |
+
are required. These factors result in a lightweight network with minimal trainable parameters and simplified inference.
|
215 |
+
</p>
|
216 |
+
|
217 |
+
</div>
|
218 |
+
</div>
|
219 |
+
</div>
|
220 |
+
<!-- Two Columns -->
|
221 |
+
<div class="columns is-centered">
|
222 |
+
<!-- Visual Effects. -->
|
223 |
+
<div class="column">
|
224 |
+
<div class="content">
|
225 |
+
<h2 class="title is-3">Structure Comparison</h2>
|
226 |
+
<p>
|
227 |
+
We illustrate simple structure comparison of different kinds of try-on methods below. Our approach neither relies on warped garments nor
|
228 |
+
requires the heavy ReferenceNet for additional garment encoding; it only needs simple concatenation of the garment
|
229 |
+
and person images as input to obtain high-quality try-on results.
|
230 |
+
</p>
|
231 |
+
<img src="resource/img/structure.jpg">
|
232 |
+
</div>
|
233 |
+
</div>
|
234 |
+
|
235 |
+
<!-- Efficiency Comparison -->
|
236 |
+
<div class="column">
|
237 |
+
<h2 class="title is-3">Efficiency Comparison</h2>
|
238 |
+
<div class="columns is-centered">
|
239 |
+
<div class="column content">
|
240 |
+
<p>
|
241 |
+
We represent each method by two concentric circles,
|
242 |
+
where the outer circle denotes the total parameters and the inner circle denotes the trainable parameters, with the
|
243 |
+
area proportional to the parameter number. CatVTON achieves lower FID on the VITONHD dataset with fewer total
|
244 |
+
parameters, trainable parameters, and memory usage.
|
245 |
+
</p>
|
246 |
+
<img src="resource/img/efficency.jpg">
|
247 |
+
</div>
|
248 |
+
|
249 |
+
</div>
|
250 |
+
</div>
|
251 |
+
</div>
|
252 |
+
|
253 |
+
<!-- Demo -->
|
254 |
+
<div class="columns is-centered">
|
255 |
+
<div class="column is-full-width">
|
256 |
+
<h2 class="title is-3">Online Demo</h2>
|
257 |
+
<div class="content has-text-justified">
|
258 |
+
<!-- <iframe src="http://120.76.142.206:8888" width="100%" height="700px" frameborder="1/0" name="demo" scrolling="yes/no/auto">
|
259 |
+
</iframe> -->
|
260 |
+
<p>
|
261 |
+
Since GitHub Pages does not support embedded web pages, please jump to our <a href="http://120.76.142.206:8888">Demo </a>.
|
262 |
+
</p>
|
263 |
+
</div>
|
264 |
+
</div>
|
265 |
+
</div>
|
266 |
+
|
267 |
+
<!-- Acknowledgement -->
|
268 |
+
<div class="columns is-centered">
|
269 |
+
<div class="column is-full-width">
|
270 |
+
<h2 class="title is-3">Acknowledgement</h2>
|
271 |
+
<div class="content has-text-justified">
|
272 |
+
<p>
|
273 |
+
Our code is modified based on <a href="https://github.com/huggingface/diffusers">Diffusers</a>.
|
274 |
+
We adopt <a href="https://huggingface.co/runwayml/stable-diffusion-inpainting">Stable Diffusion v1.5 inpainitng</a> as base model.
|
275 |
+
We use <a href="https://github.com/GoGoDuck912/Self-Correction-Human-Parsing/tree/master">SCHP</a>
|
276 |
+
and <a href="https://github.com/facebookresearch/DensePose">DensePose</a> to automatically generate masks in our
|
277 |
+
<a href="https://github.com/gradio-app/gradio">Gradio</a> App.
|
278 |
+
Thanks to all the contributors!
|
279 |
+
</p>
|
280 |
+
</div>
|
281 |
+
</div>
|
282 |
+
</div>
|
283 |
+
<!-- "BibTeX -->
|
284 |
+
|
285 |
+
<div class="container is-max-desktop content">
|
286 |
+
<h2 class="title">BibTeX</h2>
|
287 |
+
<pre><code>
|
288 |
+
@misc{chong2024catvtonconcatenationneedvirtual,
|
289 |
+
title={CatVTON: Concatenation Is All You Need for Virtual Try-On with Diffusion Models},
|
290 |
+
author={Zheng Chong and Xiao Dong and Haoxiang Li and Shiyue Zhang and Wenqing Zhang and Xujie Zhang and Hanqing Zhao and Xiaodan Liang},
|
291 |
+
year={2024},
|
292 |
+
eprint={2407.15886},
|
293 |
+
archivePrefix={arXiv},
|
294 |
+
primaryClass={cs.CV},
|
295 |
+
url={https://arxiv.org/abs/2407.15886},
|
296 |
+
}
|
297 |
+
</code></pre>
|
298 |
+
</div>
|
299 |
+
</div>
|
300 |
+
</section>
|
301 |
+
|
302 |
+
|
303 |
+
|
304 |
+
<footer class="footer">
|
305 |
+
<div class="container">
|
306 |
+
<div class="content has-text-centered">
|
307 |
+
<a class="icon-link" href="http://arxiv.org/abs/2407.15886" class="external-link" disabled>
|
308 |
+
<i class="ai ai-arxiv"></i>
|
309 |
+
</a>
|
310 |
+
<a class="icon-link" href="https://arxiv.org/pdf/2407.15886">
|
311 |
+
<i class="fas fa-file-pdf"></i>
|
312 |
+
</a>
|
313 |
+
<a class="icon-link" href="http://120.76.142.206:8888" class="external-link" disabled>
|
314 |
+
<i class="fas fa-gamepad"></i>
|
315 |
+
</a>
|
316 |
+
<a class="icon-link" href="https://github.com/Zheng-Chong/CatVTON" class="external-link" disabled>
|
317 |
+
<i class="fab fa-github"></i>
|
318 |
+
</a>
|
319 |
+
|
320 |
+
<a class="icon-link" href="https://huggingface.co/zhengchong/CatVTON" class="external-link" disabled>
|
321 |
+
<i class="fas fa-cube"></i>
|
322 |
+
</a>
|
323 |
+
|
324 |
+
</div>
|
325 |
+
<div class="columns is-centered">
|
326 |
+
<div class="column is-8">
|
327 |
+
<div class="content">
|
328 |
+
<p>
|
329 |
+
This website is modified from <a href="https://nerfies.github.io/">Nerfies</a>. Thanks for the great work!
|
330 |
+
Their source code is available on <a href="https://github.com/nerfies/nerfies.github.io">GitHub</a>.
|
331 |
+
</p>
|
332 |
+
</div>
|
333 |
+
</div>
|
334 |
+
</div>
|
335 |
+
</div>
|
336 |
+
</footer>
|
337 |
+
|
338 |
+
</body>
|
339 |
+
</html>
|
inference.py
ADDED
@@ -0,0 +1,327 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import numpy as np
|
3 |
+
import torch
|
4 |
+
import argparse
|
5 |
+
from torch.utils.data import Dataset, DataLoader
|
6 |
+
from diffusers.image_processor import VaeImageProcessor
|
7 |
+
from tqdm import tqdm
|
8 |
+
from PIL import Image, ImageFilter
|
9 |
+
|
10 |
+
from model.pipeline import CatVTONPipeline
|
11 |
+
|
12 |
+
class InferenceDataset(Dataset):
|
13 |
+
def __init__(self, args):
|
14 |
+
self.args = args
|
15 |
+
|
16 |
+
self.vae_processor = VaeImageProcessor(vae_scale_factor=8)
|
17 |
+
self.mask_processor = VaeImageProcessor(vae_scale_factor=8, do_normalize=False, do_binarize=True, do_convert_grayscale=True)
|
18 |
+
self.data = self.load_data()
|
19 |
+
|
20 |
+
def load_data(self):
|
21 |
+
return []
|
22 |
+
|
23 |
+
def __len__(self):
|
24 |
+
return len(self.data)
|
25 |
+
|
26 |
+
def __getitem__(self, idx):
|
27 |
+
data = self.data[idx]
|
28 |
+
person, cloth, mask = [Image.open(data[key]) for key in ['person', 'cloth', 'mask']]
|
29 |
+
return {
|
30 |
+
'index': idx,
|
31 |
+
'person_name': data['person_name'],
|
32 |
+
'person': self.vae_processor.preprocess(person, self.args.height, self.args.width)[0],
|
33 |
+
'cloth': self.vae_processor.preprocess(cloth, self.args.height, self.args.width)[0],
|
34 |
+
'mask': self.mask_processor.preprocess(mask, self.args.height, self.args.width)[0]
|
35 |
+
}
|
36 |
+
|
37 |
+
class VITONHDTestDataset(InferenceDataset):
|
38 |
+
def load_data(self):
|
39 |
+
assert os.path.exists(pair_txt:=os.path.join(self.args.data_root_path, 'test_pairs_unpaired.txt')), f"File {pair_txt} does not exist."
|
40 |
+
with open(pair_txt, 'r') as f:
|
41 |
+
lines = f.readlines()
|
42 |
+
self.args.data_root_path = os.path.join(self.args.data_root_path, "test")
|
43 |
+
output_dir = os.path.join(self.args.output_dir, "vitonhd", 'unpaired' if not self.args.eval_pair else 'paired')
|
44 |
+
data = []
|
45 |
+
for line in lines:
|
46 |
+
person_img, cloth_img = line.strip().split(" ")
|
47 |
+
if os.path.exists(os.path.join(output_dir, person_img)):
|
48 |
+
continue
|
49 |
+
if self.args.eval_pair:
|
50 |
+
cloth_img = person_img
|
51 |
+
data.append({
|
52 |
+
'person_name': person_img,
|
53 |
+
'person': os.path.join(self.args.data_root_path, 'image', person_img),
|
54 |
+
'cloth': os.path.join(self.args.data_root_path, 'cloth', cloth_img),
|
55 |
+
'mask': os.path.join(self.args.data_root_path, 'agnostic-mask', person_img.replace('.jpg', '_mask.png')),
|
56 |
+
})
|
57 |
+
return data
|
58 |
+
|
59 |
+
class DressCodeTestDataset(InferenceDataset):
|
60 |
+
def load_data(self):
|
61 |
+
data = []
|
62 |
+
for sub_folder in ['upper_body', 'lower_body', 'dresses']:
|
63 |
+
assert os.path.exists(os.path.join(self.args.data_root_path, sub_folder)), f"Folder {sub_folder} does not exist."
|
64 |
+
pair_txt = os.path.join(self.args.data_root_path, sub_folder, 'test_pairs_paired.txt' if self.args.eval_pair else 'test_pairs_unpaired.txt')
|
65 |
+
assert os.path.exists(pair_txt), f"File {pair_txt} does not exist."
|
66 |
+
with open(pair_txt, 'r') as f:
|
67 |
+
lines = f.readlines()
|
68 |
+
|
69 |
+
output_dir = os.path.join(self.args.output_dir, f"dresscode-{self.args.height}",
|
70 |
+
'unpaired' if not self.args.eval_pair else 'paired', sub_folder)
|
71 |
+
for line in lines:
|
72 |
+
person_img, cloth_img = line.strip().split(" ")
|
73 |
+
if os.path.exists(os.path.join(output_dir, person_img)):
|
74 |
+
continue
|
75 |
+
data.append({
|
76 |
+
'person_name': os.path.join(sub_folder, person_img),
|
77 |
+
'person': os.path.join(self.args.data_root_path, sub_folder, 'images', person_img),
|
78 |
+
'cloth': os.path.join(self.args.data_root_path, sub_folder, 'images', cloth_img),
|
79 |
+
'mask': os.path.join(self.args.data_root_path, sub_folder, 'agnostic_masks', person_img.replace('.jpg', '.png'))
|
80 |
+
})
|
81 |
+
return data
|
82 |
+
|
83 |
+
|
84 |
+
def parse_args():
|
85 |
+
parser = argparse.ArgumentParser(description="Simple example of a training script.")
|
86 |
+
parser.add_argument(
|
87 |
+
"--base_model_path",
|
88 |
+
type=str,
|
89 |
+
default="runwayml/stable-diffusion-inpainting",
|
90 |
+
help=(
|
91 |
+
"The path to the base model to use for evaluation. This can be a local path or a model identifier from the Model Hub."
|
92 |
+
),
|
93 |
+
)
|
94 |
+
parser.add_argument(
|
95 |
+
"--resume_path",
|
96 |
+
type=str,
|
97 |
+
default="zhengchong/CatVTON",
|
98 |
+
help=(
|
99 |
+
"The Path to the checkpoint of trained tryon model."
|
100 |
+
),
|
101 |
+
)
|
102 |
+
parser.add_argument(
|
103 |
+
"--dataset_name",
|
104 |
+
type=str,
|
105 |
+
required=True,
|
106 |
+
help="The datasets to use for evaluation.",
|
107 |
+
)
|
108 |
+
parser.add_argument(
|
109 |
+
"--data_root_path",
|
110 |
+
type=str,
|
111 |
+
required=True,
|
112 |
+
help="Path to the dataset to evaluate."
|
113 |
+
)
|
114 |
+
parser.add_argument(
|
115 |
+
"--output_dir",
|
116 |
+
type=str,
|
117 |
+
default="output",
|
118 |
+
help="The output directory where the model predictions will be written.",
|
119 |
+
)
|
120 |
+
|
121 |
+
parser.add_argument(
|
122 |
+
"--seed", type=int, default=555, help="A seed for reproducible evaluation."
|
123 |
+
)
|
124 |
+
parser.add_argument(
|
125 |
+
"--batch_size", type=int, default=8, help="The batch size for evaluation."
|
126 |
+
)
|
127 |
+
|
128 |
+
parser.add_argument(
|
129 |
+
"--num_inference_steps",
|
130 |
+
type=int,
|
131 |
+
default=50,
|
132 |
+
help="Number of inference steps to perform.",
|
133 |
+
)
|
134 |
+
parser.add_argument(
|
135 |
+
"--guidance_scale",
|
136 |
+
type=float,
|
137 |
+
default=2.5,
|
138 |
+
help="The scale of classifier-free guidance for inference.",
|
139 |
+
)
|
140 |
+
|
141 |
+
parser.add_argument(
|
142 |
+
"--width",
|
143 |
+
type=int,
|
144 |
+
default=384,
|
145 |
+
help=(
|
146 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
147 |
+
" resolution"
|
148 |
+
),
|
149 |
+
)
|
150 |
+
parser.add_argument(
|
151 |
+
"--height",
|
152 |
+
type=int,
|
153 |
+
default=512,
|
154 |
+
help=(
|
155 |
+
"The resolution for input images, all the images in the train/validation dataset will be resized to this"
|
156 |
+
" resolution"
|
157 |
+
),
|
158 |
+
)
|
159 |
+
parser.add_argument(
|
160 |
+
"--repaint",
|
161 |
+
action="store_true",
|
162 |
+
help="Whether to repaint the result image with the original background."
|
163 |
+
)
|
164 |
+
parser.add_argument(
|
165 |
+
"--eval_pair",
|
166 |
+
action="store_true",
|
167 |
+
help="Whether or not to evaluate the pair.",
|
168 |
+
)
|
169 |
+
parser.add_argument(
|
170 |
+
"--concat_eval_results",
|
171 |
+
action="store_true",
|
172 |
+
help="Whether or not to concatenate the all conditions into one image.",
|
173 |
+
)
|
174 |
+
parser.add_argument(
|
175 |
+
"--allow_tf32",
|
176 |
+
action="store_true",
|
177 |
+
default=True,
|
178 |
+
help=(
|
179 |
+
"Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
|
180 |
+
" https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
|
181 |
+
),
|
182 |
+
)
|
183 |
+
parser.add_argument(
|
184 |
+
"--dataloader_num_workers",
|
185 |
+
type=int,
|
186 |
+
default=8,
|
187 |
+
help=(
|
188 |
+
"Number of subprocesses to use for data loading. 0 means that the data will be loaded in the main process."
|
189 |
+
),
|
190 |
+
)
|
191 |
+
parser.add_argument(
|
192 |
+
"--mixed_precision",
|
193 |
+
type=str,
|
194 |
+
default="bf16",
|
195 |
+
choices=["no", "fp16", "bf16"],
|
196 |
+
help=(
|
197 |
+
"Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
|
198 |
+
" 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
|
199 |
+
" flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
|
200 |
+
),
|
201 |
+
)
|
202 |
+
|
203 |
+
parser.add_argument(
|
204 |
+
"--concat_axis",
|
205 |
+
type=str,
|
206 |
+
choices=["x", "y", 'random'],
|
207 |
+
default="y",
|
208 |
+
help="The axis to concat the cloth feature, select from ['x', 'y', 'random'].",
|
209 |
+
)
|
210 |
+
parser.add_argument(
|
211 |
+
"--enable_condition_noise",
|
212 |
+
action="store_true",
|
213 |
+
default=True,
|
214 |
+
help="Whether or not to enable condition noise.",
|
215 |
+
)
|
216 |
+
|
217 |
+
args = parser.parse_args()
|
218 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
219 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
220 |
+
args.local_rank = env_local_rank
|
221 |
+
|
222 |
+
return args
|
223 |
+
|
224 |
+
|
225 |
+
def repaint(person, mask, result):
|
226 |
+
_, h = result.size
|
227 |
+
kernal_size = h // 50
|
228 |
+
if kernal_size % 2 == 0:
|
229 |
+
kernal_size += 1
|
230 |
+
mask = mask.filter(ImageFilter.GaussianBlur(kernal_size))
|
231 |
+
person_np = np.array(person)
|
232 |
+
result_np = np.array(result)
|
233 |
+
mask_np = np.array(mask) / 255
|
234 |
+
repaint_result = person_np * (1 - mask_np) + result_np * mask_np
|
235 |
+
repaint_result = Image.fromarray(repaint_result.astype(np.uint8))
|
236 |
+
return repaint_result
|
237 |
+
|
238 |
+
def to_pil_image(images):
|
239 |
+
images = (images / 2 + 0.5).clamp(0, 1)
|
240 |
+
images = images.cpu().permute(0, 2, 3, 1).float().numpy()
|
241 |
+
if images.ndim == 3:
|
242 |
+
images = images[None, ...]
|
243 |
+
images = (images * 255).round().astype("uint8")
|
244 |
+
if images.shape[-1] == 1:
|
245 |
+
# special case for grayscale (single channel) images
|
246 |
+
pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
|
247 |
+
else:
|
248 |
+
pil_images = [Image.fromarray(image) for image in images]
|
249 |
+
return pil_images
|
250 |
+
|
251 |
+
@torch.no_grad()
|
252 |
+
def main():
|
253 |
+
args = parse_args()
|
254 |
+
# Pipeline
|
255 |
+
pipeline = CatVTONPipeline(
|
256 |
+
attn_ckpt_version=args.dataset_name,
|
257 |
+
attn_ckpt=args.resume_path,
|
258 |
+
base_ckpt=args.base_model_path,
|
259 |
+
weight_dtype={
|
260 |
+
"no": torch.float32,
|
261 |
+
"fp16": torch.float16,
|
262 |
+
"bf16": torch.bfloat16,
|
263 |
+
}[args.mixed_precision],
|
264 |
+
# device="cuda",
|
265 |
+
device='cpu',
|
266 |
+
skip_safety_check=True
|
267 |
+
)
|
268 |
+
# Dataset
|
269 |
+
if args.dataset_name == "vitonhd":
|
270 |
+
dataset = VITONHDTestDataset(args)
|
271 |
+
elif args.dataset_name == "dresscode":
|
272 |
+
dataset = DressCodeTestDataset(args)
|
273 |
+
else:
|
274 |
+
raise ValueError(f"Invalid dataset name {args.dataset}.")
|
275 |
+
print(f"Dataset {args.dataset_name} loaded, total {len(dataset)} pairs.")
|
276 |
+
dataloader = DataLoader(
|
277 |
+
dataset,
|
278 |
+
batch_size=args.batch_size,
|
279 |
+
shuffle=False,
|
280 |
+
num_workers=args.dataloader_num_workers
|
281 |
+
)
|
282 |
+
# Inference
|
283 |
+
# generator = torch.Generator(device='cuda').manual_seed(args.seed)
|
284 |
+
generator = torch.Generator(device='cpu').manual_seed(args.seed)
|
285 |
+
args.output_dir = os.path.join(args.output_dir, f"{args.dataset_name}-{args.height}", "paired" if args.eval_pair else "unpaired")
|
286 |
+
if not os.path.exists(args.output_dir):
|
287 |
+
os.makedirs(args.output_dir)
|
288 |
+
for batch in tqdm(dataloader):
|
289 |
+
person_images = batch['person']
|
290 |
+
cloth_images = batch['cloth']
|
291 |
+
masks = batch['mask']
|
292 |
+
results = pipeline(
|
293 |
+
person_images,
|
294 |
+
cloth_images,
|
295 |
+
masks,
|
296 |
+
num_inference_steps=args.num_inference_steps,
|
297 |
+
guidance_scale=args.guidance_scale,
|
298 |
+
height=args.height,
|
299 |
+
width=args.width,
|
300 |
+
generator=generator,
|
301 |
+
)
|
302 |
+
|
303 |
+
if args.concat_eval_results or args.repaint:
|
304 |
+
person_images = to_pil_image(person_images)
|
305 |
+
cloth_images = to_pil_image(cloth_images)
|
306 |
+
masks = to_pil_image(masks)
|
307 |
+
for i, result in enumerate(results):
|
308 |
+
person_name = batch['person_name'][i]
|
309 |
+
output_path = os.path.join(args.output_dir, person_name)
|
310 |
+
if not os.path.exists(os.path.dirname(output_path)):
|
311 |
+
os.makedirs(os.path.dirname(output_path))
|
312 |
+
if args.repaint:
|
313 |
+
person_path, mask_path = dataset.data[batch['index'][i]]['person'], dataset.data[batch['index'][i]]['mask']
|
314 |
+
person_image= Image.open(person_path).resize(result.size, Image.LANCZOS)
|
315 |
+
mask = Image.open(mask_path).resize(result.size, Image.NEAREST)
|
316 |
+
result = repaint(person_image, mask, result)
|
317 |
+
if args.concat_eval_results:
|
318 |
+
w, h = result.size
|
319 |
+
concated_result = Image.new('RGB', (w*3, h))
|
320 |
+
concated_result.paste(person_images[i], (0, 0))
|
321 |
+
concated_result.paste(cloth_images[i], (w, 0))
|
322 |
+
concated_result.paste(result, (w*2, 0))
|
323 |
+
result = concated_result
|
324 |
+
result.save(output_path)
|
325 |
+
|
326 |
+
if __name__ == "__main__":
|
327 |
+
main()
|
preprocess_agnostic_mask.py
ADDED
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import argparse
|
2 |
+
import os
|
3 |
+
|
4 |
+
from huggingface_hub import snapshot_download
|
5 |
+
from tqdm import tqdm
|
6 |
+
|
7 |
+
from model.cloth_masker import AutoMasker
|
8 |
+
|
9 |
+
|
10 |
+
def parse_args():
|
11 |
+
parser = argparse.ArgumentParser(description="Simple example of Preprocess Agnostic Mask")
|
12 |
+
parser.add_argument(
|
13 |
+
"--data_root_path",
|
14 |
+
type=str,
|
15 |
+
required=True,
|
16 |
+
help="Path to the dataset to evaluate."
|
17 |
+
)
|
18 |
+
parser.add_argument(
|
19 |
+
"--repo_path",
|
20 |
+
type=str,
|
21 |
+
default="zhengchong/CatVTON",
|
22 |
+
help=(
|
23 |
+
"The Path or repo name of CatVTON. "
|
24 |
+
),
|
25 |
+
)
|
26 |
+
args = parser.parse_args()
|
27 |
+
env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
|
28 |
+
if env_local_rank != -1 and env_local_rank != args.local_rank:
|
29 |
+
args.local_rank = env_local_rank
|
30 |
+
|
31 |
+
return args
|
32 |
+
|
33 |
+
def main(args):
|
34 |
+
args.repo_path = snapshot_download(repo_id=args.repo_path)
|
35 |
+
|
36 |
+
automasker = AutoMasker(
|
37 |
+
densepose_ckpt=os.path.join(args.repo_path, "DensePose"),
|
38 |
+
schp_ckpt=os.path.join(args.repo_path, "SCHP"),
|
39 |
+
# device='cuda',
|
40 |
+
device='cpu',
|
41 |
+
)
|
42 |
+
for sub_folder in ['upper_body', 'lower_body', 'dresses']:
|
43 |
+
assert os.path.exists(os.path.join(args.data_root_path, sub_folder)), f"Folder {sub_folder} does not exist."
|
44 |
+
pair_txt = os.path.join(args.data_root_path, sub_folder, 'test_pairs_paired.txt')
|
45 |
+
assert os.path.exists(pair_txt), f"File {pair_txt} does not exist."
|
46 |
+
cloth_type = {'upper_body': 'upper', 'lower_body': 'lower', 'dresses': 'overall'}[sub_folder]
|
47 |
+
with open(pair_txt, 'r') as f:
|
48 |
+
lines = f.readlines()
|
49 |
+
output_dir = os.path.join(args.data_root_path, sub_folder, 'agnostic_masks')
|
50 |
+
if not os.path.exists(output_dir):
|
51 |
+
os.makedirs(output_dir)
|
52 |
+
for line in tqdm(lines, desc=f"Processing {sub_folder}"):
|
53 |
+
person_img, _ = line.strip().split(" ")
|
54 |
+
if os.path.exists(os.path.join(output_dir, person_img.replace('.jpg', '.png'))):
|
55 |
+
continue
|
56 |
+
mask = automasker(
|
57 |
+
os.path.join(args.data_root_path, sub_folder, 'images', person_img),
|
58 |
+
cloth_type
|
59 |
+
)['mask']
|
60 |
+
mask.save(os.path.join(output_dir, person_img.replace('.jpg', '.png')))
|
61 |
+
|
62 |
+
if __name__ == "__main__":
|
63 |
+
args = parse_args()
|
64 |
+
main(args)
|
65 |
+
|
requirements.txt
ADDED
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
accelerate==0.31.0
|
2 |
+
aiofiles==23.2.1
|
3 |
+
annotated-types==0.7.0
|
4 |
+
antlr4-python3-runtime==4.9.3
|
5 |
+
anyio==4.4.0
|
6 |
+
av==12.3.0
|
7 |
+
certifi==2024.7.4
|
8 |
+
charset-normalizer==3.3.2
|
9 |
+
click==8.1.7
|
10 |
+
cloudpickle==3.0.0
|
11 |
+
contourpy==1.3.0
|
12 |
+
cycler==0.12.1
|
13 |
+
diffusers==0.29.2
|
14 |
+
exceptiongroup==1.2.2
|
15 |
+
fastapi==0.112.2
|
16 |
+
ffmpy==0.4.0
|
17 |
+
filelock==3.15.4
|
18 |
+
fonttools==4.53.1
|
19 |
+
fsspec==2024.6.1
|
20 |
+
fvcore==0.1.5.post20221221
|
21 |
+
gradio==4.41.0
|
22 |
+
gradio_client==1.3.0
|
23 |
+
h11==0.14.0
|
24 |
+
httpcore==1.0.5
|
25 |
+
httpx==0.27.2
|
26 |
+
huggingface-hub==0.23.4
|
27 |
+
idna==3.8
|
28 |
+
imageio==2.35.1
|
29 |
+
importlib_metadata==8.4.0
|
30 |
+
importlib_resources==6.4.4
|
31 |
+
iopath==0.1.10
|
32 |
+
Jinja2==3.1.4
|
33 |
+
kiwisolver==1.4.5
|
34 |
+
lazy_loader==0.4
|
35 |
+
markdown-it-py==3.0.0
|
36 |
+
MarkupSafe==2.1.5
|
37 |
+
matplotlib==3.9.1
|
38 |
+
mdurl==0.1.2
|
39 |
+
mpmath==1.3.0
|
40 |
+
networkx==3.2.1
|
41 |
+
numpy==1.26.4
|
42 |
+
omegaconf==2.3.0
|
43 |
+
opencv-python==4.10.0.84
|
44 |
+
orjson==3.10.7
|
45 |
+
packaging==24.1
|
46 |
+
pandas==2.2.2
|
47 |
+
pillow==10.3.0
|
48 |
+
portalocker==2.10.1
|
49 |
+
psutil==6.0.0
|
50 |
+
pycocotools==2.0.8
|
51 |
+
pydantic==2.8.2
|
52 |
+
pydantic-settings==2.4.0
|
53 |
+
pydantic_core==2.20.1
|
54 |
+
pydub==0.25.1
|
55 |
+
Pygments==2.18.0
|
56 |
+
pyparsing==3.1.4
|
57 |
+
python-dateutil==2.9.0.post0
|
58 |
+
python-dotenv==1.0.1
|
59 |
+
python-multipart==0.0.9
|
60 |
+
pytz==2024.1
|
61 |
+
PyYAML==6.0.1
|
62 |
+
regex==2024.7.24
|
63 |
+
requests==2.32.3
|
64 |
+
rich==13.8.0
|
65 |
+
ruff==0.6.2
|
66 |
+
safetensors==0.4.4
|
67 |
+
scikit-image==0.24.0
|
68 |
+
scipy==1.13.1
|
69 |
+
semantic-version==2.10.0
|
70 |
+
shellingham==1.5.4
|
71 |
+
six==1.16.0
|
72 |
+
sniffio==1.3.1
|
73 |
+
starlette==0.38.2
|
74 |
+
sympy==1.13.2
|
75 |
+
tabulate==0.9.0
|
76 |
+
termcolor==2.4.0
|
77 |
+
tifffile==2024.8.28
|
78 |
+
tokenizers==0.13.3
|
79 |
+
tomlkit==0.12.0
|
80 |
+
torch==2.1.2
|
81 |
+
torchvision==0.16.2
|
82 |
+
tqdm==4.66.4
|
83 |
+
transformers==4.27.3
|
84 |
+
typer==0.12.5
|
85 |
+
typing_extensions==4.12.2
|
86 |
+
tzdata==2024.1
|
87 |
+
urllib3==2.2.2
|
88 |
+
uvicorn==0.30.6
|
89 |
+
websockets==12.0
|
90 |
+
yacs==0.1.8
|
91 |
+
zipp==3.20.1
|
simplified.py
ADDED
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python3
|
2 |
+
# -*- coding: utf-8 -*-
|
3 |
+
"""
|
4 |
+
__author__ = 'Ahmad Abdulnasir Shuaib <[email protected]>'
|
5 |
+
__homepage__ = https://ahmadabdulnasir.com.ng
|
6 |
+
__copyright__ = 'Copyright (c) 2024, salafi'
|
7 |
+
__version__ = "0.01t"
|
8 |
+
"""
|
9 |
+
import gradio as gr
|
10 |
+
|
11 |
+
from PIL import Image
|
12 |
+
|
13 |
+
def change_clothes(person_img, shirt_img=None, trouser_img=None):
|
14 |
+
person = Image.open(person_img).convert("RGBA") # Ensure person image has an alpha channel
|
15 |
+
if shirt_img:
|
16 |
+
shirt = Image.open(shirt_img).convert("RGBA").resize((person.width, int(person.height * 0.5)))
|
17 |
+
person.paste(shirt, (0, 0), shirt) # Paste shirt with transparency
|
18 |
+
if trouser_img:
|
19 |
+
trouser = Image.open(trouser_img).convert("RGBA").resize((person.width, int(person.height * 0.5)))
|
20 |
+
person.paste(trouser, (0, int(person.height * 0.5)), trouser) # Paste trouser with transparency
|
21 |
+
return person
|
22 |
+
|
23 |
+
def run():
|
24 |
+
iface = gr.Interface(
|
25 |
+
fn=change_clothes,
|
26 |
+
inputs=[
|
27 |
+
gr.Image(type="filepath", label="Upload Person Image"),
|
28 |
+
gr.Image(type="filepath", label="Upload Shirt Image", ),
|
29 |
+
gr.Image(type="filepath", label="Upload Trouser Image", ),
|
30 |
+
],
|
31 |
+
outputs="image",
|
32 |
+
title="Clothes Change Interface"
|
33 |
+
)
|
34 |
+
|
35 |
+
iface.launch(show_error=True )
|
36 |
+
|
37 |
+
|
38 |
+
def boot():
|
39 |
+
run()
|
40 |
+
|
41 |
+
if __name__ == "__main__":
|
42 |
+
boot()
|
utils.py
ADDED
@@ -0,0 +1,508 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
|
3 |
+
import math
|
4 |
+
import PIL
|
5 |
+
import numpy as np
|
6 |
+
import torch
|
7 |
+
from PIL import Image
|
8 |
+
from accelerate.state import AcceleratorState
|
9 |
+
from packaging import version
|
10 |
+
import accelerate
|
11 |
+
from typing import List, Optional, Tuple, Set
|
12 |
+
from diffusers import UNet2DConditionModel, SchedulerMixin
|
13 |
+
from tqdm import tqdm
|
14 |
+
|
15 |
+
|
16 |
+
# Compute DREAM and update latents for diffusion sampling
|
17 |
+
def compute_dream_and_update_latents_for_inpaint(
|
18 |
+
unet: UNet2DConditionModel,
|
19 |
+
noise_scheduler: SchedulerMixin,
|
20 |
+
timesteps: torch.Tensor,
|
21 |
+
noise: torch.Tensor,
|
22 |
+
noisy_latents: torch.Tensor,
|
23 |
+
target: torch.Tensor,
|
24 |
+
encoder_hidden_states: torch.Tensor,
|
25 |
+
dream_detail_preservation: float = 1.0,
|
26 |
+
) -> Tuple[Optional[torch.Tensor], Optional[torch.Tensor]]:
|
27 |
+
"""
|
28 |
+
Implements "DREAM (Diffusion Rectification and Estimation-Adaptive Models)" from http://arxiv.org/abs/2312.00210.
|
29 |
+
DREAM helps align training with sampling to help training be more efficient and accurate at the cost of an extra
|
30 |
+
forward step without gradients.
|
31 |
+
|
32 |
+
Args:
|
33 |
+
`unet`: The state unet to use to make a prediction.
|
34 |
+
`noise_scheduler`: The noise scheduler used to add noise for the given timestep.
|
35 |
+
`timesteps`: The timesteps for the noise_scheduler to user.
|
36 |
+
`noise`: A tensor of noise in the shape of noisy_latents.
|
37 |
+
`noisy_latents`: Previously noise latents from the training loop.
|
38 |
+
`target`: The ground-truth tensor to predict after eps is removed.
|
39 |
+
`encoder_hidden_states`: Text embeddings from the text model.
|
40 |
+
`dream_detail_preservation`: A float value that indicates detail preservation level.
|
41 |
+
See reference.
|
42 |
+
|
43 |
+
Returns:
|
44 |
+
`tuple[torch.Tensor, torch.Tensor]`: Adjusted noisy_latents and target.
|
45 |
+
"""
|
46 |
+
alphas_cumprod = noise_scheduler.alphas_cumprod.to(timesteps.device)[timesteps, None, None, None]
|
47 |
+
sqrt_one_minus_alphas_cumprod = (1.0 - alphas_cumprod) ** 0.5
|
48 |
+
|
49 |
+
# The paper uses lambda = sqrt(1 - alpha) ** p, with p = 1 in their experiments.
|
50 |
+
dream_lambda = sqrt_one_minus_alphas_cumprod**dream_detail_preservation
|
51 |
+
|
52 |
+
pred = None # b, 4, h, w
|
53 |
+
with torch.no_grad():
|
54 |
+
pred = unet(noisy_latents, timesteps, encoder_hidden_states).sample
|
55 |
+
|
56 |
+
noisy_latents_no_condition = noisy_latents[:, :4]
|
57 |
+
_noisy_latents, _target = (None, None)
|
58 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
59 |
+
predicted_noise = pred
|
60 |
+
delta_noise = (noise - predicted_noise).detach()
|
61 |
+
delta_noise.mul_(dream_lambda)
|
62 |
+
_noisy_latents = noisy_latents_no_condition.add(sqrt_one_minus_alphas_cumprod * delta_noise)
|
63 |
+
_target = target.add(delta_noise)
|
64 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
65 |
+
raise NotImplementedError("DREAM has not been implemented for v-prediction")
|
66 |
+
else:
|
67 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
68 |
+
|
69 |
+
_noisy_latents = torch.cat([_noisy_latents, noisy_latents[:, 4:]], dim=1)
|
70 |
+
return _noisy_latents, _target
|
71 |
+
|
72 |
+
# Prepare the input for inpainting model.
|
73 |
+
def prepare_inpainting_input(
|
74 |
+
noisy_latents: torch.Tensor,
|
75 |
+
mask_latents: torch.Tensor,
|
76 |
+
condition_latents: torch.Tensor,
|
77 |
+
enable_condition_noise: bool = True,
|
78 |
+
condition_concat_dim: int = -1,
|
79 |
+
) -> torch.Tensor:
|
80 |
+
"""
|
81 |
+
Prepare the input for inpainting model.
|
82 |
+
|
83 |
+
Args:
|
84 |
+
noisy_latents (torch.Tensor): Noisy latents.
|
85 |
+
mask_latents (torch.Tensor): Mask latents.
|
86 |
+
condition_latents (torch.Tensor): Condition latents.
|
87 |
+
enable_condition_noise (bool): Enable condition noise.
|
88 |
+
|
89 |
+
Returns:
|
90 |
+
torch.Tensor: Inpainting input.
|
91 |
+
"""
|
92 |
+
if not enable_condition_noise:
|
93 |
+
condition_latents_ = condition_latents.chunk(2, dim=condition_concat_dim)[-1]
|
94 |
+
noisy_latents = torch.cat([noisy_latents, condition_latents_], dim=condition_concat_dim)
|
95 |
+
noisy_latents = torch.cat([noisy_latents, mask_latents, condition_latents], dim=1)
|
96 |
+
return noisy_latents
|
97 |
+
|
98 |
+
# Compute VAE encodings
|
99 |
+
def compute_vae_encodings(image: torch.Tensor, vae: torch.nn.Module) -> torch.Tensor:
|
100 |
+
"""
|
101 |
+
Args:
|
102 |
+
images (torch.Tensor): image to be encoded
|
103 |
+
vae (torch.nn.Module): vae model
|
104 |
+
|
105 |
+
Returns:
|
106 |
+
torch.Tensor: latent encoding of the image
|
107 |
+
"""
|
108 |
+
pixel_values = image.to(memory_format=torch.contiguous_format).float()
|
109 |
+
pixel_values = pixel_values.to(vae.device, dtype=vae.dtype)
|
110 |
+
with torch.no_grad():
|
111 |
+
model_input = vae.encode(pixel_values).latent_dist.sample()
|
112 |
+
model_input = model_input * vae.config.scaling_factor
|
113 |
+
return model_input
|
114 |
+
|
115 |
+
|
116 |
+
# Init Accelerator
|
117 |
+
from accelerate import Accelerator, DistributedDataParallelKwargs
|
118 |
+
from accelerate.utils import ProjectConfiguration
|
119 |
+
|
120 |
+
def init_accelerator(config):
|
121 |
+
accelerator_project_config = ProjectConfiguration(
|
122 |
+
project_dir=config.project_name,
|
123 |
+
logging_dir=os.path.join(config.project_name, "logs"),
|
124 |
+
)
|
125 |
+
accelerator_ddp_config = DistributedDataParallelKwargs(find_unused_parameters=True)
|
126 |
+
accelerator = Accelerator(
|
127 |
+
mixed_precision=config.mixed_precision,
|
128 |
+
log_with=config.report_to,
|
129 |
+
project_config=accelerator_project_config,
|
130 |
+
kwargs_handlers=[accelerator_ddp_config],
|
131 |
+
gradient_accumulation_steps=config.gradient_accumulation_steps,
|
132 |
+
)
|
133 |
+
# Disable AMP for MPS.
|
134 |
+
if torch.backends.mps.is_available():
|
135 |
+
accelerator.native_amp = False
|
136 |
+
|
137 |
+
if accelerator.is_main_process:
|
138 |
+
accelerator.init_trackers(
|
139 |
+
project_name=config.project_name,
|
140 |
+
config={
|
141 |
+
"learning_rate": config.learning_rate,
|
142 |
+
"train_batch_size": config.train_batch_size,
|
143 |
+
"image_size": f"{config.width}x{config.height}",
|
144 |
+
},
|
145 |
+
)
|
146 |
+
|
147 |
+
return accelerator
|
148 |
+
|
149 |
+
|
150 |
+
def init_weight_dtype(wight_dtype):
|
151 |
+
return {
|
152 |
+
"no": torch.float32,
|
153 |
+
"fp16": torch.float16,
|
154 |
+
"bf16": torch.bfloat16,
|
155 |
+
}[wight_dtype]
|
156 |
+
|
157 |
+
|
158 |
+
def init_add_item_id(config):
|
159 |
+
return torch.tensor(
|
160 |
+
[
|
161 |
+
config.height,
|
162 |
+
config.width * 2,
|
163 |
+
0,
|
164 |
+
0,
|
165 |
+
config.height,
|
166 |
+
config.width * 2,
|
167 |
+
]
|
168 |
+
).repeat(config.train_batch_size, 1)
|
169 |
+
|
170 |
+
|
171 |
+
def prepare_eval_data(dataset_root, dataset_name, is_pair=True):
|
172 |
+
assert dataset_name in ["vitonhd", "dresscode", "farfetch"], "Unknown dataset name {}.".format(dataset_name)
|
173 |
+
if dataset_name == "vitonhd":
|
174 |
+
data_root = os.path.join(dataset_root, "VITONHD-1024", "test")
|
175 |
+
if is_pair:
|
176 |
+
keys = os.listdir(os.path.join(data_root, "Images"))
|
177 |
+
cloth_image_paths = [
|
178 |
+
os.path.join(data_root, "Images", key, key + "-0.jpg") for key in keys
|
179 |
+
]
|
180 |
+
person_image_paths = [
|
181 |
+
os.path.join(data_root, "Images", key, key + "-1.jpg") for key in keys
|
182 |
+
]
|
183 |
+
else:
|
184 |
+
# read ../test_pairs.txt
|
185 |
+
cloth_image_paths = []
|
186 |
+
person_image_paths = []
|
187 |
+
with open(
|
188 |
+
os.path.join(dataset_root, "VITONHD-1024", "test_pairs.txt"), "r"
|
189 |
+
) as f:
|
190 |
+
lines = f.readlines()
|
191 |
+
for line in lines:
|
192 |
+
cloth_image, person_image = (
|
193 |
+
line.replace(".jpg", "").strip().split(" ")
|
194 |
+
)
|
195 |
+
cloth_image_paths.append(
|
196 |
+
os.path.join(
|
197 |
+
data_root, "Images", cloth_image, cloth_image + "-0.jpg"
|
198 |
+
)
|
199 |
+
)
|
200 |
+
person_image_paths.append(
|
201 |
+
os.path.join(
|
202 |
+
data_root, "Images", person_image, person_image + "-1.jpg"
|
203 |
+
)
|
204 |
+
)
|
205 |
+
elif dataset_name == "dresscode":
|
206 |
+
data_root = os.path.join(dataset_root, "DressCode-1024")
|
207 |
+
if is_pair:
|
208 |
+
part = ["lower", "lower", "upper", "upper", "dresses", "dresses"]
|
209 |
+
ids = ["013581", "051685", "000190", "050072", "020829", "053742"]
|
210 |
+
cloth_image_paths = [
|
211 |
+
os.path.join(data_root, "Images", part[i], ids[i], ids[i] + "_1.jpg")
|
212 |
+
for i in range(len(part))
|
213 |
+
]
|
214 |
+
person_image_paths = [
|
215 |
+
os.path.join(data_root, "Images", part[i], ids[i], ids[i] + "_0.jpg")
|
216 |
+
for i in range(len(part))
|
217 |
+
]
|
218 |
+
else:
|
219 |
+
raise ValueError("DressCode dataset does not support non-pair evaluation.")
|
220 |
+
elif dataset_name == "farfetch":
|
221 |
+
data_root = os.path.join(dataset_root, "FARFETCH-1024")
|
222 |
+
cloth_image_paths = [
|
223 |
+
# TryOn
|
224 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/women/Tops/Blouses/13732751/13732751-2.jpg",
|
225 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/women/Tops/Hoodies/14661627/14661627-4.jpg",
|
226 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/women/Tops/Vests & Tank Tops/16532697/16532697-4.jpg",
|
227 |
+
"Images/men/Pants/Loose Fit Pants/14750720/14750720-6.jpg",
|
228 |
+
# Garment Transfer
|
229 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/women/Tops/Shirts/10889688/10889688-3.jpg",
|
230 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/women/Shorts/Leather & Faux Leather Shorts/20143338/20143338-1.jpg",
|
231 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/women/Jackets/Blazers/15541224/15541224-2.jpg",
|
232 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/men/Polo Shirts/Polo Shirts/17652415/17652415-0.jpg"
|
233 |
+
|
234 |
+
# "Images/men/Jackets/Hooded Jackets/12550261/12550261-1.jpg",
|
235 |
+
# "Images/men/Shirts/Shirts/15614589/15614589-4.jpg",
|
236 |
+
# "Images/women/Dresses/Day Dresses/10372515/10372515-3.jpg",
|
237 |
+
# "Images/women/Dresses/Sundresses/18520992/18520992-4.jpg",
|
238 |
+
# "Images/women/Skirts/Asymmetric & Draped Skirts/12404908/12404908-2.jpg",
|
239 |
+
]
|
240 |
+
person_image_paths = [
|
241 |
+
# TryOn
|
242 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/women/Tops/Blouses/13732751/13732751-0.jpg",
|
243 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/women/Tops/Hoodies/14661627/14661627-2.jpg",
|
244 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/women/Tops/Vests & Tank Tops/16532697/16532697-1.jpg",
|
245 |
+
"Images/men/Pants/Loose Fit Pants/14750720/14750720-5.jpg",
|
246 |
+
# Garment Transfer
|
247 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/women/Tops/Shirts/10889688/10889688-1.jpg",
|
248 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/women/Shorts/Leather & Faux Leather Shorts/20143338/20143338-2.jpg",
|
249 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/women/Jackets/Blazers/15541224/15541224-0.jpg",
|
250 |
+
"/home/chongzheng/Projects/hivton/Datasets/FARFETCH-1024/Images/men/Polo Shirts/Polo Shirts/17652415/17652415-4.jpg",
|
251 |
+
|
252 |
+
# "Images/men/Jackets/Hooded Jackets/12550261/12550261-3.jpg",
|
253 |
+
# "Images/men/Shirts/Shirts/15614589/15614589-3.jpg",
|
254 |
+
# "Images/women/Dresses/Day Dresses/10372515/10372515-0.jpg",
|
255 |
+
# "Images/women/Dresses/Sundresses/18520992/18520992-1.jpg",
|
256 |
+
# "Images/women/Skirts/Asymmetric & Draped Skirts/12404908/12404908-1.jpg",
|
257 |
+
]
|
258 |
+
cloth_image_paths = [
|
259 |
+
os.path.join(data_root, path) for path in cloth_image_paths
|
260 |
+
]
|
261 |
+
person_image_paths = [
|
262 |
+
os.path.join(data_root, path) for path in person_image_paths
|
263 |
+
]
|
264 |
+
else:
|
265 |
+
raise ValueError(f"Unknown dataset name: {dataset_name}")
|
266 |
+
|
267 |
+
samples = [
|
268 |
+
{
|
269 |
+
"folder": os.path.basename(os.path.dirname(cloth_image)),
|
270 |
+
"cloth": cloth_image,
|
271 |
+
"person": person_image,
|
272 |
+
}
|
273 |
+
for cloth_image, person_image in zip(
|
274 |
+
cloth_image_paths, person_image_paths
|
275 |
+
)
|
276 |
+
]
|
277 |
+
return samples
|
278 |
+
|
279 |
+
|
280 |
+
def repaint_result(result, person_image, mask_image):
|
281 |
+
result, person, mask = np.array(result), np.array(person_image), np.array(mask_image)
|
282 |
+
# expand the mask to 3 channels & to 0~1
|
283 |
+
mask = np.expand_dims(mask, axis=2)
|
284 |
+
mask = mask / 255.0
|
285 |
+
# mask for result, ~mask for person
|
286 |
+
result_ = result * mask + person * (1 - mask)
|
287 |
+
return Image.fromarray(result_.astype(np.uint8))
|
288 |
+
|
289 |
+
|
290 |
+
def prepare_image(image):
|
291 |
+
if isinstance(image, torch.Tensor):
|
292 |
+
# Batch single image
|
293 |
+
if image.ndim == 3:
|
294 |
+
image = image.unsqueeze(0)
|
295 |
+
image = image.to(dtype=torch.float32)
|
296 |
+
else:
|
297 |
+
# preprocess image
|
298 |
+
if isinstance(image, (PIL.Image.Image, np.ndarray)):
|
299 |
+
image = [image]
|
300 |
+
if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
|
301 |
+
image = [np.array(i.convert("RGB"))[None, :] for i in image]
|
302 |
+
image = np.concatenate(image, axis=0)
|
303 |
+
elif isinstance(image, list) and isinstance(image[0], np.ndarray):
|
304 |
+
image = np.concatenate([i[None, :] for i in image], axis=0)
|
305 |
+
image = image.transpose(0, 3, 1, 2)
|
306 |
+
image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
|
307 |
+
return image
|
308 |
+
|
309 |
+
|
310 |
+
def prepare_mask_image(mask_image):
|
311 |
+
if isinstance(mask_image, torch.Tensor):
|
312 |
+
if mask_image.ndim == 2:
|
313 |
+
# Batch and add channel dim for single mask
|
314 |
+
mask_image = mask_image.unsqueeze(0).unsqueeze(0)
|
315 |
+
elif mask_image.ndim == 3 and mask_image.shape[0] == 1:
|
316 |
+
# Single mask, the 0'th dimension is considered to be
|
317 |
+
# the existing batch size of 1
|
318 |
+
mask_image = mask_image.unsqueeze(0)
|
319 |
+
elif mask_image.ndim == 3 and mask_image.shape[0] != 1:
|
320 |
+
# Batch of mask, the 0'th dimension is considered to be
|
321 |
+
# the batching dimension
|
322 |
+
mask_image = mask_image.unsqueeze(1)
|
323 |
+
|
324 |
+
# Binarize mask
|
325 |
+
mask_image[mask_image < 0.5] = 0
|
326 |
+
mask_image[mask_image >= 0.5] = 1
|
327 |
+
else:
|
328 |
+
# preprocess mask
|
329 |
+
if isinstance(mask_image, (PIL.Image.Image, np.ndarray)):
|
330 |
+
mask_image = [mask_image]
|
331 |
+
|
332 |
+
if isinstance(mask_image, list) and isinstance(mask_image[0], PIL.Image.Image):
|
333 |
+
mask_image = np.concatenate(
|
334 |
+
[np.array(m.convert("L"))[None, None, :] for m in mask_image], axis=0
|
335 |
+
)
|
336 |
+
mask_image = mask_image.astype(np.float32) / 255.0
|
337 |
+
elif isinstance(mask_image, list) and isinstance(mask_image[0], np.ndarray):
|
338 |
+
mask_image = np.concatenate([m[None, None, :] for m in mask_image], axis=0)
|
339 |
+
|
340 |
+
mask_image[mask_image < 0.5] = 0
|
341 |
+
mask_image[mask_image >= 0.5] = 1
|
342 |
+
mask_image = torch.from_numpy(mask_image)
|
343 |
+
|
344 |
+
return mask_image
|
345 |
+
|
346 |
+
|
347 |
+
def numpy_to_pil(images):
|
348 |
+
"""
|
349 |
+
Convert a numpy image or a batch of images to a PIL image.
|
350 |
+
"""
|
351 |
+
if images.ndim == 3:
|
352 |
+
images = images[None, ...]
|
353 |
+
images = (images * 255).round().astype("uint8")
|
354 |
+
if images.shape[-1] == 1:
|
355 |
+
# special case for grayscale (single channel) images
|
356 |
+
pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
|
357 |
+
else:
|
358 |
+
pil_images = [Image.fromarray(image) for image in images]
|
359 |
+
|
360 |
+
return pil_images
|
361 |
+
|
362 |
+
|
363 |
+
def tensor_to_image(tensor: torch.Tensor):
|
364 |
+
"""
|
365 |
+
Converts a torch tensor to PIL Image.
|
366 |
+
"""
|
367 |
+
assert tensor.dim() == 3, "Input tensor should be 3-dimensional."
|
368 |
+
assert tensor.dtype == torch.float32, "Input tensor should be float32."
|
369 |
+
assert (
|
370 |
+
tensor.min() >= 0 and tensor.max() <= 1
|
371 |
+
), "Input tensor should be in range [0, 1]."
|
372 |
+
tensor = tensor.cpu()
|
373 |
+
tensor = tensor * 255
|
374 |
+
tensor = tensor.permute(1, 2, 0)
|
375 |
+
tensor = tensor.numpy().astype(np.uint8)
|
376 |
+
image = Image.fromarray(tensor)
|
377 |
+
return image
|
378 |
+
|
379 |
+
|
380 |
+
def concat_images(images: List[Image.Image], divider: int = 4, cols: int = 4):
|
381 |
+
"""
|
382 |
+
Concatenates images horizontally and with
|
383 |
+
"""
|
384 |
+
widths = [image.size[0] for image in images]
|
385 |
+
heights = [image.size[1] for image in images]
|
386 |
+
total_width = cols * max(widths)
|
387 |
+
total_width += divider * (cols - 1)
|
388 |
+
# `col` images each row
|
389 |
+
rows = math.ceil(len(images) / cols)
|
390 |
+
total_height = max(heights) * rows
|
391 |
+
# add divider between rows
|
392 |
+
total_height += divider * (len(heights) // cols - 1)
|
393 |
+
|
394 |
+
# all black image
|
395 |
+
concat_image = Image.new("RGB", (total_width, total_height), (0, 0, 0))
|
396 |
+
|
397 |
+
x_offset = 0
|
398 |
+
y_offset = 0
|
399 |
+
for i, image in enumerate(images):
|
400 |
+
concat_image.paste(image, (x_offset, y_offset))
|
401 |
+
x_offset += image.size[0] + divider
|
402 |
+
if (i + 1) % cols == 0:
|
403 |
+
x_offset = 0
|
404 |
+
y_offset += image.size[1] + divider
|
405 |
+
|
406 |
+
return concat_image
|
407 |
+
|
408 |
+
|
409 |
+
def read_prompt_file(prompt_file: str):
|
410 |
+
if prompt_file is not None and os.path.isfile(prompt_file):
|
411 |
+
with open(prompt_file, "r") as sample_prompt_file:
|
412 |
+
sample_prompts = sample_prompt_file.readlines()
|
413 |
+
sample_prompts = [sample_prompt.strip() for sample_prompt in sample_prompts]
|
414 |
+
else:
|
415 |
+
sample_prompts = []
|
416 |
+
return sample_prompts
|
417 |
+
|
418 |
+
|
419 |
+
def save_tensors_to_npz(tensors: torch.Tensor, paths: List[str]):
|
420 |
+
assert len(tensors) == len(paths), "Length of tensors and paths should be the same!"
|
421 |
+
for tensor, path in zip(tensors, paths):
|
422 |
+
np.savez_compressed(path, latent=tensor.cpu().numpy())
|
423 |
+
|
424 |
+
|
425 |
+
def deepspeed_zero_init_disabled_context_manager():
|
426 |
+
"""
|
427 |
+
returns either a context list that includes one that will disable zero.Init or an empty context list
|
428 |
+
"""
|
429 |
+
deepspeed_plugin = (
|
430 |
+
AcceleratorState().deepspeed_plugin
|
431 |
+
if accelerate.state.is_initialized()
|
432 |
+
else None
|
433 |
+
)
|
434 |
+
if deepspeed_plugin is None:
|
435 |
+
return []
|
436 |
+
|
437 |
+
return [deepspeed_plugin.zero3_init_context_manager(enable=False)]
|
438 |
+
|
439 |
+
|
440 |
+
def is_xformers_available():
|
441 |
+
try:
|
442 |
+
import xformers
|
443 |
+
|
444 |
+
xformers_version = version.parse(xformers.__version__)
|
445 |
+
if xformers_version == version.parse("0.0.16"):
|
446 |
+
print(
|
447 |
+
"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, "
|
448 |
+
"please update xFormers to at least 0.0.17. "
|
449 |
+
"See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
|
450 |
+
)
|
451 |
+
return True
|
452 |
+
except ImportError:
|
453 |
+
raise ValueError(
|
454 |
+
"xformers is not available. Make sure it is installed correctly"
|
455 |
+
)
|
456 |
+
|
457 |
+
|
458 |
+
|
459 |
+
def resize_and_crop(image, size):
|
460 |
+
# Crop to size ratio
|
461 |
+
w, h = image.size
|
462 |
+
target_w, target_h = size
|
463 |
+
if w / h < target_w / target_h:
|
464 |
+
new_w = w
|
465 |
+
new_h = w * target_h // target_w
|
466 |
+
else:
|
467 |
+
new_h = h
|
468 |
+
new_w = h * target_w // target_h
|
469 |
+
image = image.crop(
|
470 |
+
((w - new_w) // 2, (h - new_h) // 2, (w + new_w) // 2, (h + new_h) // 2)
|
471 |
+
)
|
472 |
+
# resize
|
473 |
+
image = image.resize(size, Image.LANCZOS)
|
474 |
+
return image
|
475 |
+
|
476 |
+
|
477 |
+
def resize_and_padding(image, size):
|
478 |
+
# Padding to size ratio
|
479 |
+
w, h = image.size
|
480 |
+
target_w, target_h = size
|
481 |
+
if w / h < target_w / target_h:
|
482 |
+
new_h = target_h
|
483 |
+
new_w = w * target_h // h
|
484 |
+
else:
|
485 |
+
new_w = target_w
|
486 |
+
new_h = h * target_w // w
|
487 |
+
image = image.resize((new_w, new_h), Image.LANCZOS)
|
488 |
+
# padding
|
489 |
+
padding = Image.new("RGB", size, (255, 255, 255))
|
490 |
+
padding.paste(image, ((target_w - new_w) // 2, (target_h - new_h) // 2))
|
491 |
+
return padding
|
492 |
+
|
493 |
+
|
494 |
+
def scan_files_in_dir(directory, postfix: Set[str] = None, progress_bar: tqdm = None) -> list:
|
495 |
+
file_list = []
|
496 |
+
progress_bar = tqdm(total=0, desc=f"Scanning", ncols=100) if progress_bar is None else progress_bar
|
497 |
+
for entry in os.scandir(directory):
|
498 |
+
if entry.is_file():
|
499 |
+
if postfix is None or os.path.splitext(entry.path)[1] in postfix:
|
500 |
+
file_list.append(entry)
|
501 |
+
progress_bar.total += 1
|
502 |
+
progress_bar.update(1)
|
503 |
+
elif entry.is_dir():
|
504 |
+
file_list += scan_files_in_dir(entry.path, postfix=postfix, progress_bar=progress_bar)
|
505 |
+
return file_list
|
506 |
+
|
507 |
+
if __name__ == "__main__":
|
508 |
+
...
|