Upload 585 files
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .gitattributes+26
- .gitignoreAdded+162
- LICENSEAdded+107
- README.md+129-13
- examples/garment/0.jpgAdded
- examples/garment/0012.jpgAdded
- examples/garment/0023.jpgAdded
- examples/garment/0047.jpgAdded
- examples/garment/0049.jpgAdded
- examples/garment/0317.jpgAdded
- examples/garment/0327.jpgAdded
- examples/garment/0329.jpgAdded
- examples/garment/0362.jpgAdded
- examples/garment/1.jpgAdded
- examples/garment/10.jpgAdded
- examples/garment/11.jpgAdded
- examples/garment/12.pngAdded
- examples/garment/2.jpgAdded
- examples/garment/3.jpgAdded
- examples/garment/4.jpgAdded
- examples/garment/5.jpgAdded
- examples/garment/6.jpegAdded
- examples/garment/7.jpgAdded
- examples/garment/8.jpgAdded
- examples/garment/9.pngAdded
- examples/model/0.jpgAdded
- examples/model/0083.jpgAdded
- examples/model/0179.jpgAdded
- examples/model/0220.jpgAdded
- examples/model/0223.jpgAdded
- examples/model/0274.jpgAdded
- examples/model/0279.jpgAdded
- examples/model/0303.jpgAdded
- examples/model/0347.jpgAdded
- examples/model/1.jpgAdded
- examples/model/2.jpgAdded
- examples/model/3.pngAdded
- examples/model/4.jpgAdded
- examples/model/5.jpgAdded
- examples/model/6.jpgAdded
- examples/model/7.jpgAdded
- examples/model/8.pngAdded
- gradio_sd3.pyAdded+315
- preprocess/dwpose/__init__.pyAdded+68
- preprocess/dwpose/onnxdet.pyAdded+125
- preprocess/dwpose/onnxpose.pyAdded+360
- preprocess/dwpose/util.pyAdded+297
- preprocess/dwpose/wholebody.pyAdded+46
- preprocess/humanparsing/datasets/__init__.pyAdded
- preprocess/humanparsing/datasets/datasets.pyAdded+201
58 unmodified lines59606158 unmodified linesFitDiT-main/resource/img/mask_offset.jpg filter=lfs diff=lfs merge=lfs -textFitDiT-main/resource/img/QQ_group.jpg filter=lfs diff=lfs merge=lfs -textFitDiT-main/resource/img/teaser.jpg filter=lfs diff=lfs merge=lfs -text58 unmodified lines596061626364656667686970717273747576777879808182838485868758 unmodified linesFitDiT-main/resource/img/mask_offset.jpg filter=lfs diff=lfs merge=lfs -textFitDiT-main/resource/img/QQ_group.jpg filter=lfs diff=lfs merge=lfs -textFitDiT-main/resource/img/teaser.jpg filter=lfs diff=lfs merge=lfs -textexamples/garment/0012.jpg filter=lfs diff=lfs merge=lfs -textexamples/garment/0049.jpg filter=lfs diff=lfs merge=lfs -textexamples/garment/0317.jpg filter=lfs diff=lfs merge=lfs -textexamples/garment/0327.jpg filter=lfs diff=lfs merge=lfs -textexamples/garment/0329.jpg filter=lfs diff=lfs merge=lfs -textexamples/garment/0362.jpg filter=lfs diff=lfs merge=lfs -textexamples/garment/1.jpg filter=lfs diff=lfs merge=lfs -textexamples/garment/12.png filter=lfs diff=lfs merge=lfs -textexamples/garment/6.jpeg filter=lfs diff=lfs merge=lfs -textexamples/garment/7.jpg filter=lfs diff=lfs merge=lfs -textexamples/garment/8.jpg filter=lfs diff=lfs merge=lfs -textexamples/garment/9.png filter=lfs diff=lfs merge=lfs -textexamples/model/0.jpg filter=lfs diff=lfs merge=lfs -textexamples/model/0083.jpg filter=lfs diff=lfs merge=lfs -textexamples/model/0179.jpg filter=lfs diff=lfs merge=lfs -textexamples/model/0274.jpg filter=lfs diff=lfs merge=lfs -textexamples/model/0279.jpg filter=lfs diff=lfs merge=lfs -textexamples/model/0303.jpg filter=lfs diff=lfs merge=lfs -textexamples/model/0347.jpg filter=lfs diff=lfs merge=lfs -textexamples/model/3.png filter=lfs diff=lfs merge=lfs -textexamples/model/7.jpg filter=lfs diff=lfs merge=lfs -textexamples/model/8.png filter=lfs diff=lfs merge=lfs -textresource/img/manually_adjust.jpg filter=lfs diff=lfs merge=lfs -textresource/img/mask_offset.jpg filter=lfs diff=lfs merge=lfs -textresource/img/QQ_group.jpg filter=lfs diff=lfs merge=lfs -textresource/img/teaser.jpg filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162# Byte-compiled / optimized / DLL files__pycache__/*.py[cod]*$py.class
# C extensions*.so
# Distribution / packaging.Pythonbuild/develop-eggs/dist/downloads/eggs/.eggs/lib/lib64/parts/sdist/var/wheels/share/python-wheels/*.egg-info/.installed.cfg*.eggMANIFEST
# PyInstaller# Usually these files are written by a python script from a template# before PyInstaller builds the exe, so as to inject date/other infos into it.*.manifest*.spec
# Installer logspip-log.txtpip-delete-this-directory.txt
# Unit test / coverage reportshtmlcov/.tox/.nox/.coverage.coverage.*.cachenosetests.xmlcoverage.xml*.cover*.py,cover.hypothesis/.pytest_cache/cover/
# Translations*.mo*.pot
# Django stuff:*.loglocal_settings.pydb.sqlite3db.sqlite3-journal
# Flask stuff:instance/.webassets-cache
# Scrapy stuff:.scrapy
# Sphinx documentationdocs/_build/
# PyBuilder.pybuilder/target/
# Jupyter Notebook.ipynb_checkpoints
# IPythonprofile_default/ipython_config.py
# pyenv# For a library or package, you might want to ignore these files since the code is# intended to run in multiple environments; otherwise, check them in:# .python-version
# pipenv# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.# However, in case of collaboration, if having platform-specific dependencies or dependencies# having no cross-platform support, pipenv may install dependencies that don't work, or not# install all needed dependencies.#Pipfile.lock
# poetry# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.# This is especially recommended for binary packages to ensure reproducibility, and is more# commonly ignored for libraries.# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control#poetry.lock
# pdm# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.#pdm.lock# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it# in version control.# https://pdm.fming.dev/latest/usage/project/#working-with-version-control.pdm.toml.pdm-python.pdm-build/
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm__pypackages__/
# Celery stuffcelerybeat-schedulecelerybeat.pid
# SageMath parsed files*.sage.py
# Environments.env.venvenv/venv/ENV/env.bak/venv.bak/
# Spyder project settings.spyderproject.spyproject
# Rope project settings.ropeproject
# mkdocs documentation/site
# mypy.mypy_cache/.dmypy.jsondmypy.json
# Pyre type checker.pyre/
# pytype static type analyzer.pytype/
# Cython debug symbolscython_debug/
# PyCharm# JetBrains specific template is maintained in a separate JetBrains.gitignore that can# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore# and can be added to the global gitignore or merged into this file. For a more nuclear# option (not recommended) you can uncomment the following to ignore the entire idea folder.#.idea/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
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.
Using Creative Commons Public Licenses
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.
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
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
Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International Public License
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.
Section 1 – Definitions.
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.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.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.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.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.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.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.h. Licensed Material means the artistic or literary work, database, or other material to which the Licensor applied this Public License.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.j. Licensor means the individual(s) or entity(ies) granting rights under this Public License.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.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.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.n. You means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.Section 2 – Scope.
a. License grant.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:A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; andB. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.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.3. Term. The term of this Public License is specified in Section 6(a).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.5. Downstream recipients.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.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.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.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).b. Other rights.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.2. Patent and trademark rights are not licensed under this Public License.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.Section 3 – License Conditions.
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
a. Attribution.1. If You Share the Licensed Material (including in modified form), You must:A. retain the following if it is supplied by the Licensor with the Licensed Material: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);ii. a copyright notice;iii. a notice that refers to this Public License;iv. a notice that refers to the disclaimer of warranties;v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; andC. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License.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.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.b. ShareAlike.In addition to the conditions in Section 3(a), if You Share Adapted Material You produce, the following conditions also apply.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.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.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.Section 4 – Sui Generis Database Rights.
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
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;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); andc. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database.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.Section 5 – Disclaimer of Warranties and Limitation of Liability.
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.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.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.Section 6 – Term and Termination.
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.b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or2. upon express reinstatement by the Licensor.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.
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.d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.Section 7 – Other Terms and Conditions.
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.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.Section 8 – Interpretation.
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.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.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.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.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.
Creative Commons may be contacted at creativecommons.org.12345678910111213---title: FitTonemoji: 🏃colorFrom: graycolorTo: yellowsdk: gradiosdk_version: 5.33.0app_file: app.pypinned: falselicense: mit---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129# FitDiT: Advancing the Authentic Garment Details for High-fidelity Virtual Try-on<div style="display: flex; justify-content: center; align-items: center;"><a href="https://arxiv.org/abs/2411.10499" style="margin: 0 2px;"><img src='https://img.shields.io/badge/arXiv-2411.10499-red?style=flat&logo=arXiv&logoColor=red' alt='arxiv'></a><a href="https://github.com/BoyuanJiang/FitDiT" style="margin: 0 2px;"><img src='https://img.shields.io/badge/GitHub-Repo-blue?style=flat&logo=GitHub' alt='GitHub'></a><a href="https://huggingface.co/spaces/BoyuanJiang/FitDiT" style="margin: 0 2px;"><img src='https://img.shields.io/badge/Space-ZeroGPU-orange?style=flat&logo=Gradio&logoColor=red' alt='Demo'></a><a href="http://demo.fitdit.byjiang.com/" style="margin: 0 2px;"><img src='https://img.shields.io/badge/Demo-Gradio-gold?style=flat&logo=Gradio&logoColor=red' alt='Demo'></a><a href='https://huggingface.co/BoyuanJiang/FitDiT' style="margin: 0 2px;"><img src='https://img.shields.io/badge/Hugging Face-ckpts-orange?style=flat&logo=HuggingFace&logoColor=orange' alt='huggingface'></a><a href='https://byjiang.com/FitDiT/' style="margin: 0 2px;"><img src='https://img.shields.io/badge/Webpage-Project-silver?style=flat&logo=&logoColor=orange' alt='webpage'></a><a href="https://raw.githubusercontent.com/BoyuanJiang/FitDiT/refs/heads/main/LICENSE" style="margin: 0 2px;"><img src='https://img.shields.io/badge/License-CC BY--NC--SA--4.0-lightgreen?style=flat&logo=Lisence' alt='License'></a></div><p align="center">👋 Join our <a href="resource/img/QQ_group.jpg" target="_blank">QQ Chat Group</a></p><p align="center">**FitDiT** is designed for high-fidelity virtual try-on using Diffusion Transformers (DiT).<div align="center"><img src="resource/img/teaser.jpg" width="100%" height="100%"/></div>## Updates- **`2025/1/16`**: We provide the [ComfyUI version of FitDiT](https://github.com/BoyuanJiang/FitDiT/tree/FitDiT-ComfyUI), you can use FitDiT in ComfyUI now.- **`2025/1/9`**: We provide a [**Huggingface Space**](https://huggingface.co/spaces/BoyuanJiang/FitDiT) of FitDiT, thanks for Huggingface community GPU grant for providing the GPU resources.- **`2024/12/20`**: The FitDiT [**model weight**](https://huggingface.co/BoyuanJiang/FitDiT) is available.- **`2024/12/17`**: Inference code is released.- **`2024/12/4`**: Our [**Online Demo**](http://demo.fitdit.byjiang.com/) is released.- **`2024/11/25`**: Our [**Complex Virtual Dressing Dataset (CVDD)**](https://huggingface.co/datasets/BoyuanJiang/CVDD) is released.- **`2024/11/15`**: Our [**FitDiT paper**](https://arxiv.org/abs/2411.10499) is available.## Gradio DemoOur algorithm is divided into two steps. The first step is to generate the mask of the try-on area, and the second step is to try-on in the mask area.### Step1: Run MaskYou can simpley get try-on mask by click **Step1: Run Mask** at the right side of gradio demo. If the automatically generated mask are not well covered the area where you want to try-on, you can either adjust the mask by:1. Drag the slider of *mask offset top*, *mask offset bottom*, *mask offset left* or *mask offset right* and then click **Step1: Run Mask** button, this will re-generate mask.2. Using the brush or eraser tool to edit the automatically generated mask### Step2: Run Try-onAfter generating a suitable mask, you can get the try-on results by click **Step2: Run Try-on**. In the Try-on resolution drop-down box, you can select a suitable processing resolution. In our online demo, the default resolution is 1152x1536, which means that the input model image and garment image will be pad and resized to this resolution before being fed into the model.## Local DemoFirst apply access of FitDiT [model weight](https://huggingface.co/BoyuanJiang/FitDiT), then clone model to *local_model_dir*### EnviromentWe test our model with following enviroment```torch==2.4.0torchvision==0.19.0diffusers==0.31.0transformers==4.39.3gradio==5.8.0onnxruntime-gpu==1.20.1```### Run gradio locally```# Run model with bf16 without any offload, fastest inference and most memorypython gradio_sd3.py --model_path local_model_dir# Run model with fp16python gradio_sd3.py --model_path local_model_dir --fp16# Run model with fp16 and cpu offload, moderate inference and moderate memorypython gradio_sd3.py --model_path local_model_dir --fp16 --offload# Run model with fp16 and aggressive cpu offload, slowest inference and less memorypython gradio_sd3.py --model_path local_model_dir --fp16 --aggressive_offload```## Third-Party CreationsWe found there've been some 3rd party applications or tutorial based on our FitDiT. Many thanks for their contribution to the community!If you have any related work that you would like to see displayed, please submit it in the [issue](https://github.com/BoyuanJiang/FitDiT/issues/new).These projects have not been verified by us. If you have any questions, please seek help from the original project authors.### Tutorial- A tutorial of using the comfyui version of FitDiT, from `T8star-Aix` at [youtube](https://www.youtube.com/watch?v=qBQtYYa-bvs) or [bilibili](https://www.bilibili.com/video/BV1U4wpe6EkD/)### Applications- Local one-click integration package of FitDiT, which can be found at [deepface forum](https://deepface.cc/thread-517-1-1.html)## Star History[](https://star-history.com/#BoyuanJiang/FitDiT&Date)## ContactThis model can only be used **for non-commercial use**. For commercial use, please visit [Tencent Cloud](https://cloud.tencent.com/document/product/1668/108532) for support.## CitationIf you find our work helpful for your research, please consider citing our work.```@misc{jiang2024fitditadvancingauthenticgarment,title={FitDiT: Advancing the Authentic Garment Details for High-fidelity Virtual Try-on},author={Boyuan Jiang and Xiaobin Hu and Donghao Luo and Qingdong He and Chengming Xu and Jinlong Peng and Jiangning Zhang and Chengjie Wang and Yunsheng Wu and Yanwei Fu},year={2024},eprint={2411.10499},archivePrefix={arXiv},primaryClass={cs.CV},url={https://arxiv.org/abs/2411.10499},}```
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315import gradio as grimport osimport mathfrom preprocess.humanparsing.run_parsing import Parsingfrom preprocess.dwpose import DWposeDetectorfrom transformers import CLIPVisionModelWithProjection, CLIPImageProcessorimport torchimport torch.nn as nnfrom src.pose_guider import PoseGuiderfrom PIL import Imagefrom src.utils_mask import get_mask_locationimport numpy as npfrom src.pipeline_stable_diffusion_3_tryon import StableDiffusion3TryOnPipelinefrom src.transformer_sd3_garm import SD3Transformer2DModel as SD3Transformer2DModel_Garmfrom src.transformer_sd3_vton import SD3Transformer2DModel as SD3Transformer2DModel_Vtonimport cv2import random
example_path = os.path.join(os.path.dirname(__file__), 'examples')
class FitDiTGenerator: def __init__(self, model_root, offload=False, aggressive_offload=False, device="cuda:0", with_fp16=False): weight_dtype = torch.float16 if with_fp16 else torch.bfloat16 transformer_garm = SD3Transformer2DModel_Garm.from_pretrained(os.path.join(model_root, "transformer_garm"), torch_dtype=weight_dtype) transformer_vton = SD3Transformer2DModel_Vton.from_pretrained(os.path.join(model_root, "transformer_vton"), torch_dtype=weight_dtype) pose_guider = PoseGuider(conditioning_embedding_channels=1536, conditioning_channels=3, block_out_channels=(32, 64, 256, 512)) pose_guider.load_state_dict(torch.load(os.path.join(model_root, "pose_guider", "diffusion_pytorch_model.bin"))) image_encoder_large = CLIPVisionModelWithProjection.from_pretrained("openai/clip-vit-large-patch14", torch_dtype=weight_dtype) image_encoder_bigG = CLIPVisionModelWithProjection.from_pretrained("laion/CLIP-ViT-bigG-14-laion2B-39B-b160k", torch_dtype=weight_dtype) pose_guider.to(device=device, dtype=weight_dtype) image_encoder_large.to(device=device) image_encoder_bigG.to(device=device) self.pipeline = StableDiffusion3TryOnPipeline.from_pretrained(model_root, torch_dtype=weight_dtype, transformer_garm=transformer_garm, transformer_vton=transformer_vton, pose_guider=pose_guider, image_encoder_large=image_encoder_large, image_encoder_bigG=image_encoder_bigG) self.pipeline.to(device) if offload: self.pipeline.enable_model_cpu_offload() self.dwprocessor = DWposeDetector(model_root=model_root, device='cpu') self.parsing_model = Parsing(model_root=model_root, device='cpu') elif aggressive_offload: self.pipeline.enable_sequential_cpu_offload() self.dwprocessor = DWposeDetector(model_root=model_root, device='cpu') self.parsing_model = Parsing(model_root=model_root, device='cpu') else: self.pipeline.to(device) self.dwprocessor = DWposeDetector(model_root=model_root, device=device) self.parsing_model = Parsing(model_root=model_root, device=device) def generate_mask(self, vton_img, category, offset_top, offset_bottom, offset_left, offset_right): with torch.inference_mode(): vton_img = Image.open(vton_img) vton_img_det = resize_image(vton_img) pose_image, keypoints, _, candidate = self.dwprocessor(np.array(vton_img_det)[:,:,::-1]) candidate[candidate<0]=0 candidate = candidate[0]
candidate[:, 0]*=vton_img_det.width candidate[:, 1]*=vton_img_det.height
pose_image = pose_image[:,:,::-1] #rgb pose_image = Image.fromarray(pose_image) model_parse, _ = self.parsing_model(vton_img_det)
mask, mask_gray = get_mask_location(category, model_parse, \ candidate, model_parse.width, model_parse.height, \ offset_top, offset_bottom, offset_left, offset_right) mask = mask.resize(vton_img.size) mask_gray = mask_gray.resize(vton_img.size) mask = mask.convert("L") mask_gray = mask_gray.convert("L") masked_vton_img = Image.composite(mask_gray, vton_img, mask)
im = {} im['background'] = np.array(vton_img.convert("RGBA")) im['layers'] = [np.concatenate((np.array(mask_gray.convert("RGB")), np.array(mask)[:,:,np.newaxis]),axis=2)] im['composite'] = np.array(masked_vton_img.convert("RGBA")) return im, pose_image
def process(self, vton_img, garm_img, pre_mask, pose_image, n_steps, image_scale, seed, num_images_per_prompt, resolution): assert resolution in ["768x1024", "1152x1536", "1536x2048"] new_width, new_height = resolution.split("x") new_width = int(new_width) new_height = int(new_height) with torch.inference_mode(): garm_img = Image.open(garm_img) vton_img = Image.open(vton_img)
model_image_size = vton_img.size garm_img, _, _ = pad_and_resize(garm_img, new_width=new_width, new_height=new_height) vton_img, pad_w, pad_h = pad_and_resize(vton_img, new_width=new_width, new_height=new_height)
mask = pre_mask["layers"][0][:,:,3] mask = Image.fromarray(mask) mask, _, _ = pad_and_resize(mask, new_width=new_width, new_height=new_height, pad_color=(0,0,0)) mask = mask.convert("L") pose_image = Image.fromarray(pose_image) pose_image, _, _ = pad_and_resize(pose_image, new_width=new_width, new_height=new_height, pad_color=(0,0,0)) if seed==-1: seed = random.randint(0, 2147483647) res = self.pipeline( height=new_height, width=new_width, guidance_scale=image_scale, num_inference_steps=n_steps, generator=torch.Generator("cpu").manual_seed(seed), cloth_image=garm_img, model_image=vton_img, mask=mask, pose_image=pose_image, num_images_per_prompt=num_images_per_prompt ).images for idx in range(len(res)): res[idx] = unpad_and_resize(res[idx], pad_w, pad_h, model_image_size[0], model_image_size[1]) return res
def pad_and_resize(im, new_width=768, new_height=1024, pad_color=(255, 255, 255), mode=Image.LANCZOS): old_width, old_height = im.size ratio_w = new_width / old_width ratio_h = new_height / old_height if ratio_w < ratio_h: new_size = (new_width, round(old_height * ratio_w)) else: new_size = (round(old_width * ratio_h), new_height) im_resized = im.resize(new_size, mode)
pad_w = math.ceil((new_width - im_resized.width) / 2) pad_h = math.ceil((new_height - im_resized.height) / 2)
new_im = Image.new('RGB', (new_width, new_height), pad_color) new_im.paste(im_resized, (pad_w, pad_h))
return new_im, pad_w, pad_h
def unpad_and_resize(padded_im, pad_w, pad_h, original_width, original_height): width, height = padded_im.size left = pad_w top = pad_h right = width - pad_w bottom = height - pad_h cropped_im = padded_im.crop((left, top, right, bottom))
resized_im = cropped_im.resize((original_width, original_height), Image.LANCZOS)
return resized_im
def resize_image(img, target_size=768): width, height = img.size if width < height: scale = target_size / width else: scale = target_size / height new_width = int(round(width * scale)) new_height = int(round(height * scale)) resized_img = img.resize((new_width, new_height), Image.LANCZOS) return resized_img
HEADER = """<h1 style="text-align: center;"> FitDiT: Advancing the Authentic Garment Details for High-fidelity Virtual Try-on </h1><div style="display: flex; justify-content: center; align-items: center;"> <a href="https://github.com/BoyuanJiang/FitDiT" style="margin: 0 2px;"> <img src='https://img.shields.io/badge/GitHub-Repo-blue?style=flat&logo=GitHub' alt='GitHub'> </a> <a href="https://arxiv.org/abs/2411.10499" style="margin: 0 2px;"> <img src='https://img.shields.io/badge/arXiv-2411.10499-red?style=flat&logo=arXiv&logoColor=red' alt='arxiv'> </a> <a href="http://demo.fitdit.byjiang.com/" style="margin: 0 2px;"> <img src='https://img.shields.io/badge/Demo-Gradio-gold?style=flat&logo=Gradio&logoColor=red' alt='Demo'> </a> <a href='https://byjiang.com/FitDiT/' style="margin: 0 2px;"> <img src='https://img.shields.io/badge/Webpage-Project-silver?style=flat&logo=&logoColor=orange' alt='webpage'> </a> <a href="https://raw.githubusercontent.com/BoyuanJiang/FitDiT/refs/heads/main/LICENSE" style="margin: 0 2px;"> <img src='https://img.shields.io/badge/License-CC BY--NC--SA--4.0-lightgreen?style=flat&logo=Lisence' alt='License'> </a></div><br>FitDiT is designed for high-fidelity virtual try-on using Diffusion Transformers (DiT). It can only be used for <b>Non-commercial Use</b>.<br>If you like our work, please star <a href="https://github.com/BoyuanJiang/FitDiT" style="color: blue; text-decoration: underline;">our github repository</a>."""
def create_demo(model_path, device, offload, aggressive_offload, with_fp16): generator = FitDiTGenerator(model_path, offload, aggressive_offload, device, with_fp16) with gr.Blocks(title="FitDiT") as demo: gr.Markdown(HEADER) with gr.Row(): with gr.Column(): vton_img = gr.Image(label="Model", sources=None, type="filepath", height=512)
with gr.Column(): garm_img = gr.Image(label="Garment", sources=None, type="filepath", height=512) with gr.Row(): with gr.Column(): masked_vton_img = gr.ImageEditor(label="masked_vton_img", type="numpy", height=512, interactive=True, brush=gr.Brush(default_color="rgb(127, 127, 127)", colors=[ "rgb(128, 128, 128)" ])) pose_image = gr.Image(label="pose_image", visible=False, interactive=False) with gr.Column(): result_gallery = gr.Gallery(label="Output", elem_id="output-img", interactive=False, columns=[2], rows=[2], object_fit="contain", height="auto") with gr.Row(): with gr.Column(): offset_top = gr.Slider(label="mask offset top", minimum=-200, maximum=200, step=1, value=0) with gr.Column(): offset_bottom = gr.Slider(label="mask offset bottom", minimum=-200, maximum=200, step=1, value=0) with gr.Column(): offset_left = gr.Slider(label="mask offset left", minimum=-200, maximum=200, step=1, value=0) with gr.Column(): offset_right = gr.Slider(label="mask offset right", minimum=-200, maximum=200, step=1, value=0) with gr.Row(): with gr.Column(): n_steps = gr.Slider(label="Steps", minimum=15, maximum=30, value=20, step=1) with gr.Column(): image_scale = gr.Slider(label="Guidance scale", minimum=1.0, maximum=5.0, value=2, step=0.1) with gr.Column(): seed = gr.Slider(label="Seed", minimum=-1, maximum=2147483647, step=1, value=-1) with gr.Column(): num_images_per_prompt = gr.Slider(label="num_images", minimum=1, maximum=4, step=1, value=1)
with gr.Row(): with gr.Column(): example = gr.Examples( label="Model (upper-body)", inputs=vton_img, examples_per_page=7, examples=[ os.path.join(example_path, 'model/0279.jpg'), os.path.join(example_path, 'model/0303.jpg'), os.path.join(example_path, 'model/2.jpg'), os.path.join(example_path, 'model/0083.jpg'), ]) example = gr.Examples( label="Model (upper-body/lower-body)", inputs=vton_img, examples_per_page=7, examples=[ os.path.join(example_path, 'model/0.jpg'), os.path.join(example_path, 'model/0179.jpg'), os.path.join(example_path, 'model/0223.jpg'), os.path.join(example_path, 'model/0347.jpg'), ]) example = gr.Examples( label="Model (dresses)", inputs=vton_img, examples_per_page=7, examples=[ os.path.join(example_path, 'model/4.jpg'), os.path.join(example_path, 'model/5.jpg'), os.path.join(example_path, 'model/6.jpg'), os.path.join(example_path, 'model/7.jpg'), ]) with gr.Column(): example = gr.Examples( label="Garment (upper-body)", inputs=garm_img, examples_per_page=7, examples=[ os.path.join(example_path, 'garment/12.png'), os.path.join(example_path, 'garment/0012.jpg'), os.path.join(example_path, 'garment/0047.jpg'), os.path.join(example_path, 'garment/0049.jpg'), ]) example = gr.Examples( label="Garment (lower-body)", inputs=garm_img, examples_per_page=7, examples=[ os.path.join(example_path, 'garment/0317.jpg'), os.path.join(example_path, 'garment/0327.jpg'), os.path.join(example_path, 'garment/0329.jpg'), os.path.join(example_path, 'garment/0362.jpg'), ]) example = gr.Examples( label="Garment (dresses)", inputs=garm_img, examples_per_page=7, examples=[ os.path.join(example_path, 'garment/8.jpg'), os.path.join(example_path, 'garment/9.png'), os.path.join(example_path, 'garment/10.jpg'), os.path.join(example_path, 'garment/11.jpg'), ]) with gr.Column(): category = gr.Dropdown(label="Garment category", choices=["Upper-body", "Lower-body", "Dresses"], value="Upper-body") resolution = gr.Dropdown(label="Try-on resolution", choices=["768x1024", "1152x1536", "1536x2048"], value="1152x1536") with gr.Column(): run_mask_button = gr.Button(value="Step1: Run Mask") run_button = gr.Button(value="Step2: Run Try-on")
ips1 = [vton_img, category, offset_top, offset_bottom, offset_left, offset_right] ips2 = [vton_img, garm_img, masked_vton_img, pose_image, n_steps, image_scale, seed, num_images_per_prompt, resolution] run_mask_button.click(fn=generator.generate_mask, inputs=ips1, outputs=[masked_vton_img, pose_image]) run_button.click(fn=generator.process, inputs=ips2, outputs=[result_gallery]) return demo
if __name__ == "__main__": import argparse parser = argparse.ArgumentParser(description="FitDiT") parser.add_argument("--model_path", type=str, required=True, help="The path of FitDiT model.") parser.add_argument("--device", type=str, default="cuda:0", help="Device to use") parser.add_argument("--fp16", action="store_true", help="Load model with fp16, default is bf16") parser.add_argument("--offload", action="store_true", help="Offload model to CPU when not in use.") parser.add_argument("--aggressive_offload", action="store_true", help="Offload model more aggressively to CPU when not in use.") args = parser.parse_args() demo = create_demo(args.model_path, args.device, args.offload, args.aggressive_offload, args.fp16) demo.launch(share=True)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768# Openpose# Original from CMU https://github.com/CMU-Perceptual-Computing-Lab/openpose# 2nd Edited by https://github.com/Hzzone/pytorch-openpose# 3rd Edited by ControlNet# 4th Edited by ControlNet (added face and correct hands)
import osos.environ["KMP_DUPLICATE_LIB_OK"]="TRUE"
import torchimport numpy as npfrom . import utilfrom .wholebody import Wholebody
def draw_pose(pose, H, W): bodies = pose['bodies'] faces = pose['faces'] hands = pose['hands'] candidate = bodies['candidate'] subset = bodies['subset'] canvas = np.zeros(shape=(H, W, 3), dtype=np.uint8)
canvas = util.draw_bodypose(canvas, candidate, subset)
canvas = util.draw_handpose(canvas, hands)
canvas = util.draw_facepose(canvas, faces)
return canvas
class DWposeDetector: def __init__(self, model_root, device):
self.pose_estimation = Wholebody(model_root, device)
def __call__(self, oriImg): oriImg = oriImg.copy() H, W, C = oriImg.shape with torch.no_grad(): candidate, subset = self.pose_estimation(oriImg) nums, keys, locs = candidate.shape candidate[..., 0] /= float(W) candidate[..., 1] /= float(H) body = candidate[:,:18].copy() body = body.reshape(nums*18, locs) ori_score = subset[:,:18].copy() score = subset[:,:18].copy() for i in range(len(score)): for j in range(len(score[i])): if score[i][j] > 0.3: score[i][j] = int(18*i+j) else: score[i][j] = -1
un_visible = subset<0.3 candidate[un_visible] = -1
foot = candidate[:,18:24]
faces = candidate[:,24:92]
hands = candidate[:,92:113] hands = np.vstack([hands, candidate[:,113:]]) bodies = dict(candidate=body, subset=score) pose = dict(bodies=bodies, hands=hands, faces=faces) return draw_pose(pose, H, W), body, ori_score, candidate123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125import cv2import numpy as np
import onnxruntime
def nms(boxes, scores, nms_thr): """Single class NMS implemented in Numpy.""" x1 = boxes[:, 0] y1 = boxes[:, 1] x2 = boxes[:, 2] y2 = boxes[:, 3]
areas = (x2 - x1 + 1) * (y2 - y1 + 1) order = scores.argsort()[::-1]
keep = [] while order.size > 0: i = order[0] keep.append(i) xx1 = np.maximum(x1[i], x1[order[1:]]) yy1 = np.maximum(y1[i], y1[order[1:]]) xx2 = np.minimum(x2[i], x2[order[1:]]) yy2 = np.minimum(y2[i], y2[order[1:]])
w = np.maximum(0.0, xx2 - xx1 + 1) h = np.maximum(0.0, yy2 - yy1 + 1) inter = w * h ovr = inter / (areas[i] + areas[order[1:]] - inter)
inds = np.where(ovr <= nms_thr)[0] order = order[inds + 1]
return keep
def multiclass_nms(boxes, scores, nms_thr, score_thr): """Multiclass NMS implemented in Numpy. Class-aware version.""" final_dets = [] num_classes = scores.shape[1] for cls_ind in range(num_classes): cls_scores = scores[:, cls_ind] valid_score_mask = cls_scores > score_thr if valid_score_mask.sum() == 0: continue else: valid_scores = cls_scores[valid_score_mask] valid_boxes = boxes[valid_score_mask] keep = nms(valid_boxes, valid_scores, nms_thr) if len(keep) > 0: cls_inds = np.ones((len(keep), 1)) * cls_ind dets = np.concatenate( [valid_boxes[keep], valid_scores[keep, None], cls_inds], 1 ) final_dets.append(dets) if len(final_dets) == 0: return None return np.concatenate(final_dets, 0)
def demo_postprocess(outputs, img_size, p6=False): grids = [] expanded_strides = [] strides = [8, 16, 32] if not p6 else [8, 16, 32, 64]
hsizes = [img_size[0] // stride for stride in strides] wsizes = [img_size[1] // stride for stride in strides]
for hsize, wsize, stride in zip(hsizes, wsizes, strides): xv, yv = np.meshgrid(np.arange(wsize), np.arange(hsize)) grid = np.stack((xv, yv), 2).reshape(1, -1, 2) grids.append(grid) shape = grid.shape[:2] expanded_strides.append(np.full((*shape, 1), stride))
grids = np.concatenate(grids, 1) expanded_strides = np.concatenate(expanded_strides, 1) outputs[..., :2] = (outputs[..., :2] + grids) * expanded_strides outputs[..., 2:4] = np.exp(outputs[..., 2:4]) * expanded_strides
return outputs
def preprocess(img, input_size, swap=(2, 0, 1)): if len(img.shape) == 3: padded_img = np.ones((input_size[0], input_size[1], 3), dtype=np.uint8) * 114 else: padded_img = np.ones(input_size, dtype=np.uint8) * 114
r = min(input_size[0] / img.shape[0], input_size[1] / img.shape[1]) resized_img = cv2.resize( img, (int(img.shape[1] * r), int(img.shape[0] * r)), interpolation=cv2.INTER_LINEAR, ).astype(np.uint8) padded_img[: int(img.shape[0] * r), : int(img.shape[1] * r)] = resized_img
padded_img = padded_img.transpose(swap) padded_img = np.ascontiguousarray(padded_img, dtype=np.float32) return padded_img, r
def inference_detector(session, oriImg): input_shape = (640,640) img, ratio = preprocess(oriImg, input_shape)
ort_inputs = {session.get_inputs()[0].name: img[None, :, :, :]} output = session.run(None, ort_inputs) predictions = demo_postprocess(output[0], input_shape)[0]
boxes = predictions[:, :4] scores = predictions[:, 4:5] * predictions[:, 5:]
boxes_xyxy = np.ones_like(boxes) boxes_xyxy[:, 0] = boxes[:, 0] - boxes[:, 2]/2. boxes_xyxy[:, 1] = boxes[:, 1] - boxes[:, 3]/2. boxes_xyxy[:, 2] = boxes[:, 0] + boxes[:, 2]/2. boxes_xyxy[:, 3] = boxes[:, 1] + boxes[:, 3]/2. boxes_xyxy /= ratio dets = multiclass_nms(boxes_xyxy, scores, nms_thr=0.45, score_thr=0.1) if dets is not None: final_boxes, final_scores, final_cls_inds = dets[:, :4], dets[:, 4], dets[:, 5] isscore = final_scores>0.3 iscat = final_cls_inds == 0 isbbox = [ i and j for (i, j) in zip(isscore, iscat)] final_boxes = final_boxes[isbbox] else: final_boxes = np.array([])
return final_boxes123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360from typing import List, Tuple
import cv2import numpy as npimport onnxruntime as ort
def preprocess( img: np.ndarray, out_bbox, input_size: Tuple[int, int] = (192, 256)) -> Tuple[np.ndarray, np.ndarray, np.ndarray]: """Do preprocessing for RTMPose model inference.
Args: img (np.ndarray): Input image in shape. input_size (tuple): Input image size in shape (w, h).
Returns: tuple: - resized_img (np.ndarray): Preprocessed image. - center (np.ndarray): Center of image. - scale (np.ndarray): Scale of image. """ # get shape of image img_shape = img.shape[:2] out_img, out_center, out_scale = [], [], [] if len(out_bbox) == 0: out_bbox = [[0, 0, img_shape[1], img_shape[0]]] for i in range(len(out_bbox)): x0 = out_bbox[i][0] y0 = out_bbox[i][1] x1 = out_bbox[i][2] y1 = out_bbox[i][3] bbox = np.array([x0, y0, x1, y1])
# get center and scale center, scale = bbox_xyxy2cs(bbox, padding=1.25)
# do affine transformation resized_img, scale = top_down_affine(input_size, scale, center, img)
# normalize image mean = np.array([123.675, 116.28, 103.53]) std = np.array([58.395, 57.12, 57.375]) resized_img = (resized_img - mean) / std
out_img.append(resized_img) out_center.append(center) out_scale.append(scale)
return out_img, out_center, out_scale
def inference(sess: ort.InferenceSession, img: np.ndarray) -> np.ndarray: """Inference RTMPose model.
Args: sess (ort.InferenceSession): ONNXRuntime session. img (np.ndarray): Input image in shape.
Returns: outputs (np.ndarray): Output of RTMPose model. """ all_out = [] # build input for i in range(len(img)): input = [img[i].transpose(2, 0, 1)]
# build output sess_input = {sess.get_inputs()[0].name: input} sess_output = [] for out in sess.get_outputs(): sess_output.append(out.name)
# run model outputs = sess.run(sess_output, sess_input) all_out.append(outputs)
return all_out
def postprocess(outputs: List[np.ndarray], model_input_size: Tuple[int, int], center: Tuple[int, int], scale: Tuple[int, int], simcc_split_ratio: float = 2.0 ) -> Tuple[np.ndarray, np.ndarray]: """Postprocess for RTMPose model output.
Args: outputs (np.ndarray): Output of RTMPose model. model_input_size (tuple): RTMPose model Input image size. center (tuple): Center of bbox in shape (x, y). scale (tuple): Scale of bbox in shape (w, h). simcc_split_ratio (float): Split ratio of simcc.
Returns: tuple: - keypoints (np.ndarray): Rescaled keypoints. - scores (np.ndarray): Model predict scores. """ all_key = [] all_score = [] for i in range(len(outputs)): # use simcc to decode simcc_x, simcc_y = outputs[i] keypoints, scores = decode(simcc_x, simcc_y, simcc_split_ratio)
# rescale keypoints keypoints = keypoints / model_input_size * scale[i] + center[i] - scale[i] / 2 all_key.append(keypoints[0]) all_score.append(scores[0])
return np.array(all_key), np.array(all_score)
def bbox_xyxy2cs(bbox: np.ndarray, padding: float = 1.) -> Tuple[np.ndarray, np.ndarray]: """Transform the bbox format from (x,y,w,h) into (center, scale)
Args: bbox (ndarray): Bounding box(es) in shape (4,) or (n, 4), formatted as (left, top, right, bottom) padding (float): BBox padding factor that will be multilied to scale. Default: 1.0
Returns: tuple: A tuple containing center and scale. - np.ndarray[float32]: Center (x, y) of the bbox in shape (2,) or (n, 2) - np.ndarray[float32]: Scale (w, h) of the bbox in shape (2,) or (n, 2) """ # convert single bbox from (4, ) to (1, 4) dim = bbox.ndim if dim == 1: bbox = bbox[None, :]
# get bbox center and scale x1, y1, x2, y2 = np.hsplit(bbox, [1, 2, 3]) center = np.hstack([x1 + x2, y1 + y2]) * 0.5 scale = np.hstack([x2 - x1, y2 - y1]) * padding
if dim == 1: center = center[0] scale = scale[0]
return center, scale
def _fix_aspect_ratio(bbox_scale: np.ndarray, aspect_ratio: float) -> np.ndarray: """Extend the scale to match the given aspect ratio.
Args: scale (np.ndarray): The image scale (w, h) in shape (2, ) aspect_ratio (float): The ratio of ``w/h``
Returns: np.ndarray: The reshaped image scale in (2, ) """ w, h = np.hsplit(bbox_scale, [1]) bbox_scale = np.where(w > h * aspect_ratio, np.hstack([w, w / aspect_ratio]), np.hstack([h * aspect_ratio, h])) return bbox_scale
def _rotate_point(pt: np.ndarray, angle_rad: float) -> np.ndarray: """Rotate a point by an angle.
Args: pt (np.ndarray): 2D point coordinates (x, y) in shape (2, ) angle_rad (float): rotation angle in radian
Returns: np.ndarray: Rotated point in shape (2, ) """ sn, cs = np.sin(angle_rad), np.cos(angle_rad) rot_mat = np.array([[cs, -sn], [sn, cs]]) return rot_mat @ pt
def _get_3rd_point(a: np.ndarray, b: np.ndarray) -> np.ndarray: """To calculate the affine matrix, three pairs of points are required. This function is used to get the 3rd point, given 2D points a & b.
The 3rd point is defined by rotating vector `a - b` by 90 degrees anticlockwise, using b as the rotation center.
Args: a (np.ndarray): The 1st point (x,y) in shape (2, ) b (np.ndarray): The 2nd point (x,y) in shape (2, )
Returns: np.ndarray: The 3rd point. """ direction = a - b c = b + np.r_[-direction[1], direction[0]] return c
def get_warp_matrix(center: np.ndarray, scale: np.ndarray, rot: float, output_size: Tuple[int, int], shift: Tuple[float, float] = (0., 0.), inv: bool = False) -> np.ndarray: """Calculate the affine transformation matrix that can warp the bbox area in the input image to the output size.
Args: center (np.ndarray[2, ]): Center of the bounding box (x, y). scale (np.ndarray[2, ]): Scale of the bounding box wrt [width, height]. rot (float): Rotation angle (degree). output_size (np.ndarray[2, ] | list(2,)): Size of the destination heatmaps. shift (0-100%): Shift translation ratio wrt the width/height. Default (0., 0.). inv (bool): Option to inverse the affine transform direction. (inv=False: src->dst or inv=True: dst->src)
Returns: np.ndarray: A 2x3 transformation matrix """ shift = np.array(shift) src_w = scale[0] dst_w = output_size[0] dst_h = output_size[1]
# compute transformation matrix rot_rad = np.deg2rad(rot) src_dir = _rotate_point(np.array([0., src_w * -0.5]), rot_rad) dst_dir = np.array([0., dst_w * -0.5])
# get four corners of the src rectangle in the original image src = np.zeros((3, 2), dtype=np.float32) src[0, :] = center + scale * shift src[1, :] = center + src_dir + scale * shift src[2, :] = _get_3rd_point(src[0, :], src[1, :])
# get four corners of the dst rectangle in the input image dst = np.zeros((3, 2), dtype=np.float32) dst[0, :] = [dst_w * 0.5, dst_h * 0.5] dst[1, :] = np.array([dst_w * 0.5, dst_h * 0.5]) + dst_dir dst[2, :] = _get_3rd_point(dst[0, :], dst[1, :])
if inv: warp_mat = cv2.getAffineTransform(np.float32(dst), np.float32(src)) else: warp_mat = cv2.getAffineTransform(np.float32(src), np.float32(dst))
return warp_mat
def top_down_affine(input_size: dict, bbox_scale: dict, bbox_center: dict, img: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Get the bbox image as the model input by affine transform.
Args: input_size (dict): The input size of the model. bbox_scale (dict): The bbox scale of the img. bbox_center (dict): The bbox center of the img. img (np.ndarray): The original image.
Returns: tuple: A tuple containing center and scale. - np.ndarray[float32]: img after affine transform. - np.ndarray[float32]: bbox scale after affine transform. """ w, h = input_size warp_size = (int(w), int(h))
# reshape bbox to fixed aspect ratio bbox_scale = _fix_aspect_ratio(bbox_scale, aspect_ratio=w / h)
# get the affine matrix center = bbox_center scale = bbox_scale rot = 0 warp_mat = get_warp_matrix(center, scale, rot, output_size=(w, h))
# do affine transform img = cv2.warpAffine(img, warp_mat, warp_size, flags=cv2.INTER_LINEAR)
return img, bbox_scale
def get_simcc_maximum(simcc_x: np.ndarray, simcc_y: np.ndarray) -> Tuple[np.ndarray, np.ndarray]: """Get maximum response location and value from simcc representations.
Note: instance number: N num_keypoints: K heatmap height: H heatmap width: W
Args: simcc_x (np.ndarray): x-axis SimCC in shape (K, Wx) or (N, K, Wx) simcc_y (np.ndarray): y-axis SimCC in shape (K, Wy) or (N, K, Wy)
Returns: tuple: - locs (np.ndarray): locations of maximum heatmap responses in shape (K, 2) or (N, K, 2) - vals (np.ndarray): values of maximum heatmap responses in shape (K,) or (N, K) """ N, K, Wx = simcc_x.shape simcc_x = simcc_x.reshape(N * K, -1) simcc_y = simcc_y.reshape(N * K, -1)
# get maximum value locations x_locs = np.argmax(simcc_x, axis=1) y_locs = np.argmax(simcc_y, axis=1) locs = np.stack((x_locs, y_locs), axis=-1).astype(np.float32) max_val_x = np.amax(simcc_x, axis=1) max_val_y = np.amax(simcc_y, axis=1)
# get maximum value across x and y axis mask = max_val_x > max_val_y max_val_x[mask] = max_val_y[mask] vals = max_val_x locs[vals <= 0.] = -1
# reshape locs = locs.reshape(N, K, 2) vals = vals.reshape(N, K)
return locs, vals
def decode(simcc_x: np.ndarray, simcc_y: np.ndarray, simcc_split_ratio) -> Tuple[np.ndarray, np.ndarray]: """Modulate simcc distribution with Gaussian.
Args: simcc_x (np.ndarray[K, Wx]): model predicted simcc in x. simcc_y (np.ndarray[K, Wy]): model predicted simcc in y. simcc_split_ratio (int): The split ratio of simcc.
Returns: tuple: A tuple containing center and scale. - np.ndarray[float32]: keypoints in shape (K, 2) or (n, K, 2) - np.ndarray[float32]: scores in shape (K,) or (n, K) """ keypoints, scores = get_simcc_maximum(simcc_x, simcc_y) keypoints /= simcc_split_ratio
return keypoints, scores
def inference_pose(session, out_bbox, oriImg): h, w = session.get_inputs()[0].shape[2:] model_input_size = (w, h) resized_img, center, scale = preprocess(oriImg, out_bbox, model_input_size) outputs = inference(session, resized_img) keypoints, scores = postprocess(outputs, model_input_size, center, scale)
return keypoints, scores123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297import mathimport numpy as npimport matplotlibimport cv2
eps = 0.01
def smart_resize(x, s): Ht, Wt = s if x.ndim == 2: Ho, Wo = x.shape Co = 1 else: Ho, Wo, Co = x.shape if Co == 3 or Co == 1: k = float(Ht + Wt) / float(Ho + Wo) return cv2.resize(x, (int(Wt), int(Ht)), interpolation=cv2.INTER_AREA if k < 1 else cv2.INTER_LANCZOS4) else: return np.stack([smart_resize(x[:, :, i], s) for i in range(Co)], axis=2)
def smart_resize_k(x, fx, fy): if x.ndim == 2: Ho, Wo = x.shape Co = 1 else: Ho, Wo, Co = x.shape Ht, Wt = Ho * fy, Wo * fx if Co == 3 or Co == 1: k = float(Ht + Wt) / float(Ho + Wo) return cv2.resize(x, (int(Wt), int(Ht)), interpolation=cv2.INTER_AREA if k < 1 else cv2.INTER_LANCZOS4) else: return np.stack([smart_resize_k(x[:, :, i], fx, fy) for i in range(Co)], axis=2)
def padRightDownCorner(img, stride, padValue): h = img.shape[0] w = img.shape[1]
pad = 4 * [None] pad[0] = 0 # up pad[1] = 0 # left pad[2] = 0 if (h % stride == 0) else stride - (h % stride) # down pad[3] = 0 if (w % stride == 0) else stride - (w % stride) # right
img_padded = img pad_up = np.tile(img_padded[0:1, :, :]*0 + padValue, (pad[0], 1, 1)) img_padded = np.concatenate((pad_up, img_padded), axis=0) pad_left = np.tile(img_padded[:, 0:1, :]*0 + padValue, (1, pad[1], 1)) img_padded = np.concatenate((pad_left, img_padded), axis=1) pad_down = np.tile(img_padded[-2:-1, :, :]*0 + padValue, (pad[2], 1, 1)) img_padded = np.concatenate((img_padded, pad_down), axis=0) pad_right = np.tile(img_padded[:, -2:-1, :]*0 + padValue, (1, pad[3], 1)) img_padded = np.concatenate((img_padded, pad_right), axis=1)
return img_padded, pad
def transfer(model, model_weights): transfered_model_weights = {} for weights_name in model.state_dict().keys(): transfered_model_weights[weights_name] = model_weights['.'.join(weights_name.split('.')[1:])] return transfered_model_weights
def draw_bodypose(canvas, candidate, subset): H, W, C = canvas.shape candidate = np.array(candidate) subset = np.array(subset)
stickwidth = 4
limbSeq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], [9, 10], \ [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], [1, 15], [15, 17], \ [1, 16], [16, 18], [3, 17], [6, 18]]
colors = [[255, 0, 0], [255, 85, 0], [255, 170, 0], [255, 255, 0], [170, 255, 0], [85, 255, 0], [0, 255, 0], \ [0, 255, 85], [0, 255, 170], [0, 255, 255], [0, 170, 255], [0, 85, 255], [0, 0, 255], [85, 0, 255], \ [170, 0, 255], [255, 0, 255], [255, 0, 170], [255, 0, 85]]
for i in range(17): for n in range(len(subset)): index = subset[n][np.array(limbSeq[i]) - 1] if -1 in index: continue Y = candidate[index.astype(int), 0] * float(W) X = candidate[index.astype(int), 1] * float(H) mX = np.mean(X) mY = np.mean(Y) length = ((X[0] - X[1]) ** 2 + (Y[0] - Y[1]) ** 2) ** 0.5 angle = math.degrees(math.atan2(X[0] - X[1], Y[0] - Y[1])) polygon = cv2.ellipse2Poly((int(mY), int(mX)), (int(length / 2), stickwidth), int(angle), 0, 360, 1) cv2.fillConvexPoly(canvas, polygon, colors[i])
canvas = (canvas * 0.6).astype(np.uint8)
for i in range(18): for n in range(len(subset)): index = int(subset[n][i]) if index == -1: continue x, y = candidate[index][0:2] x = int(x * W) y = int(y * H) cv2.circle(canvas, (int(x), int(y)), 4, colors[i], thickness=-1)
return canvas
def draw_handpose(canvas, all_hand_peaks): H, W, C = canvas.shape
edges = [[0, 1], [1, 2], [2, 3], [3, 4], [0, 5], [5, 6], [6, 7], [7, 8], [0, 9], [9, 10], \ [10, 11], [11, 12], [0, 13], [13, 14], [14, 15], [15, 16], [0, 17], [17, 18], [18, 19], [19, 20]]
for peaks in all_hand_peaks: peaks = np.array(peaks)
for ie, e in enumerate(edges): x1, y1 = peaks[e[0]] x2, y2 = peaks[e[1]] x1 = int(x1 * W) y1 = int(y1 * H) x2 = int(x2 * W) y2 = int(y2 * H) if x1 > eps and y1 > eps and x2 > eps and y2 > eps: cv2.line(canvas, (x1, y1), (x2, y2), matplotlib.colors.hsv_to_rgb([ie / float(len(edges)), 1.0, 1.0]) * 255, thickness=2)
for i, keyponit in enumerate(peaks): x, y = keyponit x = int(x * W) y = int(y * H) if x > eps and y > eps: cv2.circle(canvas, (x, y), 4, (0, 0, 255), thickness=-1) return canvas
def draw_facepose(canvas, all_lmks): H, W, C = canvas.shape for lmks in all_lmks: lmks = np.array(lmks) for lmk in lmks: x, y = lmk x = int(x * W) y = int(y * H) if x > eps and y > eps: cv2.circle(canvas, (x, y), 3, (255, 255, 255), thickness=-1) return canvas
# detect hand according to body pose keypoints# please refer to https://github.com/CMU-Perceptual-Computing-Lab/openpose/blob/master/src/openpose/hand/handDetector.cppdef handDetect(candidate, subset, oriImg): # right hand: wrist 4, elbow 3, shoulder 2 # left hand: wrist 7, elbow 6, shoulder 5 ratioWristElbow = 0.33 detect_result = [] image_height, image_width = oriImg.shape[0:2] for person in subset.astype(int): # if any of three not detected has_left = np.sum(person[[5, 6, 7]] == -1) == 0 has_right = np.sum(person[[2, 3, 4]] == -1) == 0 if not (has_left or has_right): continue hands = [] #left hand if has_left: left_shoulder_index, left_elbow_index, left_wrist_index = person[[5, 6, 7]] x1, y1 = candidate[left_shoulder_index][:2] x2, y2 = candidate[left_elbow_index][:2] x3, y3 = candidate[left_wrist_index][:2] hands.append([x1, y1, x2, y2, x3, y3, True]) # right hand if has_right: right_shoulder_index, right_elbow_index, right_wrist_index = person[[2, 3, 4]] x1, y1 = candidate[right_shoulder_index][:2] x2, y2 = candidate[right_elbow_index][:2] x3, y3 = candidate[right_wrist_index][:2] hands.append([x1, y1, x2, y2, x3, y3, False])
for x1, y1, x2, y2, x3, y3, is_left in hands: # pos_hand = pos_wrist + ratio * (pos_wrist - pos_elbox) = (1 + ratio) * pos_wrist - ratio * pos_elbox # handRectangle.x = posePtr[wrist*3] + ratioWristElbow * (posePtr[wrist*3] - posePtr[elbow*3]); # handRectangle.y = posePtr[wrist*3+1] + ratioWristElbow * (posePtr[wrist*3+1] - posePtr[elbow*3+1]); # const auto distanceWristElbow = getDistance(poseKeypoints, person, wrist, elbow); # const auto distanceElbowShoulder = getDistance(poseKeypoints, person, elbow, shoulder); # handRectangle.width = 1.5f * fastMax(distanceWristElbow, 0.9f * distanceElbowShoulder); x = x3 + ratioWristElbow * (x3 - x2) y = y3 + ratioWristElbow * (y3 - y2) distanceWristElbow = math.sqrt((x3 - x2) ** 2 + (y3 - y2) ** 2) distanceElbowShoulder = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2) width = 1.5 * max(distanceWristElbow, 0.9 * distanceElbowShoulder) # x-y refers to the center --> offset to topLeft point # handRectangle.x -= handRectangle.width / 2.f; # handRectangle.y -= handRectangle.height / 2.f; x -= width / 2 y -= width / 2 # width = height # overflow the image if x < 0: x = 0 if y < 0: y = 0 width1 = width width2 = width if x + width > image_width: width1 = image_width - x if y + width > image_height: width2 = image_height - y width = min(width1, width2) # the max hand box value is 20 pixels if width >= 20: detect_result.append([int(x), int(y), int(width), is_left])
''' return value: [[x, y, w, True if left hand else False]]. width=height since the network require squared input. x, y is the coordinate of top left ''' return detect_result
# Written by Lvmindef faceDetect(candidate, subset, oriImg): # left right eye ear 14 15 16 17 detect_result = [] image_height, image_width = oriImg.shape[0:2] for person in subset.astype(int): has_head = person[0] > -1 if not has_head: continue
has_left_eye = person[14] > -1 has_right_eye = person[15] > -1 has_left_ear = person[16] > -1 has_right_ear = person[17] > -1
if not (has_left_eye or has_right_eye or has_left_ear or has_right_ear): continue
head, left_eye, right_eye, left_ear, right_ear = person[[0, 14, 15, 16, 17]]
width = 0.0 x0, y0 = candidate[head][:2]
if has_left_eye: x1, y1 = candidate[left_eye][:2] d = max(abs(x0 - x1), abs(y0 - y1)) width = max(width, d * 3.0)
if has_right_eye: x1, y1 = candidate[right_eye][:2] d = max(abs(x0 - x1), abs(y0 - y1)) width = max(width, d * 3.0)
if has_left_ear: x1, y1 = candidate[left_ear][:2] d = max(abs(x0 - x1), abs(y0 - y1)) width = max(width, d * 1.5)
if has_right_ear: x1, y1 = candidate[right_ear][:2] d = max(abs(x0 - x1), abs(y0 - y1)) width = max(width, d * 1.5)
x, y = x0, y0
x -= width y -= width
if x < 0: x = 0
if y < 0: y = 0
width1 = width * 2 width2 = width * 2
if x + width > image_width: width1 = image_width - x
if y + width > image_height: width2 = image_height - y
width = min(width1, width2)
if width >= 20: detect_result.append([int(x), int(y), int(width)])
return detect_result
# get max index of 2d arraydef npmax(array): arrayindex = array.argmax(1) arrayvalue = array.max(1) i = arrayvalue.argmax() j = arrayindex[i] return i, j12345678910111213141516171819202122232425262728293031323334353637383940414243444546import cv2import numpy as npimport os
import onnxruntime as ortfrom .onnxdet import inference_detectorfrom .onnxpose import inference_pose
class Wholebody: def __init__(self, model_root, device): providers = ['CPUExecutionProvider' ] if device == 'cpu' else ['CUDAExecutionProvider'] onnx_det = os.path.join(model_root, 'dwpose/yolox_l.onnx') onnx_pose = os.path.join(model_root, 'dwpose/dw-ll_ucoco_384.onnx')
self.session_det = ort.InferenceSession(path_or_bytes=onnx_det, providers=providers) self.session_pose = ort.InferenceSession(path_or_bytes=onnx_pose, providers=providers) def __call__(self, oriImg): det_result = inference_detector(self.session_det, oriImg) keypoints, scores = inference_pose(self.session_pose, det_result, oriImg)
keypoints_info = np.concatenate( (keypoints, scores[..., None]), axis=-1) # compute neck joint neck = np.mean(keypoints_info[:, [5, 6]], axis=1) # neck score when visualizing pred neck[:, 2:4] = np.logical_and( keypoints_info[:, 5, 2:4] > 0.3, keypoints_info[:, 6, 2:4] > 0.3).astype(int) new_keypoints_info = np.insert( keypoints_info, 17, neck, axis=1) mmpose_idx = [ 17, 6, 8, 10, 7, 9, 12, 14, 16, 13, 15, 2, 1, 4, 3 ] openpose_idx = [ 1, 2, 3, 4, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17 ] new_keypoints_info[:, openpose_idx] = \ new_keypoints_info[:, mmpose_idx] keypoints_info = new_keypoints_info
keypoints, scores = keypoints_info[ ..., :2], keypoints_info[..., 2] return keypoints, scores123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201#!/usr/bin/env python# -*- encoding: utf-8 -*-
"""@Author : Peike Li@Contact : peike.li@yahoo.com@File : datasets.py@Time : 8/4/19 3:35 PM@Desc :@License : This source code is licensed under the license found in the LICENSE file in the root directory of this source tree."""
import osimport numpy as npimport randomimport torchimport cv2from torch.utils import datafrom utils.transforms import get_affine_transform
class LIPDataSet(data.Dataset): def __init__(self, root, dataset, crop_size=[473, 473], scale_factor=0.25, rotation_factor=30, ignore_label=255, transform=None): self.root = root self.aspect_ratio = crop_size[1] * 1.0 / crop_size[0] self.crop_size = np.asarray(crop_size) self.ignore_label = ignore_label self.scale_factor = scale_factor self.rotation_factor = rotation_factor self.flip_prob = 0.5 self.transform = transform self.dataset = dataset
list_path = os.path.join(self.root, self.dataset + '_id.txt') train_list = [i_id.strip() for i_id in open(list_path)]
self.train_list = train_list self.number_samples = len(self.train_list)
def __len__(self): return self.number_samples
def _box2cs(self, box): x, y, w, h = box[:4] return self._xywh2cs(x, y, w, h)
def _xywh2cs(self, x, y, w, h): center = np.zeros((2), dtype=np.float32) center[0] = x + w * 0.5 center[1] = y + h * 0.5 if w > self.aspect_ratio * h: h = w * 1.0 / self.aspect_ratio elif w < self.aspect_ratio * h: w = h * self.aspect_ratio scale = np.array([w * 1.0, h * 1.0], dtype=np.float32) return center, scale
def __getitem__(self, index): train_item = self.train_list[index]
im_path = os.path.join(self.root, self.dataset + '_images', train_item + '.jpg') parsing_anno_path = os.path.join(self.root, self.dataset + '_segmentations', train_item + '.png')
im = cv2.imread(im_path, cv2.IMREAD_COLOR) h, w, _ = im.shape parsing_anno = np.zeros((h, w), dtype=np.long)
# Get person center and scale person_center, s = self._box2cs([0, 0, w - 1, h - 1]) r = 0
if self.dataset != 'test': # Get pose annotation parsing_anno = cv2.imread(parsing_anno_path, cv2.IMREAD_GRAYSCALE) if self.dataset == 'train' or self.dataset == 'trainval': sf = self.scale_factor rf = self.rotation_factor s = s * np.clip(np.random.randn() * sf + 1, 1 - sf, 1 + sf) r = np.clip(np.random.randn() * rf, -rf * 2, rf * 2) if random.random() <= 0.6 else 0
if random.random() <= self.flip_prob: im = im[:, ::-1, :] parsing_anno = parsing_anno[:, ::-1] person_center[0] = im.shape[1] - person_center[0] - 1 right_idx = [15, 17, 19] left_idx = [14, 16, 18] for i in range(0, 3): right_pos = np.where(parsing_anno == right_idx[i]) left_pos = np.where(parsing_anno == left_idx[i]) parsing_anno[right_pos[0], right_pos[1]] = left_idx[i] parsing_anno[left_pos[0], left_pos[1]] = right_idx[i]
trans = get_affine_transform(person_center, s, r, self.crop_size) input = cv2.warpAffine( im, trans, (int(self.crop_size[1]), int(self.crop_size[0])), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0))
if self.transform: input = self.transform(input)
meta = { 'name': train_item, 'center': person_center, 'height': h, 'width': w, 'scale': s, 'rotation': r }
if self.dataset == 'val' or self.dataset == 'test': return input, meta else: label_parsing = cv2.warpAffine( parsing_anno, trans, (int(self.crop_size[1]), int(self.crop_size[0])), flags=cv2.INTER_NEAREST, borderMode=cv2.BORDER_CONSTANT, borderValue=(255))
label_parsing = torch.from_numpy(label_parsing)
return input, label_parsing, meta
class LIPDataValSet(data.Dataset): def __init__(self, root, dataset='val', crop_size=[473, 473], transform=None, flip=False): self.root = root self.crop_size = crop_size self.transform = transform self.flip = flip self.dataset = dataset self.root = root self.aspect_ratio = crop_size[1] * 1.0 / crop_size[0] self.crop_size = np.asarray(crop_size)
list_path = os.path.join(self.root, self.dataset + '_id.txt') val_list = [i_id.strip() for i_id in open(list_path)]
self.val_list = val_list self.number_samples = len(self.val_list)
def __len__(self): return len(self.val_list)
def _box2cs(self, box): x, y, w, h = box[:4] return self._xywh2cs(x, y, w, h)
def _xywh2cs(self, x, y, w, h): center = np.zeros((2), dtype=np.float32) center[0] = x + w * 0.5 center[1] = y + h * 0.5 if w > self.aspect_ratio * h: h = w * 1.0 / self.aspect_ratio elif w < self.aspect_ratio * h: w = h * self.aspect_ratio scale = np.array([w * 1.0, h * 1.0], dtype=np.float32)
return center, scale
def __getitem__(self, index): val_item = self.val_list[index] # Load training image im_path = os.path.join(self.root, self.dataset + '_images', val_item + '.jpg') im = cv2.imread(im_path, cv2.IMREAD_COLOR) h, w, _ = im.shape # Get person center and scale person_center, s = self._box2cs([0, 0, w - 1, h - 1]) r = 0 trans = get_affine_transform(person_center, s, r, self.crop_size) input = cv2.warpAffine( im, trans, (int(self.crop_size[1]), int(self.crop_size[0])), flags=cv2.INTER_LINEAR, borderMode=cv2.BORDER_CONSTANT, borderValue=(0, 0, 0)) input = self.transform(input) flip_input = input.flip(dims=[-1]) if self.flip: batch_input_im = torch.stack([input, flip_input]) else: batch_input_im = input
meta = { 'name': val_item, 'center': person_center, 'height': h, 'width': w, 'scale': s, 'rotation': r }
return batch_input_im, meta.gitattributes+26
.gitignoreAdded+162
LICENSEAdded+107
README.md+129-13
examples/garment/0.jpgAdded

examples/garment/0012.jpgAdded

Large File Pointer Details
- SHA256: d07b1ef57359b9cd3a91740ce8ec4067ba24fa08162e23a8b1a2b37b99d27e0b
- Pointer size: 131 Bytes
- Size of remote file: 210 kB
examples/garment/0023.jpgAdded

examples/garment/0047.jpgAdded

examples/garment/0049.jpgAdded

Large File Pointer Details
- SHA256: 07cbaf43dfca31e1b3fc74a6b1d7ba14f990c641621b6f4f662cfa73c03baeff
- Pointer size: 131 Bytes
- Size of remote file: 176 kB
examples/garment/0317.jpgAdded

Large File Pointer Details
- SHA256: 3c5e8962b07f05bc20efd57a21a3066d8669ac255e8ad0733a5e7ef40eab54b8
- Pointer size: 131 Bytes
- Size of remote file: 178 kB
examples/garment/0327.jpgAdded

Large File Pointer Details
- SHA256: 07c00f8ce0dc1453ea817fdc278b52588c9e5eeebe39f8f325dd434394341c0b
- Pointer size: 131 Bytes
- Size of remote file: 210 kB
examples/garment/0329.jpgAdded

Large File Pointer Details
- SHA256: 86efe3301ffb6029c3029a263c30285b86c78799d3af9070456f6a7b1a3d2d1b
- Pointer size: 131 Bytes
- Size of remote file: 300 kB
examples/garment/0362.jpgAdded

Large File Pointer Details
- SHA256: 642ca1fd558ad1c524a8b9c449f7d7bd42eb298c8d08fa1ee5e41aaddf38418d
- Pointer size: 131 Bytes
- Size of remote file: 177 kB
examples/garment/1.jpgAdded

Large File Pointer Details
- SHA256: c278aab7f43222916a965be0f199a9adaffc6d78a953f5f89c4cd81594130024
- Pointer size: 131 Bytes
- Size of remote file: 135 kB
examples/garment/10.jpgAdded

examples/garment/11.jpgAdded

examples/garment/12.pngAdded

Large File Pointer Details
- SHA256: cf7de6a7c6284316d56e3e2bd43e076b81f55ba7766c503788d47f3dea49271d
- Pointer size: 132 Bytes
- Size of remote file: 1.78 MB
examples/garment/2.jpgAdded

examples/garment/3.jpgAdded

examples/garment/4.jpgAdded

examples/garment/5.jpgAdded

examples/garment/6.jpegAdded

Large File Pointer Details
- SHA256: fa041f77fcbc1612307c6c88184cf73b914f5e2ee8812f48982da9bf38ba6d1c
- Pointer size: 131 Bytes
- Size of remote file: 154 kB
examples/garment/7.jpgAdded

Large File Pointer Details
- SHA256: e76180e30caa3e270f91660ba51d6d3a9729d192c18685dc8ca0c6fcd8272bb0
- Pointer size: 131 Bytes
- Size of remote file: 169 kB
examples/garment/8.jpgAdded

Large File Pointer Details
- SHA256: 03e7d5d003459b68b9ab8344e3ee2bd0a463108b3cd726e426736a8ffa9d1dbd
- Pointer size: 131 Bytes
- Size of remote file: 254 kB
examples/garment/9.pngAdded

Large File Pointer Details
- SHA256: c628636d68da98815c3015931ee1aaf395a5b679a3f9ae3b4df1fc3d9ab6cc9e
- Pointer size: 131 Bytes
- Size of remote file: 120 kB
examples/model/0.jpgAdded

Large File Pointer Details
- SHA256: f4a0bcac7f5b43656a9f541192a238e30d96c024cd1ea3bdb8d78764ec0ab8e4
- Pointer size: 131 Bytes
- Size of remote file: 136 kB
examples/model/0083.jpgAdded

Large File Pointer Details
- SHA256: 8418c2211fecaa0865a78deed5265c8a27f818ffd82ae7f7059cd91c9794fc60
- Pointer size: 131 Bytes
- Size of remote file: 290 kB
examples/model/0179.jpgAdded

Large File Pointer Details
- SHA256: 55ba05f16118f6d83e00713984b43151c33ac76494c25badfb957248bd495b7b
- Pointer size: 131 Bytes
- Size of remote file: 147 kB
examples/model/0220.jpgAdded

examples/model/0223.jpgAdded

examples/model/0274.jpgAdded

Large File Pointer Details
- SHA256: dedf3b371cbd33cf0e449ba19dcc3113186d2ed10d4f3641b5df04c80ed07da3
- Pointer size: 131 Bytes
- Size of remote file: 126 kB
examples/model/0279.jpgAdded

Large File Pointer Details
- SHA256: b3e03ad1eeae4e6412f467b39648a81361866eb58244d3a48b9b745eaa10d898
- Pointer size: 131 Bytes
- Size of remote file: 170 kB
examples/model/0303.jpgAdded

Large File Pointer Details
- SHA256: 7cf62e1d952164d60523ec732ac8047fb27b084bd5c8a99b644a588337e1d78e
- Pointer size: 131 Bytes
- Size of remote file: 166 kB
examples/model/0347.jpgAdded

Large File Pointer Details
- SHA256: 9e4c65cc36abc7616ba11a83da81a88e95190674719923f8fd18cbca662e8cf0
- Pointer size: 131 Bytes
- Size of remote file: 273 kB
examples/model/1.jpgAdded

examples/model/2.jpgAdded

examples/model/3.pngAdded

Large File Pointer Details
- SHA256: bf4f2064cc6efe6aa4b6bb503d6d2aadba4feff13b5784457ed7ddd63c1fc20f
- Pointer size: 131 Bytes
- Size of remote file: 589 kB
examples/model/4.jpgAdded

examples/model/5.jpgAdded

examples/model/6.jpgAdded

examples/model/7.jpgAdded

Large File Pointer Details
- SHA256: 50dc293a17a22d03a8329ddd3f653263d3308a7c9fa8b53e08c5ef675c53a1a0
- Pointer size: 131 Bytes
- Size of remote file: 141 kB
examples/model/8.pngAdded

Large File Pointer Details
- SHA256: 2556c2f046c16a3e03b2f029edfd1e1ce16841896cf33fa9f206f793f1ef9786
- Pointer size: 131 Bytes
- Size of remote file: 570 kB
gradio_sd3.pyAdded+315
preprocess/dwpose/__init__.pyAdded+68
preprocess/dwpose/onnxdet.pyAdded+125
preprocess/dwpose/onnxpose.pyAdded+360
preprocess/dwpose/util.pyAdded+297
preprocess/dwpose/wholebody.pyAdded+46
preprocess/humanparsing/datasets/__init__.pyAdded
preprocess/humanparsing/datasets/datasets.pyAdded+201