SaadAhmedSiddiqui commited on
Commit
b97f7c1
·
verified ·
1 Parent(s): 8cc931a

Upload 11 files

Browse files
Files changed (11) hide show
  1. .gitignore +14 -0
  2. LICENSE +107 -0
  3. README.md +184 -13
  4. app.py +368 -7
  5. app_p2p.py +567 -0
  6. eval.py +158 -0
  7. index.html +339 -0
  8. inference.py +325 -0
  9. preprocess_agnostic_mask.py +64 -0
  10. requirements.txt +21 -0
  11. utils.py +399 -0
.gitignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ model/__pycache__
3
+ model/DensePose/__pycache__
4
+ model/SCHP/__pycache__
5
+ model/SCHP/*/__pycache__
6
+ resource/demo/output
7
+ resource/demo/example/.DS_Store
8
+ Models
9
+ Datasets
10
+ densepose_
11
+ .vscode
12
+ playground.py
13
+ output
14
+ model/cloth_masker_segformer.py
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,13 +1,184 @@
1
- ---
2
- title: 27 Dec CatVTON
3
- emoji: 📉
4
- colorFrom: red
5
- colorTo: gray
6
- sdk: gradio
7
- sdk_version: 5.9.1
8
- app_file: app.py
9
- pinned: false
10
- short_description: VTON model using a pre-trained model CatVTON.
11
- ---
12
-
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🐈 CatVTON: Concatenation Is All You Need for Virtual Try-On with Diffusion Models
2
+
3
+ <div style="display: flex; justify-content: center; align-items: center;">
4
+ <a href="http://arxiv.org/abs/2407.15886" style="margin: 0 2px;">
5
+ <img src='https://img.shields.io/badge/arXiv-2407.15886-red?style=flat&logo=arXiv&logoColor=red' alt='arxiv'>
6
+ </a>
7
+ <a href='https://huggingface.co/zhengchong/CatVTON' style="margin: 0 2px;">
8
+ <img src='https://img.shields.io/badge/Hugging Face-ckpts-orange?style=flat&logo=HuggingFace&logoColor=orange' alt='huggingface'>
9
+ </a>
10
+ <a href="https://github.com/Zheng-Chong/CatVTON" style="margin: 0 2px;">
11
+ <img src='https://img.shields.io/badge/GitHub-Repo-blue?style=flat&logo=GitHub' alt='GitHub'>
12
+ </a>
13
+ <a href="https://huggingface.co/spaces/zhengchong/CatVTON" style="margin: 0 2px;">
14
+ <img src='https://img.shields.io/badge/Demo-Gradio-gold?style=flat&logo=Gradio&logoColor=red' alt='Demo'>
15
+ </a>
16
+ <a href="https://huggingface.co/spaces/zhengchong/CatVTON" style="margin: 0 2px;">
17
+ <img src='https://img.shields.io/badge/Space-ZeroGPU-orange?style=flat&logo=Gradio&logoColor=red' alt='Demo'>
18
+ </a>
19
+ <a href='https://zheng-chong.github.io/CatVTON/' style="margin: 0 2px;">
20
+ <img src='https://img.shields.io/badge/Webpage-Project-silver?style=flat&logo=&logoColor=orange' alt='webpage'>
21
+ </a>
22
+ <a href="https://github.com/Zheng-Chong/CatVTON/LICENCE" style="margin: 0 2px;">
23
+ <img src='https://img.shields.io/badge/License-CC BY--NC--SA--4.0-lightgreen?style=flat&logo=Lisence' alt='License'>
24
+ </a>
25
+ </div>
26
+
27
+
28
+ **CatVTON** is a simple and efficient virtual try-on diffusion model with ***1) Lightweight Network (899.06M parameters totally)***, ***2) Parameter-Efficient Training (49.57M parameters trainable)*** and ***3) Simplified Inference (< 8G VRAM for 1024X768 resolution)***.
29
+ <div align="center">
30
+ <img src="resource/img/teaser.jpg" width="100%" height="100%"/>
31
+ </div>
32
+
33
+
34
+
35
+ ## Updates
36
+ - **`2024/11/26`**: Our **unified vision-based model for image and video try-on** will be released soon, bringing a brand-new virtual try-on experience! While our demo page will be temporarily taken offline, [**the demo on HuggingFace Space**](https://huggingface.co/spaces/zhengchong/CatVTON) will remain available for use !
37
+ - **`2024/10/17`**:[**Mask-free version**](https://huggingface.co/zhengchong/CatVTON-MaskFree)🤗 of CatVTON is release !
38
+ - **`2024/10/13`**: We have built a repo [**Awesome-Try-On-Models**](https://github.com/Zheng-Chong/Awesome-Try-On-Models) that focuses on image, video, and 3D-based try-on models published after 2023, aiming to provide insights into the latest technological trends. If you're interested, feel free to contribute or give it a 🌟 star!
39
+ - **`2024/08/13`**: We localize DensePose & SCHP to avoid certain environment issues.
40
+ - **`2024/08/10`**: Our 🤗 [**HuggingFace Space**](https://huggingface.co/spaces/zhengchong/CatVTON) is available now! Thanks for the grant from [**ZeroGPU**](https://huggingface.co/zero-gpu-explorers)!
41
+ - **`2024/08/09`**: [**Evaluation code**](https://github.com/Zheng-Chong/CatVTON?tab=readme-ov-file#3-calculate-metrics) is provided to calculate metrics 📚.
42
+ - **`2024/07/27`**: We provide code and workflow for deploying CatVTON on [**ComfyUI**](https://github.com/Zheng-Chong/CatVTON?tab=readme-ov-file#comfyui-workflow) 💥.
43
+ - **`2024/07/24`**: Our [**Paper on ArXiv**](http://arxiv.org/abs/2407.15886) is available 🥳!
44
+ - **`2024/07/22`**: Our [**App Code**](https://github.com/Zheng-Chong/CatVTON/blob/main/app.py) is released, deploy and enjoy CatVTON on your mechine 🎉!
45
+ - **`2024/07/21`**: Our [**Inference Code**](https://github.com/Zheng-Chong/CatVTON/blob/main/inference.py) and [**Weights** 🤗](https://huggingface.co/zhengchong/CatVTON) are released.
46
+ - **`2024/07/11`**: Our [**Online Demo**](https://huggingface.co/spaces/zhengchong/CatVTON) is released 😁.
47
+
48
+
49
+
50
+
51
+ ## Installation
52
+
53
+ Create a conda environment & Install requirments
54
+ ```shell
55
+ conda create -n catvton python==3.9.0
56
+ conda activate catvton
57
+ cd CatVTON-main # or your path to CatVTON project dir
58
+ pip install -r requirements.txt
59
+ ```
60
+
61
+ ## Deployment
62
+ ### ComfyUI Workflow
63
+ We have modified the main code to enable easy deployment of CatVTON on [ComfyUI](https://github.com/comfyanonymous/ComfyUI). Due to the incompatibility of the code structure, we have released this part in the [Releases](https://github.com/Zheng-Chong/CatVTON/releases/tag/ComfyUI), which includes the code placed under `custom_nodes` of ComfyUI and our workflow JSON files.
64
+
65
+ To deploy CatVTON to your ComfyUI, follow these steps:
66
+ 1. Install all the requirements for both CatVTON and ComfyUI, refer to [Installation Guide for CatVTON](https://github.com/Zheng-Chong/CatVTON/blob/main/INSTALL.md) and [Installation Guide for ComfyUI](https://github.com/comfyanonymous/ComfyUI?tab=readme-ov-file#installing).
67
+ 2. Download [`ComfyUI-CatVTON.zip`](https://github.com/Zheng-Chong/CatVTON/releases/download/ComfyUI/ComfyUI-CatVTON.zip) and unzip it in the `custom_nodes` folder under your ComfyUI project (clone from [ComfyUI](https://github.com/comfyanonymous/ComfyUI)).
68
+ 3. Run the ComfyUI.
69
+ 4. Download [`catvton_workflow.json`](https://github.com/Zheng-Chong/CatVTON/releases/download/ComfyUI/catvton_workflow.json) and drag it into you ComfyUI webpage and enjoy 😆!
70
+
71
+ > Problems under Windows OS, please refer to [issue#8](https://github.com/Zheng-Chong/CatVTON/issues/8).
72
+ >
73
+ When you run the CatVTON workflow for the first time, the weight files will be automatically downloaded, usually taking dozens of minutes.
74
+
75
+ <div align="center">
76
+ <img src="resource/img/comfyui-1.png" width="100%" height="100%"/>
77
+ </div>
78
+
79
+ <!-- <div align="center">
80
+ <img src="resource/img/comfyui.png" width="100%" height="100%"/>
81
+ </div> -->
82
+
83
+ ### Gradio App
84
+
85
+ To deploy the Gradio App for CatVTON on your machine, run the following command, and checkpoints will be automatically downloaded from HuggingFace.
86
+
87
+ ```PowerShell
88
+ CUDA_VISIBLE_DEVICES=0 python app.py \
89
+ --output_dir="resource/demo/output" \
90
+ --mixed_precision="bf16" \
91
+ --allow_tf32
92
+ ```
93
+ When using `bf16` precision, generating results with a resolution of `1024x768` only requires about `8G` VRAM.
94
+
95
+ ## Inference
96
+ ### 1. Data Preparation
97
+ Before inference, you need to download the [VITON-HD](https://github.com/shadow2496/VITON-HD) or [DressCode](https://github.com/aimagelab/dress-code) dataset.
98
+ Once the datasets are downloaded, the folder structures should look like these:
99
+ ```
100
+ ├── VITON-HD
101
+ | ├── test_pairs_unpaired.txt
102
+ │ ├── test
103
+ | | ├── image
104
+ │ │ │ ├── [000006_00.jpg | 000008_00.jpg | ...]
105
+ │ │ ├── cloth
106
+ │ │ │ ├── [000006_00.jpg | 000008_00.jpg | ...]
107
+ │ │ ├── agnostic-mask
108
+ │ │ │ ├── [000006_00_mask.png | 000008_00.png | ...]
109
+ ...
110
+ ```
111
+
112
+ ```
113
+ ├── DressCode
114
+ | ├── test_pairs_paired.txt
115
+ | ├── test_pairs_unpaired.txt
116
+ │ ├── [dresses | lower_body | upper_body]
117
+ | | ├── test_pairs_paired.txt
118
+ | | ├── test_pairs_unpaired.txt
119
+ │ │ ├── images
120
+ │ │ │ ├── [013563_0.jpg | 013563_1.jpg | 013564_0.jpg | 013564_1.jpg | ...]
121
+ │ │ ├── agnostic_masks
122
+ │ │ │ ├── [013563_0.png| 013564_0.png | ...]
123
+ ...
124
+ ```
125
+ For the DressCode dataset, we provide script to preprocessed agnostic masks, run the following command:
126
+ ```PowerShell
127
+ CUDA_VISIBLE_DEVICES=0 python preprocess_agnostic_mask.py \
128
+ --data_root_path <your_path_to_DressCode>
129
+ ```
130
+
131
+ ### 2. Inference on VTIONHD/DressCode
132
+ To run the inference on the DressCode or VITON-HD dataset, run the following command, checkpoints will be automatically downloaded from HuggingFace.
133
+
134
+ ```PowerShell
135
+ CUDA_VISIBLE_DEVICES=0 python inference.py \
136
+ --dataset [dresscode | vitonhd] \
137
+ --data_root_path <path> \
138
+ --output_dir <path>
139
+ --dataloader_num_workers 8 \
140
+ --batch_size 8 \
141
+ --seed 555 \
142
+ --mixed_precision [no | fp16 | bf16] \
143
+ --allow_tf32 \
144
+ --repaint \
145
+ --eval_pair
146
+ ```
147
+ ### 3. Calculate Metrics
148
+
149
+ After obtaining the inference results, calculate the metrics using the following command:
150
+
151
+ ```PowerShell
152
+ CUDA_VISIBLE_DEVICES=0 python eval.py \
153
+ --gt_folder <your_path_to_gt_image_folder> \
154
+ --pred_folder <your_path_to_predicted_image_folder> \
155
+ --paired \
156
+ --batch_size=16 \
157
+ --num_workers=16
158
+ ```
159
+
160
+ - `--gt_folder` and `--pred_folder` should be folders that contain **only images**.
161
+ - To evaluate the results in a paired setting, use `--paired`; for an unpaired setting, simply omit it.
162
+ - `--batch_size` and `--num_workers` should be adjusted based on your machine.
163
+
164
+
165
+ ## Acknowledgement
166
+ Our code is modified based on [Diffusers](https://github.com/huggingface/diffusers). We adopt [Stable Diffusion v1.5 inpainting](https://huggingface.co/runwayml/stable-diffusion-inpainting) as the base model. We use [SCHP](https://github.com/GoGoDuck912/Self-Correction-Human-Parsing/tree/master) and [DensePose](https://github.com/facebookresearch/DensePose) to automatically generate masks in our [Gradio](https://github.com/gradio-app/gradio) App and [ComfyUI](https://github.com/comfyanonymous/ComfyUI) workflow. Thanks to all the contributors!
167
+
168
+ ## License
169
+ All the materials, including code, checkpoints, and demo, are made available under the [Creative Commons BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/) license. You are free to copy, redistribute, remix, transform, and build upon the project for non-commercial purposes, as long as you give appropriate credit and distribute your contributions under the same license.
170
+
171
+
172
+ ## Citation
173
+
174
+ ```bibtex
175
+ @misc{chong2024catvtonconcatenationneedvirtual,
176
+ title={CatVTON: Concatenation Is All You Need for Virtual Try-On with Diffusion Models},
177
+ author={Zheng Chong and Xiao Dong and Haoxiang Li and Shiyue Zhang and Wenqing Zhang and Xujie Zhang and Hanqing Zhao and Xiaodan Liang},
178
+ year={2024},
179
+ eprint={2407.15886},
180
+ archivePrefix={arXiv},
181
+ primaryClass={cs.CV},
182
+ url={https://arxiv.org/abs/2407.15886},
183
+ }
184
+ ```
app.py CHANGED
@@ -1,12 +1,373 @@
 
 
 
 
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
- def greet(name, intensity):
4
- return "Hello, " + name + "!" * int(intensity)
 
5
 
6
- demo = gr.Interface(
7
- fn=greet,
8
- inputs=["text", "slider"],
9
- outputs=["text"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
  )
11
 
12
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from diffusers.image_processor import VaeImageProcessor
9
+ from huggingface_hub import snapshot_download
10
+ from PIL import Image
11
+
12
+ from model.cloth_masker import AutoMasker, vis_mask
13
+ from model.pipeline import CatVTONPipeline
14
+ from utils import init_weight_dtype, resize_and_crop, resize_and_padding
15
+
16
+ def parse_args():
17
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
18
+ parser.add_argument(
19
+ "--base_model_path",
20
+ type=str,
21
+ default="booksforcharlie/stable-diffusion-inpainting", # Change to a copy repo as runawayml delete original repo
22
+ help=(
23
+ "The path to the base model to use for evaluation. This can be a local path or a model identifier from the Model Hub."
24
+ ),
25
+ )
26
+ parser.add_argument(
27
+ "--resume_path",
28
+ type=str,
29
+ default="zhengchong/CatVTON",
30
+ help=(
31
+ "The Path to the checkpoint of trained tryon model."
32
+ ),
33
+ )
34
+ parser.add_argument(
35
+ "--output_dir",
36
+ type=str,
37
+ default="resource/demo/output",
38
+ help="The output directory where the model predictions will be written.",
39
+ )
40
+
41
+ parser.add_argument(
42
+ "--width",
43
+ type=int,
44
+ default=768,
45
+ help=(
46
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
47
+ " resolution"
48
+ ),
49
+ )
50
+ parser.add_argument(
51
+ "--height",
52
+ type=int,
53
+ default=1024,
54
+ help=(
55
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
56
+ " resolution"
57
+ ),
58
+ )
59
+ parser.add_argument(
60
+ "--repaint",
61
+ action="store_true",
62
+ help="Whether to repaint the result image with the original background."
63
+ )
64
+ parser.add_argument(
65
+ "--allow_tf32",
66
+ action="store_true",
67
+ default=True,
68
+ help=(
69
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
70
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
71
+ ),
72
+ )
73
+ parser.add_argument(
74
+ "--mixed_precision",
75
+ type=str,
76
+ default="bf16",
77
+ choices=["no", "fp16", "bf16"],
78
+ help=(
79
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
80
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
81
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
82
+ ),
83
+ )
84
+
85
+ args = parser.parse_args()
86
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
87
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
88
+ args.local_rank = env_local_rank
89
+
90
+ return args
91
+
92
+ def image_grid(imgs, rows, cols):
93
+ assert len(imgs) == rows * cols
94
+
95
+ w, h = imgs[0].size
96
+ grid = Image.new("RGB", size=(cols * w, rows * h))
97
 
98
+ for i, img in enumerate(imgs):
99
+ grid.paste(img, box=(i % cols * w, i // cols * h))
100
+ return grid
101
 
102
+
103
+ args = parse_args()
104
+ repo_path = snapshot_download(repo_id=args.resume_path)
105
+ # Pipeline
106
+ pipeline = CatVTONPipeline(
107
+ base_ckpt=args.base_model_path,
108
+ attn_ckpt=repo_path,
109
+ attn_ckpt_version="mix",
110
+ weight_dtype=init_weight_dtype(args.mixed_precision),
111
+ use_tf32=args.allow_tf32,
112
+ device='cuda'
113
+ )
114
+ # AutoMasker
115
+ mask_processor = VaeImageProcessor(vae_scale_factor=8, do_normalize=False, do_binarize=True, do_convert_grayscale=True)
116
+ automasker = AutoMasker(
117
+ densepose_ckpt=os.path.join(repo_path, "DensePose"),
118
+ schp_ckpt=os.path.join(repo_path, "SCHP"),
119
+ device='cuda',
120
  )
121
 
122
+ def submit_function(
123
+ person_image,
124
+ cloth_image,
125
+ cloth_type,
126
+ num_inference_steps,
127
+ guidance_scale,
128
+ seed,
129
+ show_type
130
+ ):
131
+ person_image, mask = person_image["background"], person_image["layers"][0]
132
+ mask = Image.open(mask).convert("L")
133
+ if len(np.unique(np.array(mask))) == 1:
134
+ mask = None
135
+ else:
136
+ mask = np.array(mask)
137
+ mask[mask > 0] = 255
138
+ mask = Image.fromarray(mask)
139
+
140
+ tmp_folder = args.output_dir
141
+ date_str = datetime.now().strftime("%Y%m%d%H%M%S")
142
+ result_save_path = os.path.join(tmp_folder, date_str[:8], date_str[8:] + ".png")
143
+ if not os.path.exists(os.path.join(tmp_folder, date_str[:8])):
144
+ os.makedirs(os.path.join(tmp_folder, date_str[:8]))
145
+
146
+ generator = None
147
+ if seed != -1:
148
+ generator = torch.Generator(device='cuda').manual_seed(seed)
149
+
150
+ person_image = Image.open(person_image).convert("RGB")
151
+ cloth_image = Image.open(cloth_image).convert("RGB")
152
+ person_image = resize_and_crop(person_image, (args.width, args.height))
153
+ cloth_image = resize_and_padding(cloth_image, (args.width, args.height))
154
+
155
+ # Process mask
156
+ if mask is not None:
157
+ mask = resize_and_crop(mask, (args.width, args.height))
158
+ else:
159
+ mask = automasker(
160
+ person_image,
161
+ cloth_type
162
+ )['mask']
163
+ mask = mask_processor.blur(mask, blur_factor=9)
164
+
165
+ # Inference
166
+ # try:
167
+ result_image = pipeline(
168
+ image=person_image,
169
+ condition_image=cloth_image,
170
+ mask=mask,
171
+ num_inference_steps=num_inference_steps,
172
+ guidance_scale=guidance_scale,
173
+ generator=generator
174
+ )[0]
175
+ # except Exception as e:
176
+ # raise gr.Error(
177
+ # "An error occurred. Please try again later: {}".format(e)
178
+ # )
179
+
180
+ # Post-process
181
+ masked_person = vis_mask(person_image, mask)
182
+ save_result_image = image_grid([person_image, masked_person, cloth_image, result_image], 1, 4)
183
+ save_result_image.save(result_save_path)
184
+ if show_type == "result only":
185
+ return result_image
186
+ else:
187
+ width, height = person_image.size
188
+ if show_type == "input & result":
189
+ condition_width = width // 2
190
+ conditions = image_grid([person_image, cloth_image], 2, 1)
191
+ else:
192
+ condition_width = width // 3
193
+ conditions = image_grid([person_image, masked_person , cloth_image], 3, 1)
194
+ conditions = conditions.resize((condition_width, height), Image.NEAREST)
195
+ new_result_image = Image.new("RGB", (width + condition_width + 5, height))
196
+ new_result_image.paste(conditions, (0, 0))
197
+ new_result_image.paste(result_image, (condition_width + 5, 0))
198
+ return new_result_image
199
+
200
+
201
+ def person_example_fn(image_path):
202
+ return image_path
203
+
204
+ HEADER = """
205
+ <h1 style="text-align: center;"> 🐈 CatVTON: Concatenation Is All You Need for Virtual Try-On with Diffusion Models </h1>
206
+ <div style="display: flex; justify-content: center; align-items: center;">
207
+ <a href="http://arxiv.org/abs/2407.15886" style="margin: 0 2px;">
208
+ <img src='https://img.shields.io/badge/arXiv-2407.15886-red?style=flat&logo=arXiv&logoColor=red' alt='arxiv'>
209
+ </a>
210
+ <a href='https://huggingface.co/zhengchong/CatVTON' style="margin: 0 2px;">
211
+ <img src='https://img.shields.io/badge/Hugging Face-ckpts-orange?style=flat&logo=HuggingFace&logoColor=orange' alt='huggingface'>
212
+ </a>
213
+ <a href="https://github.com/Zheng-Chong/CatVTON" style="margin: 0 2px;">
214
+ <img src='https://img.shields.io/badge/GitHub-Repo-blue?style=flat&logo=GitHub' alt='GitHub'>
215
+ </a>
216
+ <a href="http://120.76.142.206:8888" style="margin: 0 2px;">
217
+ <img src='https://img.shields.io/badge/Demo-Gradio-gold?style=flat&logo=Gradio&logoColor=red' alt='Demo'>
218
+ </a>
219
+ <a href="https://huggingface.co/spaces/zhengchong/CatVTON" style="margin: 0 2px;">
220
+ <img src='https://img.shields.io/badge/Space-ZeroGPU-orange?style=flat&logo=Gradio&logoColor=red' alt='Demo'>
221
+ </a>
222
+ <a href='https://zheng-chong.github.io/CatVTON/' style="margin: 0 2px;">
223
+ <img src='https://img.shields.io/badge/Webpage-Project-silver?style=flat&logo=&logoColor=orange' alt='webpage'>
224
+ </a>
225
+ <a href="https://github.com/Zheng-Chong/CatVTON/LICENCE" style="margin: 0 2px;">
226
+ <img src='https://img.shields.io/badge/License-CC BY--NC--SA--4.0-lightgreen?style=flat&logo=Lisence' alt='License'>
227
+ </a>
228
+ </div>
229
+ <br>
230
+ · This demo and our weights are only for <span>Non-commercial Use</span>. <br>
231
+ · You can try CatVTON in our <a href="https://huggingface.co/spaces/zhengchong/CatVTON">HuggingFace Space</a> or our <a href="http://120.76.142.206:8888">online demo</a> (run on 3090). <br>
232
+ · Thanks to <a href="https://huggingface.co/zero-gpu-explorers">ZeroGPU</a> for providing A100 for our <a href="https://huggingface.co/spaces/zhengchong/CatVTON">HuggingFace Space</a>. <br>
233
+ · SafetyChecker is set to filter NSFW content, but it may block normal results too. Please adjust the <span>`seed`</span> for normal outcomes.<br>
234
+ """
235
+
236
+ def app_gradio():
237
+ with gr.Blocks(title="CatVTON") as demo:
238
+ gr.Markdown(HEADER)
239
+ with gr.Row():
240
+ with gr.Column(scale=1, min_width=350):
241
+ with gr.Row():
242
+ image_path = gr.Image(
243
+ type="filepath",
244
+ interactive=True,
245
+ visible=False,
246
+ )
247
+ person_image = gr.ImageEditor(
248
+ interactive=True, label="Person Image", type="filepath"
249
+ )
250
+
251
+ with gr.Row():
252
+ with gr.Column(scale=1, min_width=230):
253
+ cloth_image = gr.Image(
254
+ interactive=True, label="Condition Image", type="filepath"
255
+ )
256
+ with gr.Column(scale=1, min_width=120):
257
+ gr.Markdown(
258
+ '<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>'
259
+ )
260
+ cloth_type = gr.Radio(
261
+ label="Try-On Cloth Type",
262
+ choices=["upper", "lower", "overall"],
263
+ value="upper",
264
+ )
265
+
266
+
267
+ submit = gr.Button("Submit")
268
+ gr.Markdown(
269
+ '<center><span style="color: #FF0000">!!! Click only Once, Wait for Delay !!!</span></center>'
270
+ )
271
+
272
+ gr.Markdown(
273
+ '<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>'
274
+ )
275
+ with gr.Accordion("Advanced Options", open=False):
276
+ num_inference_steps = gr.Slider(
277
+ label="Inference Step", minimum=10, maximum=100, step=5, value=50
278
+ )
279
+ # Guidence Scale
280
+ guidance_scale = gr.Slider(
281
+ label="CFG Strenth", minimum=0.0, maximum=7.5, step=0.5, value=2.5
282
+ )
283
+ # Random Seed
284
+ seed = gr.Slider(
285
+ label="Seed", minimum=-1, maximum=10000, step=1, value=42
286
+ )
287
+ show_type = gr.Radio(
288
+ label="Show Type",
289
+ choices=["result only", "input & result", "input & mask & result"],
290
+ value="input & mask & result",
291
+ )
292
+
293
+ with gr.Column(scale=2, min_width=500):
294
+ result_image = gr.Image(interactive=False, label="Result")
295
+ with gr.Row():
296
+ # Photo Examples
297
+ root_path = "resource/demo/example"
298
+ with gr.Column():
299
+ men_exm = gr.Examples(
300
+ examples=[
301
+ os.path.join(root_path, "person", "men", _)
302
+ for _ in os.listdir(os.path.join(root_path, "person", "men"))
303
+ ],
304
+ examples_per_page=4,
305
+ inputs=image_path,
306
+ label="Person Examples ①",
307
+ )
308
+ women_exm = gr.Examples(
309
+ examples=[
310
+ os.path.join(root_path, "person", "women", _)
311
+ for _ in os.listdir(os.path.join(root_path, "person", "women"))
312
+ ],
313
+ examples_per_page=4,
314
+ inputs=image_path,
315
+ label="Person Examples ②",
316
+ )
317
+ gr.Markdown(
318
+ '<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>'
319
+ )
320
+ with gr.Column():
321
+ condition_upper_exm = gr.Examples(
322
+ examples=[
323
+ os.path.join(root_path, "condition", "upper", _)
324
+ for _ in os.listdir(os.path.join(root_path, "condition", "upper"))
325
+ ],
326
+ examples_per_page=4,
327
+ inputs=cloth_image,
328
+ label="Condition Upper Examples",
329
+ )
330
+ condition_overall_exm = gr.Examples(
331
+ examples=[
332
+ os.path.join(root_path, "condition", "overall", _)
333
+ for _ in os.listdir(os.path.join(root_path, "condition", "overall"))
334
+ ],
335
+ examples_per_page=4,
336
+ inputs=cloth_image,
337
+ label="Condition Overall Examples",
338
+ )
339
+ condition_person_exm = gr.Examples(
340
+ examples=[
341
+ os.path.join(root_path, "condition", "person", _)
342
+ for _ in os.listdir(os.path.join(root_path, "condition", "person"))
343
+ ],
344
+ examples_per_page=4,
345
+ inputs=cloth_image,
346
+ label="Condition Reference Person Examples",
347
+ )
348
+ gr.Markdown(
349
+ '<span style="color: #808080; font-size: small;">*Condition examples come from the Internet. </span>'
350
+ )
351
+
352
+ image_path.change(
353
+ person_example_fn, inputs=image_path, outputs=person_image
354
+ )
355
+
356
+ submit.click(
357
+ submit_function,
358
+ [
359
+ person_image,
360
+ cloth_image,
361
+ cloth_type,
362
+ num_inference_steps,
363
+ guidance_scale,
364
+ seed,
365
+ show_type,
366
+ ],
367
+ result_image,
368
+ )
369
+ demo.queue().launch(share=True, show_error=True)
370
+
371
+
372
+ if __name__ == "__main__":
373
+ app_gradio()
app_p2p.py ADDED
@@ -0,0 +1,567 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from diffusers.image_processor import VaeImageProcessor
9
+ from huggingface_hub import snapshot_download
10
+ from PIL import Image
11
+
12
+ from model.cloth_masker import AutoMasker, vis_mask
13
+ from model.pipeline import CatVTONPipeline, CatVTONPix2PixPipeline
14
+ from utils import init_weight_dtype, resize_and_crop, resize_and_padding
15
+
16
+
17
+ def parse_args():
18
+ parser = argparse.ArgumentParser(description="Simple example of a training script.")
19
+ parser.add_argument(
20
+ "--p2p_base_model_path",
21
+ type=str,
22
+ default="timbrooks/instruct-pix2pix",
23
+ help=(
24
+ "The path to the base model to use for evaluation. This can be a local path or a model identifier from the Model Hub."
25
+ ),
26
+ )
27
+ parser.add_argument(
28
+ "--ip_base_model_path",
29
+ type=str,
30
+ default="booksforcharlie/stable-diffusion-inpainting",
31
+ help=(
32
+ "The path to the base model to use for evaluation. This can be a local path or a model identifier from the Model Hub."
33
+ ),
34
+ )
35
+ parser.add_argument(
36
+ "--p2p_resume_path",
37
+ type=str,
38
+ default="zhengchong/CatVTON-MaskFree",
39
+ help=(
40
+ "The Path to the checkpoint of trained tryon model."
41
+ ),
42
+ )
43
+ parser.add_argument(
44
+ "--ip_resume_path",
45
+ type=str,
46
+ default="zhengchong/CatVTON",
47
+ help=(
48
+ "The Path to the checkpoint of trained tryon model."
49
+ ),
50
+ )
51
+ parser.add_argument(
52
+ "--output_dir",
53
+ type=str,
54
+ default="resource/demo/output",
55
+ help="The output directory where the model predictions will be written.",
56
+ )
57
+
58
+ parser.add_argument(
59
+ "--width",
60
+ type=int,
61
+ default=768,
62
+ help=(
63
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
64
+ " resolution"
65
+ ),
66
+ )
67
+ parser.add_argument(
68
+ "--height",
69
+ type=int,
70
+ default=1024,
71
+ help=(
72
+ "The resolution for input images, all the images in the train/validation dataset will be resized to this"
73
+ " resolution"
74
+ ),
75
+ )
76
+ parser.add_argument(
77
+ "--repaint",
78
+ action="store_true",
79
+ help="Whether to repaint the result image with the original background."
80
+ )
81
+ parser.add_argument(
82
+ "--allow_tf32",
83
+ action="store_true",
84
+ default=True,
85
+ help=(
86
+ "Whether or not to allow TF32 on Ampere GPUs. Can be used to speed up training. For more information, see"
87
+ " https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices"
88
+ ),
89
+ )
90
+ parser.add_argument(
91
+ "--mixed_precision",
92
+ type=str,
93
+ default="bf16",
94
+ choices=["no", "fp16", "bf16"],
95
+ help=(
96
+ "Whether to use mixed precision. Choose between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >="
97
+ " 1.10.and an Nvidia Ampere GPU. Default to the value of accelerate config of the current system or the"
98
+ " flag passed with the `accelerate.launch` command. Use this argument to override the accelerate config."
99
+ ),
100
+ )
101
+
102
+ args = parser.parse_args()
103
+ env_local_rank = int(os.environ.get("LOCAL_RANK", -1))
104
+ if env_local_rank != -1 and env_local_rank != args.local_rank:
105
+ args.local_rank = env_local_rank
106
+
107
+ return args
108
+
109
+ def image_grid(imgs, rows, cols):
110
+ assert len(imgs) == rows * cols
111
+
112
+ w, h = imgs[0].size
113
+ grid = Image.new("RGB", size=(cols * w, rows * h))
114
+
115
+ for i, img in enumerate(imgs):
116
+ grid.paste(img, box=(i % cols * w, i // cols * h))
117
+ return grid
118
+
119
+
120
+ args = parse_args()
121
+ repo_path = snapshot_download(repo_id=args.ip_resume_path)
122
+ # Pipeline
123
+ pipeline_p2p = CatVTONPix2PixPipeline(
124
+ base_ckpt=args.p2p_base_model_path,
125
+ attn_ckpt=repo_path,
126
+ attn_ckpt_version="mix-48k-1024",
127
+ weight_dtype=init_weight_dtype(args.mixed_precision),
128
+ use_tf32=args.allow_tf32,
129
+ device='cuda'
130
+ )
131
+
132
+ # Pipeline
133
+ repo_path = snapshot_download(repo_id=args.ip_resume_path)
134
+ pipeline = CatVTONPipeline(
135
+ base_ckpt=args.ip_base_model_path,
136
+ attn_ckpt=repo_path,
137
+ attn_ckpt_version="mix",
138
+ weight_dtype=init_weight_dtype(args.mixed_precision),
139
+ use_tf32=args.allow_tf32,
140
+ device='cuda'
141
+ )
142
+
143
+ # AutoMasker
144
+ mask_processor = VaeImageProcessor(vae_scale_factor=8, do_normalize=False, do_binarize=True, do_convert_grayscale=True)
145
+ automasker = AutoMasker(
146
+ densepose_ckpt=os.path.join(repo_path, "DensePose"),
147
+ schp_ckpt=os.path.join(repo_path, "SCHP"),
148
+ device='cuda',
149
+ )
150
+
151
+
152
+ def submit_function_p2p(
153
+ person_image,
154
+ cloth_image,
155
+ num_inference_steps,
156
+ guidance_scale,
157
+ seed):
158
+ person_image= person_image["background"]
159
+
160
+ tmp_folder = args.output_dir
161
+ date_str = datetime.now().strftime("%Y%m%d%H%M%S")
162
+ result_save_path = os.path.join(tmp_folder, date_str[:8], date_str[8:] + ".png")
163
+ if not os.path.exists(os.path.join(tmp_folder, date_str[:8])):
164
+ os.makedirs(os.path.join(tmp_folder, date_str[:8]))
165
+
166
+ generator = None
167
+ if seed != -1:
168
+ generator = torch.Generator(device='cuda').manual_seed(seed)
169
+
170
+ person_image = Image.open(person_image).convert("RGB")
171
+ cloth_image = Image.open(cloth_image).convert("RGB")
172
+ person_image = resize_and_crop(person_image, (args.width, args.height))
173
+ cloth_image = resize_and_padding(cloth_image, (args.width, args.height))
174
+
175
+ # Inference
176
+ try:
177
+ result_image = pipeline_p2p(
178
+ image=person_image,
179
+ condition_image=cloth_image,
180
+ num_inference_steps=num_inference_steps,
181
+ guidance_scale=guidance_scale,
182
+ generator=generator
183
+ )[0]
184
+ except Exception as e:
185
+ raise gr.Error(
186
+ "An error occurred. Please try again later: {}".format(e)
187
+ )
188
+
189
+ # Post-process
190
+ save_result_image = image_grid([person_image, cloth_image, result_image], 1, 3)
191
+ save_result_image.save(result_save_path)
192
+ return result_image
193
+
194
+ def submit_function(
195
+ person_image,
196
+ cloth_image,
197
+ cloth_type,
198
+ num_inference_steps,
199
+ guidance_scale,
200
+ seed,
201
+ show_type
202
+ ):
203
+ person_image, mask = person_image["background"], person_image["layers"][0]
204
+ mask = Image.open(mask).convert("L")
205
+ if len(np.unique(np.array(mask))) == 1:
206
+ mask = None
207
+ else:
208
+ mask = np.array(mask)
209
+ mask[mask > 0] = 255
210
+ mask = Image.fromarray(mask)
211
+
212
+ tmp_folder = args.output_dir
213
+ date_str = datetime.now().strftime("%Y%m%d%H%M%S")
214
+ result_save_path = os.path.join(tmp_folder, date_str[:8], date_str[8:] + ".png")
215
+ if not os.path.exists(os.path.join(tmp_folder, date_str[:8])):
216
+ os.makedirs(os.path.join(tmp_folder, date_str[:8]))
217
+
218
+ generator = None
219
+ if seed != -1:
220
+ generator = torch.Generator(device='cuda').manual_seed(seed)
221
+
222
+ person_image = Image.open(person_image).convert("RGB")
223
+ cloth_image = Image.open(cloth_image).convert("RGB")
224
+ person_image = resize_and_crop(person_image, (args.width, args.height))
225
+ cloth_image = resize_and_padding(cloth_image, (args.width, args.height))
226
+
227
+ # Process mask
228
+ if mask is not None:
229
+ mask = resize_and_crop(mask, (args.width, args.height))
230
+ else:
231
+ mask = automasker(
232
+ person_image,
233
+ cloth_type
234
+ )['mask']
235
+ mask = mask_processor.blur(mask, blur_factor=9)
236
+
237
+ # Inference
238
+ # try:
239
+ result_image = pipeline(
240
+ image=person_image,
241
+ condition_image=cloth_image,
242
+ mask=mask,
243
+ num_inference_steps=num_inference_steps,
244
+ guidance_scale=guidance_scale,
245
+ generator=generator
246
+ )[0]
247
+ # except Exception as e:
248
+ # raise gr.Error(
249
+ # "An error occurred. Please try again later: {}".format(e)
250
+ # )
251
+
252
+ # Post-process
253
+ masked_person = vis_mask(person_image, mask)
254
+ save_result_image = image_grid([person_image, masked_person, cloth_image, result_image], 1, 4)
255
+ save_result_image.save(result_save_path)
256
+ if show_type == "result only":
257
+ return result_image
258
+ else:
259
+ width, height = person_image.size
260
+ if show_type == "input & result":
261
+ condition_width = width // 2
262
+ conditions = image_grid([person_image, cloth_image], 2, 1)
263
+ else:
264
+ condition_width = width // 3
265
+ conditions = image_grid([person_image, masked_person , cloth_image], 3, 1)
266
+ conditions = conditions.resize((condition_width, height), Image.NEAREST)
267
+ new_result_image = Image.new("RGB", (width + condition_width + 5, height))
268
+ new_result_image.paste(conditions, (0, 0))
269
+ new_result_image.paste(result_image, (condition_width + 5, 0))
270
+ return new_result_image
271
+
272
+
273
+
274
+ def person_example_fn(image_path):
275
+ return image_path
276
+
277
+ HEADER = """
278
+ <h1 style="text-align: center;"> 🐈 CatVTON: Concatenation Is All You Need for Virtual Try-On with Diffusion Models </h1>
279
+ <div style="display: flex; justify-content: center; align-items: center;">
280
+ <a href="http://arxiv.org/abs/2407.15886" style="margin: 0 2px;">
281
+ <img src='https://img.shields.io/badge/arXiv-2407.15886-red?style=flat&logo=arXiv&logoColor=red' alt='arxiv'>
282
+ </a>
283
+ <a href='https://huggingface.co/zhengchong/CatVTON' style="margin: 0 2px;">
284
+ <img src='https://img.shields.io/badge/Hugging Face-ckpts-orange?style=flat&logo=HuggingFace&logoColor=orange' alt='huggingface'>
285
+ </a>
286
+ <a href="https://github.com/Zheng-Chong/CatVTON" style="margin: 0 2px;">
287
+ <img src='https://img.shields.io/badge/GitHub-Repo-blue?style=flat&logo=GitHub' alt='GitHub'>
288
+ </a>
289
+ <a href="http://120.76.142.206:8888" style="margin: 0 2px;">
290
+ <img src='https://img.shields.io/badge/Demo-Gradio-gold?style=flat&logo=Gradio&logoColor=red' alt='Demo'>
291
+ </a>
292
+ <a href="https://huggingface.co/spaces/zhengchong/CatVTON" style="margin: 0 2px;">
293
+ <img src='https://img.shields.io/badge/Space-ZeroGPU-orange?style=flat&logo=Gradio&logoColor=red' alt='Demo'>
294
+ </a>
295
+ <a href='https://zheng-chong.github.io/CatVTON/' style="margin: 0 2px;">
296
+ <img src='https://img.shields.io/badge/Webpage-Project-silver?style=flat&logo=&logoColor=orange' alt='webpage'>
297
+ </a>
298
+ <a href="https://github.com/Zheng-Chong/CatVTON/LICENCE" style="margin: 0 2px;">
299
+ <img src='https://img.shields.io/badge/License-CC BY--NC--SA--4.0-lightgreen?style=flat&logo=Lisence' alt='License'>
300
+ </a>
301
+ </div>
302
+ <br>
303
+ · This demo and our weights are only for <span>Non-commercial Use</span>. <br>
304
+ · You can try CatVTON in our <a href="https://huggingface.co/spaces/zhengchong/CatVTON">HuggingFace Space</a> or our <a href="http://120.76.142.206:8888">online demo</a> (run on 3090). <br>
305
+ · Thanks to <a href="https://huggingface.co/zero-gpu-explorers">ZeroGPU</a> for providing A100 for our <a href="https://huggingface.co/spaces/zhengchong/CatVTON">HuggingFace Space</a>. <br>
306
+ · SafetyChecker is set to filter NSFW content, but it may block normal results too. Please adjust the <span>`seed`</span> for normal outcomes.<br>
307
+ """
308
+
309
+ def app_gradio():
310
+ with gr.Blocks(title="CatVTON") as demo:
311
+ gr.Markdown(HEADER)
312
+ with gr.Tab("Mask-based Virtual Try-On"):
313
+ with gr.Row():
314
+ with gr.Column(scale=1, min_width=350):
315
+ with gr.Row():
316
+ image_path = gr.Image(
317
+ type="filepath",
318
+ interactive=True,
319
+ visible=False,
320
+ )
321
+ person_image = gr.ImageEditor(
322
+ interactive=True, label="Person Image", type="filepath"
323
+ )
324
+
325
+ with gr.Row():
326
+ with gr.Column(scale=1, min_width=230):
327
+ cloth_image = gr.Image(
328
+ interactive=True, label="Condition Image", type="filepath"
329
+ )
330
+ with gr.Column(scale=1, min_width=120):
331
+ gr.Markdown(
332
+ '<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>'
333
+ )
334
+ cloth_type = gr.Radio(
335
+ label="Try-On Cloth Type",
336
+ choices=["upper", "lower", "overall"],
337
+ value="upper",
338
+ )
339
+
340
+
341
+ submit = gr.Button("Submit")
342
+ gr.Markdown(
343
+ '<center><span style="color: #FF0000">!!! Click only Once, Wait for Delay !!!</span></center>'
344
+ )
345
+
346
+ gr.Markdown(
347
+ '<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>'
348
+ )
349
+ with gr.Accordion("Advanced Options", open=False):
350
+ num_inference_steps = gr.Slider(
351
+ label="Inference Step", minimum=10, maximum=100, step=5, value=50
352
+ )
353
+ # Guidence Scale
354
+ guidance_scale = gr.Slider(
355
+ label="CFG Strenth", minimum=0.0, maximum=7.5, step=0.5, value=2.5
356
+ )
357
+ # Random Seed
358
+ seed = gr.Slider(
359
+ label="Seed", minimum=-1, maximum=10000, step=1, value=42
360
+ )
361
+ show_type = gr.Radio(
362
+ label="Show Type",
363
+ choices=["result only", "input & result", "input & mask & result"],
364
+ value="input & mask & result",
365
+ )
366
+
367
+ with gr.Column(scale=2, min_width=500):
368
+ result_image = gr.Image(interactive=False, label="Result")
369
+ with gr.Row():
370
+ # Photo Examples
371
+ root_path = "resource/demo/example"
372
+ with gr.Column():
373
+ men_exm = gr.Examples(
374
+ examples=[
375
+ os.path.join(root_path, "person", "men", _)
376
+ for _ in os.listdir(os.path.join(root_path, "person", "men"))
377
+ ],
378
+ examples_per_page=4,
379
+ inputs=image_path,
380
+ label="Person Examples ①",
381
+ )
382
+ women_exm = gr.Examples(
383
+ examples=[
384
+ os.path.join(root_path, "person", "women", _)
385
+ for _ in os.listdir(os.path.join(root_path, "person", "women"))
386
+ ],
387
+ examples_per_page=4,
388
+ inputs=image_path,
389
+ label="Person Examples ②",
390
+ )
391
+ gr.Markdown(
392
+ '<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>'
393
+ )
394
+ with gr.Column():
395
+ condition_upper_exm = gr.Examples(
396
+ examples=[
397
+ os.path.join(root_path, "condition", "upper", _)
398
+ for _ in os.listdir(os.path.join(root_path, "condition", "upper"))
399
+ ],
400
+ examples_per_page=4,
401
+ inputs=cloth_image,
402
+ label="Condition Upper Examples",
403
+ )
404
+ condition_overall_exm = gr.Examples(
405
+ examples=[
406
+ os.path.join(root_path, "condition", "overall", _)
407
+ for _ in os.listdir(os.path.join(root_path, "condition", "overall"))
408
+ ],
409
+ examples_per_page=4,
410
+ inputs=cloth_image,
411
+ label="Condition Overall Examples",
412
+ )
413
+ condition_person_exm = gr.Examples(
414
+ examples=[
415
+ os.path.join(root_path, "condition", "person", _)
416
+ for _ in os.listdir(os.path.join(root_path, "condition", "person"))
417
+ ],
418
+ examples_per_page=4,
419
+ inputs=cloth_image,
420
+ label="Condition Reference Person Examples",
421
+ )
422
+ gr.Markdown(
423
+ '<span style="color: #808080; font-size: small;">*Condition examples come from the Internet. </span>'
424
+ )
425
+
426
+ image_path.change(
427
+ person_example_fn, inputs=image_path, outputs=person_image
428
+ )
429
+
430
+ submit.click(
431
+ submit_function,
432
+ [
433
+ person_image,
434
+ cloth_image,
435
+ cloth_type,
436
+ num_inference_steps,
437
+ guidance_scale,
438
+ seed,
439
+ show_type,
440
+ ],
441
+ result_image,
442
+ )
443
+
444
+ with gr.Tab("Mask-Free Virtual Try-On"):
445
+ with gr.Row():
446
+ with gr.Column(scale=1, min_width=350):
447
+ with gr.Row():
448
+ image_path_p2p = gr.Image(
449
+ type="filepath",
450
+ interactive=True,
451
+ visible=False,
452
+ )
453
+ person_image_p2p = gr.ImageEditor(
454
+ interactive=True, label="Person Image", type="filepath"
455
+ )
456
+
457
+ with gr.Row():
458
+ with gr.Column(scale=1, min_width=230):
459
+ cloth_image_p2p = gr.Image(
460
+ interactive=True, label="Condition Image", type="filepath"
461
+ )
462
+
463
+ submit_p2p = gr.Button("Submit")
464
+ gr.Markdown(
465
+ '<center><span style="color: #FF0000">!!! Click only Once, Wait for Delay !!!</span></center>'
466
+ )
467
+
468
+ gr.Markdown(
469
+ '<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>'
470
+ )
471
+ with gr.Accordion("Advanced Options", open=False):
472
+ num_inference_steps_p2p = gr.Slider(
473
+ label="Inference Step", minimum=10, maximum=100, step=5, value=50
474
+ )
475
+ # Guidence Scale
476
+ guidance_scale_p2p = gr.Slider(
477
+ label="CFG Strenth", minimum=0.0, maximum=7.5, step=0.5, value=2.5
478
+ )
479
+ # Random Seed
480
+ seed_p2p = gr.Slider(
481
+ label="Seed", minimum=-1, maximum=10000, step=1, value=42
482
+ )
483
+ # show_type = gr.Radio(
484
+ # label="Show Type",
485
+ # choices=["result only", "input & result", "input & mask & result"],
486
+ # value="input & mask & result",
487
+ # )
488
+
489
+ with gr.Column(scale=2, min_width=500):
490
+ result_image_p2p = gr.Image(interactive=False, label="Result")
491
+ with gr.Row():
492
+ # Photo Examples
493
+ root_path = "resource/demo/example"
494
+ with gr.Column():
495
+ gr.Examples(
496
+ examples=[
497
+ os.path.join(root_path, "person", "men", _)
498
+ for _ in os.listdir(os.path.join(root_path, "person", "men"))
499
+ ],
500
+ examples_per_page=4,
501
+ inputs=image_path_p2p,
502
+ label="Person Examples ①",
503
+ )
504
+ gr.Examples(
505
+ examples=[
506
+ os.path.join(root_path, "person", "women", _)
507
+ for _ in os.listdir(os.path.join(root_path, "person", "women"))
508
+ ],
509
+ examples_per_page=4,
510
+ inputs=image_path_p2p,
511
+ label="Person Examples ②",
512
+ )
513
+ gr.Markdown(
514
+ '<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>'
515
+ )
516
+ with gr.Column():
517
+ gr.Examples(
518
+ examples=[
519
+ os.path.join(root_path, "condition", "upper", _)
520
+ for _ in os.listdir(os.path.join(root_path, "condition", "upper"))
521
+ ],
522
+ examples_per_page=4,
523
+ inputs=cloth_image_p2p,
524
+ label="Condition Upper Examples",
525
+ )
526
+ gr.Examples(
527
+ examples=[
528
+ os.path.join(root_path, "condition", "overall", _)
529
+ for _ in os.listdir(os.path.join(root_path, "condition", "overall"))
530
+ ],
531
+ examples_per_page=4,
532
+ inputs=cloth_image_p2p,
533
+ label="Condition Overall Examples",
534
+ )
535
+ condition_person_exm = gr.Examples(
536
+ examples=[
537
+ os.path.join(root_path, "condition", "person", _)
538
+ for _ in os.listdir(os.path.join(root_path, "condition", "person"))
539
+ ],
540
+ examples_per_page=4,
541
+ inputs=cloth_image_p2p,
542
+ label="Condition Reference Person Examples",
543
+ )
544
+ gr.Markdown(
545
+ '<span style="color: #808080; font-size: small;">*Condition examples come from the Internet. </span>'
546
+ )
547
+
548
+ image_path_p2p.change(
549
+ person_example_fn, inputs=image_path_p2p, outputs=person_image_p2p
550
+ )
551
+
552
+ submit_p2p.click(
553
+ submit_function_p2p,
554
+ [
555
+ person_image_p2p,
556
+ cloth_image_p2p,
557
+ num_inference_steps_p2p,
558
+ guidance_scale_p2p,
559
+ seed_p2p],
560
+ result_image_p2p,
561
+ )
562
+
563
+ demo.queue().launch(share=True, show_error=True)
564
+
565
+
566
+ if __name__ == "__main__":
567
+ app_gradio()
eval.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ for gt, pred in tqdm(dataloader, desc="Calculating SSIM"):
87
+ batch_size = gt.size(0)
88
+ gt, pred = gt.to("cuda"), pred.to("cuda")
89
+ ssim_score += ssim(pred, gt) * batch_size
90
+ return ssim_score / len(dataloader.dataset)
91
+
92
+
93
+ @torch.no_grad()
94
+ def lpips(dataloader):
95
+ lpips_score = LearnedPerceptualImagePatchSimilarity(net_type='squeeze').to("cuda")
96
+ score = 0
97
+ for gt, pred in tqdm(dataloader, desc="Calculating LPIPS"):
98
+ batch_size = gt.size(0)
99
+ pred = pred.to("cuda")
100
+ gt = gt.to("cuda")
101
+ # LPIPS needs the images to be in the [-1, 1] range.
102
+ gt = (gt * 2) - 1
103
+ pred = (pred * 2) - 1
104
+ score += lpips_score(gt, pred) * batch_size
105
+ return score / len(dataloader.dataset)
106
+
107
+
108
+ def eval(args):
109
+ # Check gt_folder has images with target height, resize if not
110
+ pred_sample = os.listdir(args.pred_folder)[0]
111
+ gt_sample = os.listdir(args.gt_folder)[0]
112
+ img = Image.open(os.path.join(args.pred_folder, pred_sample))
113
+ gt_img = Image.open(os.path.join(args.gt_folder, gt_sample))
114
+ if img.height != gt_img.height:
115
+ title = "--"*30 + "Resizing GT Images to height {img.height}" + "--"*30
116
+ print(title)
117
+ args.gt_folder = copy_resize_gt(args.gt_folder, img.height)
118
+ print("-"*len(title))
119
+
120
+ # Form dataset
121
+ dataset = EvalDataset(args.gt_folder, args.pred_folder, img.height)
122
+ dataloader = torch.utils.data.DataLoader(
123
+ dataset, batch_size=args.batch_size, num_workers=args.num_workers, shuffle=False, drop_last=False
124
+ )
125
+
126
+ # Calculate Metrics
127
+ header = []
128
+ row = []
129
+ header = ["FID", "KID"]
130
+ fid_ = FID.compute_fid(args.gt_folder, args.pred_folder)
131
+ kid_ = FID.compute_kid(args.gt_folder, args.pred_folder) * 1000
132
+ row = [fid_, kid_]
133
+ if args.paired:
134
+ header += ["SSIM", "LPIPS"]
135
+ ssim_ = ssim(dataloader).item()
136
+ lpips_ = lpips(dataloader).item()
137
+ row += [ssim_, lpips_]
138
+
139
+ # Print Results
140
+ print("GT Folder : ", args.gt_folder)
141
+ print("Pred Folder: ", args.pred_folder)
142
+ table = PrettyTable()
143
+ table.field_names = header
144
+ table.add_row(row)
145
+ print(table)
146
+
147
+
148
+ if __name__ == "__main__":
149
+ import argparse
150
+ parser = argparse.ArgumentParser()
151
+ parser.add_argument("--gt_folder", type=str, required=True)
152
+ parser.add_argument("--pred_folder", type=str, required=True)
153
+ parser.add_argument("--paired", action="store_true")
154
+ parser.add_argument("--batch_size", type=int, default=16)
155
+ parser.add_argument("--num_workers", type=int, default=4)
156
+ args = parser.parse_args()
157
+
158
+ 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,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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="booksforcharlie/stable-diffusion-inpainting", # Change to a copy repo as runawayml delete original repo
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
+ skip_safety_check=True
266
+ )
267
+ # Dataset
268
+ if args.dataset_name == "vitonhd":
269
+ dataset = VITONHDTestDataset(args)
270
+ elif args.dataset_name == "dresscode":
271
+ dataset = DressCodeTestDataset(args)
272
+ else:
273
+ raise ValueError(f"Invalid dataset name {args.dataset}.")
274
+ print(f"Dataset {args.dataset_name} loaded, total {len(dataset)} pairs.")
275
+ dataloader = DataLoader(
276
+ dataset,
277
+ batch_size=args.batch_size,
278
+ shuffle=False,
279
+ num_workers=args.dataloader_num_workers
280
+ )
281
+ # Inference
282
+ generator = torch.Generator(device='cuda').manual_seed(args.seed)
283
+ args.output_dir = os.path.join(args.output_dir, f"{args.dataset_name}-{args.height}", "paired" if args.eval_pair else "unpaired")
284
+ if not os.path.exists(args.output_dir):
285
+ os.makedirs(args.output_dir)
286
+ for batch in tqdm(dataloader):
287
+ person_images = batch['person']
288
+ cloth_images = batch['cloth']
289
+ masks = batch['mask']
290
+ results = pipeline(
291
+ person_images,
292
+ cloth_images,
293
+ masks,
294
+ num_inference_steps=args.num_inference_steps,
295
+ guidance_scale=args.guidance_scale,
296
+ height=args.height,
297
+ width=args.width,
298
+ generator=generator,
299
+ )
300
+
301
+ if args.concat_eval_results or args.repaint:
302
+ person_images = to_pil_image(person_images)
303
+ cloth_images = to_pil_image(cloth_images)
304
+ masks = to_pil_image(masks)
305
+ for i, result in enumerate(results):
306
+ person_name = batch['person_name'][i]
307
+ output_path = os.path.join(args.output_dir, person_name)
308
+ if not os.path.exists(os.path.dirname(output_path)):
309
+ os.makedirs(os.path.dirname(output_path))
310
+ if args.repaint:
311
+ person_path, mask_path = dataset.data[batch['index'][i]]['person'], dataset.data[batch['index'][i]]['mask']
312
+ person_image= Image.open(person_path).resize(result.size, Image.LANCZOS)
313
+ mask = Image.open(mask_path).resize(result.size, Image.NEAREST)
314
+ result = repaint(person_image, mask, result)
315
+ if args.concat_eval_results:
316
+ w, h = result.size
317
+ concated_result = Image.new('RGB', (w*3, h))
318
+ concated_result.paste(person_images[i], (0, 0))
319
+ concated_result.paste(cloth_images[i], (w, 0))
320
+ concated_result.paste(result, (w*2, 0))
321
+ result = concated_result
322
+ result.save(output_path)
323
+
324
+ if __name__ == "__main__":
325
+ main()
preprocess_agnostic_mask.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )
41
+ for sub_folder in ['upper_body', 'lower_body', 'dresses']:
42
+ assert os.path.exists(os.path.join(args.data_root_path, sub_folder)), f"Folder {sub_folder} does not exist."
43
+ pair_txt = os.path.join(args.data_root_path, sub_folder, 'test_pairs_paired.txt')
44
+ assert os.path.exists(pair_txt), f"File {pair_txt} does not exist."
45
+ cloth_type = {'upper_body': 'upper', 'lower_body': 'lower', 'dresses': 'overall'}[sub_folder]
46
+ with open(pair_txt, 'r') as f:
47
+ lines = f.readlines()
48
+ output_dir = os.path.join(args.data_root_path, sub_folder, 'agnostic_masks')
49
+ if not os.path.exists(output_dir):
50
+ os.makedirs(output_dir)
51
+ for line in tqdm(lines, desc=f"Processing {sub_folder}"):
52
+ person_img, _ = line.strip().split(" ")
53
+ if os.path.exists(os.path.join(output_dir, person_img.replace('.jpg', '.png'))):
54
+ continue
55
+ mask = automasker(
56
+ os.path.join(args.data_root_path, sub_folder, 'images', person_img),
57
+ cloth_type
58
+ )['mask']
59
+ mask.save(os.path.join(output_dir, person_img.replace('.jpg', '.png')))
60
+
61
+ if __name__ == "__main__":
62
+ args = parse_args()
63
+ main(args)
64
+
requirements.txt ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch==2.1.2
2
+ torchvision==0.16.2
3
+ accelerate==0.31.0
4
+ diffusers==0.29.2
5
+ huggingface_hub==0.23.4
6
+ matplotlib==3.9.1
7
+ numpy==1.26.4
8
+ opencv_python==4.10.0.84
9
+ pillow==10.3.0
10
+ PyYAML==6.0.1
11
+ scipy==1.13.1
12
+ setuptools==51.0.0
13
+ scikit-image==0.24.0
14
+ tqdm==4.66.4
15
+ transformers==4.27.3
16
+ fvcore==0.1.5.post20221221
17
+ cloudpickle==3.0.0
18
+ omegaconf==2.3.0
19
+ pycocotools==2.0.8
20
+ av==12.3.0
21
+ gradio==4.41.0
utils.py ADDED
@@ -0,0 +1,399 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 repaint_result(result, person_image, mask_image):
172
+ result, person, mask = np.array(result), np.array(person_image), np.array(mask_image)
173
+ # expand the mask to 3 channels & to 0~1
174
+ mask = np.expand_dims(mask, axis=2)
175
+ mask = mask / 255.0
176
+ # mask for result, ~mask for person
177
+ result_ = result * mask + person * (1 - mask)
178
+ return Image.fromarray(result_.astype(np.uint8))
179
+
180
+
181
+ def prepare_image(image):
182
+ if isinstance(image, torch.Tensor):
183
+ # Batch single image
184
+ if image.ndim == 3:
185
+ image = image.unsqueeze(0)
186
+ image = image.to(dtype=torch.float32)
187
+ else:
188
+ # preprocess image
189
+ if isinstance(image, (PIL.Image.Image, np.ndarray)):
190
+ image = [image]
191
+ if isinstance(image, list) and isinstance(image[0], PIL.Image.Image):
192
+ image = [np.array(i.convert("RGB"))[None, :] for i in image]
193
+ image = np.concatenate(image, axis=0)
194
+ elif isinstance(image, list) and isinstance(image[0], np.ndarray):
195
+ image = np.concatenate([i[None, :] for i in image], axis=0)
196
+ image = image.transpose(0, 3, 1, 2)
197
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
198
+ return image
199
+
200
+
201
+ def prepare_mask_image(mask_image):
202
+ if isinstance(mask_image, torch.Tensor):
203
+ if mask_image.ndim == 2:
204
+ # Batch and add channel dim for single mask
205
+ mask_image = mask_image.unsqueeze(0).unsqueeze(0)
206
+ elif mask_image.ndim == 3 and mask_image.shape[0] == 1:
207
+ # Single mask, the 0'th dimension is considered to be
208
+ # the existing batch size of 1
209
+ mask_image = mask_image.unsqueeze(0)
210
+ elif mask_image.ndim == 3 and mask_image.shape[0] != 1:
211
+ # Batch of mask, the 0'th dimension is considered to be
212
+ # the batching dimension
213
+ mask_image = mask_image.unsqueeze(1)
214
+
215
+ # Binarize mask
216
+ mask_image[mask_image < 0.5] = 0
217
+ mask_image[mask_image >= 0.5] = 1
218
+ else:
219
+ # preprocess mask
220
+ if isinstance(mask_image, (PIL.Image.Image, np.ndarray)):
221
+ mask_image = [mask_image]
222
+
223
+ if isinstance(mask_image, list) and isinstance(mask_image[0], PIL.Image.Image):
224
+ mask_image = np.concatenate(
225
+ [np.array(m.convert("L"))[None, None, :] for m in mask_image], axis=0
226
+ )
227
+ mask_image = mask_image.astype(np.float32) / 255.0
228
+ elif isinstance(mask_image, list) and isinstance(mask_image[0], np.ndarray):
229
+ mask_image = np.concatenate([m[None, None, :] for m in mask_image], axis=0)
230
+
231
+ mask_image[mask_image < 0.5] = 0
232
+ mask_image[mask_image >= 0.5] = 1
233
+ mask_image = torch.from_numpy(mask_image)
234
+
235
+ return mask_image
236
+
237
+
238
+ def numpy_to_pil(images):
239
+ """
240
+ Convert a numpy image or a batch of images to a PIL image.
241
+ """
242
+ if images.ndim == 3:
243
+ images = images[None, ...]
244
+ images = (images * 255).round().astype("uint8")
245
+ if images.shape[-1] == 1:
246
+ # special case for grayscale (single channel) images
247
+ pil_images = [Image.fromarray(image.squeeze(), mode="L") for image in images]
248
+ else:
249
+ pil_images = [Image.fromarray(image) for image in images]
250
+
251
+ return pil_images
252
+
253
+
254
+ def tensor_to_image(tensor: torch.Tensor):
255
+ """
256
+ Converts a torch tensor to PIL Image.
257
+ """
258
+ assert tensor.dim() == 3, "Input tensor should be 3-dimensional."
259
+ assert tensor.dtype == torch.float32, "Input tensor should be float32."
260
+ assert (
261
+ tensor.min() >= 0 and tensor.max() <= 1
262
+ ), "Input tensor should be in range [0, 1]."
263
+ tensor = tensor.cpu()
264
+ tensor = tensor * 255
265
+ tensor = tensor.permute(1, 2, 0)
266
+ tensor = tensor.numpy().astype(np.uint8)
267
+ image = Image.fromarray(tensor)
268
+ return image
269
+
270
+
271
+ def concat_images(images: List[Image.Image], divider: int = 4, cols: int = 4):
272
+ """
273
+ Concatenates images horizontally and with
274
+ """
275
+ widths = [image.size[0] for image in images]
276
+ heights = [image.size[1] for image in images]
277
+ total_width = cols * max(widths)
278
+ total_width += divider * (cols - 1)
279
+ # `col` images each row
280
+ rows = math.ceil(len(images) / cols)
281
+ total_height = max(heights) * rows
282
+ # add divider between rows
283
+ total_height += divider * (len(heights) // cols - 1)
284
+
285
+ # all black image
286
+ concat_image = Image.new("RGB", (total_width, total_height), (0, 0, 0))
287
+
288
+ x_offset = 0
289
+ y_offset = 0
290
+ for i, image in enumerate(images):
291
+ concat_image.paste(image, (x_offset, y_offset))
292
+ x_offset += image.size[0] + divider
293
+ if (i + 1) % cols == 0:
294
+ x_offset = 0
295
+ y_offset += image.size[1] + divider
296
+
297
+ return concat_image
298
+
299
+
300
+ def read_prompt_file(prompt_file: str):
301
+ if prompt_file is not None and os.path.isfile(prompt_file):
302
+ with open(prompt_file, "r") as sample_prompt_file:
303
+ sample_prompts = sample_prompt_file.readlines()
304
+ sample_prompts = [sample_prompt.strip() for sample_prompt in sample_prompts]
305
+ else:
306
+ sample_prompts = []
307
+ return sample_prompts
308
+
309
+
310
+ def save_tensors_to_npz(tensors: torch.Tensor, paths: List[str]):
311
+ assert len(tensors) == len(paths), "Length of tensors and paths should be the same!"
312
+ for tensor, path in zip(tensors, paths):
313
+ np.savez_compressed(path, latent=tensor.cpu().numpy())
314
+
315
+
316
+ def deepspeed_zero_init_disabled_context_manager():
317
+ """
318
+ returns either a context list that includes one that will disable zero.Init or an empty context list
319
+ """
320
+ deepspeed_plugin = (
321
+ AcceleratorState().deepspeed_plugin
322
+ if accelerate.state.is_initialized()
323
+ else None
324
+ )
325
+ if deepspeed_plugin is None:
326
+ return []
327
+
328
+ return [deepspeed_plugin.zero3_init_context_manager(enable=False)]
329
+
330
+
331
+ def is_xformers_available():
332
+ try:
333
+ import xformers
334
+
335
+ xformers_version = version.parse(xformers.__version__)
336
+ if xformers_version == version.parse("0.0.16"):
337
+ print(
338
+ "xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, "
339
+ "please update xFormers to at least 0.0.17. "
340
+ "See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
341
+ )
342
+ return True
343
+ except ImportError:
344
+ raise ValueError(
345
+ "xformers is not available. Make sure it is installed correctly"
346
+ )
347
+
348
+
349
+
350
+ def resize_and_crop(image, size):
351
+ # Crop to size ratio
352
+ w, h = image.size
353
+ target_w, target_h = size
354
+ if w / h < target_w / target_h:
355
+ new_w = w
356
+ new_h = w * target_h // target_w
357
+ else:
358
+ new_h = h
359
+ new_w = h * target_w // target_h
360
+ image = image.crop(
361
+ ((w - new_w) // 2, (h - new_h) // 2, (w + new_w) // 2, (h + new_h) // 2)
362
+ )
363
+ # resize
364
+ image = image.resize(size, Image.LANCZOS)
365
+ return image
366
+
367
+
368
+ def resize_and_padding(image, size):
369
+ # Padding to size ratio
370
+ w, h = image.size
371
+ target_w, target_h = size
372
+ if w / h < target_w / target_h:
373
+ new_h = target_h
374
+ new_w = w * target_h // h
375
+ else:
376
+ new_w = target_w
377
+ new_h = h * target_w // w
378
+ image = image.resize((new_w, new_h), Image.LANCZOS)
379
+ # padding
380
+ padding = Image.new("RGB", size, (255, 255, 255))
381
+ padding.paste(image, ((target_w - new_w) // 2, (target_h - new_h) // 2))
382
+ return padding
383
+
384
+
385
+ def scan_files_in_dir(directory, postfix: Set[str] = None, progress_bar: tqdm = None) -> list:
386
+ file_list = []
387
+ progress_bar = tqdm(total=0, desc=f"Scanning", ncols=100) if progress_bar is None else progress_bar
388
+ for entry in os.scandir(directory):
389
+ if entry.is_file():
390
+ if postfix is None or os.path.splitext(entry.path)[1] in postfix:
391
+ file_list.append(entry)
392
+ progress_bar.total += 1
393
+ progress_bar.update(1)
394
+ elif entry.is_dir():
395
+ file_list += scan_files_in_dir(entry.path, postfix=postfix, progress_bar=progress_bar)
396
+ return file_list
397
+
398
+ if __name__ == "__main__":
399
+ ...