├── .github ├── FUNDING.yml └── workflows │ └── python-publish.yml ├── .gitignore ├── .pre-commit-config.yaml ├── .style.yapf ├── LICENSE ├── README.md ├── README_ch.md ├── docs ├── images │ ├── andy.png │ ├── multi.png │ ├── source.gif │ ├── swapped.gif │ └── trump.jpg └── test │ ├── condition.jpg │ ├── dst1.png │ ├── dst2.png │ ├── multi.png │ ├── taitan.jpeg │ ├── target_pose_reference.jpg │ └── trump.jpg ├── dofaker ├── __init__.py ├── face_core.py ├── face_det │ ├── __init__.py │ └── face_analysis.py ├── face_enhance │ ├── __init__.py │ └── gfpgan.py ├── face_swap │ ├── __init__.py │ ├── base_swapper.py │ └── inswapper.py ├── pose │ ├── __init__.py │ ├── pose_estimator.py │ ├── pose_transfer.py │ └── pose_utils.py ├── pose_core.py ├── super_resolution │ ├── __init__.py │ └── bsrgan.py ├── transforms │ ├── __init__.py │ └── functional.py └── utils │ ├── __init__.py │ ├── download.py │ ├── utils.py │ └── weights_urls.py ├── requirements.txt ├── run_faceswapper.py ├── run_posetransfer.py ├── setup.py ├── test.sh └── web_ui.py /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | # These are supported funding model platforms 2 | 3 | github: # Replace with up to 4 GitHub Sponsors-enabled usernames e.g., [user1, user2] 4 | patreon: # Replace with a single Patreon username 5 | open_collective: # Replace with a single Open Collective username 6 | ko_fi: # Replace with a single Ko-fi username 7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel 8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry 9 | liberapay: # Replace with a single Liberapay username 10 | issuehunt: # Replace with a single IssueHunt username 11 | otechie: # Replace with a single Otechie username 12 | lfx_crowdfunding: # Replace with a single LFX Crowdfunding project-name e.g., cloud-foundry 13 | custom: [] 14 | -------------------------------------------------------------------------------- /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package using Twine when a release is created 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries 3 | 4 | # This workflow uses actions that are not certified by GitHub. 5 | # They are provided by a third-party and are governed by 6 | # separate terms of service, privacy policy, and support 7 | # documentation. 8 | 9 | name: Upload Python Package 10 | 11 | on: 12 | release: 13 | types: [published] 14 | 15 | permissions: 16 | contents: read 17 | 18 | jobs: 19 | deploy: 20 | 21 | runs-on: ubuntu-latest 22 | 23 | steps: 24 | - uses: actions/checkout@v3 25 | - name: Set up Python 26 | uses: actions/setup-python@v3 27 | with: 28 | python-version: '3.x' 29 | - name: Install dependencies 30 | run: | 31 | python -m pip install --upgrade pip 32 | pip install build 33 | - name: Build package 34 | run: python -m build 35 | - name: Publish package 36 | uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 37 | with: 38 | user: __token__ 39 | password: ${{ secrets.PYPI_API_TOKEN }} 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | output/ 6 | weights/ 7 | 8 | # C extensions 9 | *.so 10 | 11 | # Distribution / packaging 12 | .Python 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | share/python-wheels/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | MANIFEST 30 | 31 | # PyInstaller 32 | # Usually these files are written by a python script from a template 33 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 34 | *.manifest 35 | *.spec 36 | 37 | # Installer logs 38 | pip-log.txt 39 | pip-delete-this-directory.txt 40 | 41 | # Unit test / coverage reports 42 | htmlcov/ 43 | .tox/ 44 | .nox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | *.py,cover 52 | .hypothesis/ 53 | .pytest_cache/ 54 | cover/ 55 | 56 | # Translations 57 | *.mo 58 | *.pot 59 | 60 | # Django stuff: 61 | *.log 62 | local_settings.py 63 | db.sqlite3 64 | db.sqlite3-journal 65 | 66 | # Flask stuff: 67 | instance/ 68 | .webassets-cache 69 | 70 | # Scrapy stuff: 71 | .scrapy 72 | 73 | # Sphinx documentation 74 | docs/_build/ 75 | 76 | # PyBuilder 77 | .pybuilder/ 78 | target/ 79 | 80 | # Jupyter Notebook 81 | .ipynb_checkpoints 82 | 83 | # IPython 84 | profile_default/ 85 | ipython_config.py 86 | 87 | # pyenv 88 | # For a library or package, you might want to ignore these files since the code is 89 | # intended to run in multiple environments; otherwise, check them in: 90 | # .python-version 91 | 92 | # pipenv 93 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 94 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 95 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 96 | # install all needed dependencies. 97 | #Pipfile.lock 98 | 99 | # poetry 100 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 101 | # This is especially recommended for binary packages to ensure reproducibility, and is more 102 | # commonly ignored for libraries. 103 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 104 | #poetry.lock 105 | 106 | # pdm 107 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 108 | #pdm.lock 109 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 110 | # in version control. 111 | # https://pdm.fming.dev/#use-with-ide 112 | .pdm.toml 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: local 3 | hooks: 4 | - id: yapf 5 | name: yapf 6 | entry: yapf --style .style.yapf -i 7 | language: system 8 | files: \.py$ 9 | 10 | - repo: https://github.com/pre-commit/pre-commit-hooks 11 | rev: a11d9314b22d8f8c7556443875b731ef05965464 12 | hooks: 13 | - id: check-merge-conflict 14 | - id: check-symlinks 15 | - id: end-of-file-fixer 16 | - id: trailing-whitespace 17 | - id: detect-private-key 18 | - id: check-added-large-files 19 | 20 | - repo: local 21 | hooks: 22 | - id: flake8 23 | name: flake8 24 | entry: flake8 --count --select=E9,F63,F7,F82 --show-source --statistics 25 | language: system 26 | files: \.py$ 27 | 28 | - repo: local 29 | hooks: 30 | - id: clang-format-with-version-check 31 | name: clang-format 32 | description: Format files with ClangFormat 33 | entry: bash .clang_format.hook -style=Google -i 34 | language: system 35 | files: \.(c|cc|cxx|cpp|cu|h|hpp|hxx|cuh|proto)$ 36 | -------------------------------------------------------------------------------- /.style.yapf: -------------------------------------------------------------------------------- 1 | [style] 2 | based_on_style = pep8 3 | column_limit = 80 -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | English|[简体中文](README_ch.md) 2 | 3 | [![colab](https://img.shields.io/static/v1?label=colab&message=colab&color=yellow)](https://colab.research.google.com/drive/1i1hO-_yS6kZdrLden8Mo_hfeHFD-cBt0?usp=sharing) 4 | 5 | # DoFaker: A very simple face swapping tool 6 | Insightface based face swapping tool to replace faces in videos or images. Windows and linux support CPU and GPU. Onnxruntime inference without pytorch. 7 | 8 |

9 | 10 |

11 | 12 |

13 | 14 |

15 | 16 |

17 | 18 | 19 |

20 | 21 | # Update 22 | - 2023/9/16 update pose transfer model 23 | - 2023/9/14 update face enhance(GFPGAN) and image super resolution(BSRGAN) 24 | 25 | # Tutorial 26 | - [dofaker tutorial in youtube:face swap so easy](https://www.youtube.com/watch?v=qd1-JSpiZao) 27 | - [colab online](https://colab.research.google.com/drive/1i1hO-_yS6kZdrLden8Mo_hfeHFD-cBt0?usp=sharing) 28 | 29 | 30 | # Qiuck Start 31 | install dofaker 32 | ```bash 33 | git clone https://github.com/justld/dofaker.git 34 | cd dofaker 35 | conda create -n dofaker 36 | conda activate dofaker 37 | pip install onnxruntime # onnxruntime-gpu 38 | pip install -e . 39 | ``` 40 | 41 | open web ui(The model weights will be downloaded automatically): 42 | ```bash 43 | dofaker 44 | ``` 45 | 46 | command line(linux): 47 | ``` 48 | bash test.sh 49 | ``` 50 | 51 | 52 | # Install from source code 53 | ## 一、Installation 54 | You should install onnxruntime or onnxruntime-gpu manually. 55 | 56 | ### conda install 57 | create virtual environment: 58 | ```bash 59 | git clone https://github.com/justld/dofaker.git 60 | cd dofaker 61 | conda create -n dofaker 62 | conda activate dofaker 63 | pip install -r requirements.txt 64 | pip install onnxruntime # onnxruntime-gpu 65 | pip install -e . 66 | ``` 67 | 68 | ### pip install 69 | ```bash 70 | git clone https://github.com/justld/dofaker.git 71 | cd dofaker 72 | pip install -r requirements.txt 73 | pip install onnxruntime # onnxruntime-gpu 74 | pip install -e . 75 | ``` 76 | 77 | ## 二、Download Weight 78 | All weights can be downloaded from [release](https://github.com/justld/dofaker/releases). These weight come from links refer to the botton links. 79 | 80 | Unzip the zip file, the dir looks like follow: 81 | ``` 82 | |-dofaker 83 | |-docs 84 | |-weights 85 | ----|-models 86 | --------|-buffalo_l 87 | ----------|-1k3d68.onnx 88 | ----------|-2d106det.onnx 89 | ----------|-... 90 | --------|-buffalo_l.zip 91 | --------|-inswapper_128.onnx 92 | --------|-GFPGANv1.3.onnx 93 | --------|-bsrgan_4.onnx 94 | |-run_faceswapper.py 95 | |-web_ui.py 96 | ``` 97 | 98 | 99 | ## 三、Usage 100 | You can use dofaker in web_ui or command line. 101 | ### web ui 102 | web gui only support one face swap once, if you want to swap multiple faces, please refer to command usage. 103 | ```bash 104 | python web_ui.py 105 | ``` 106 | 107 | ### command 108 | You can swap multiple faces in command. 109 | ```bash 110 | python run_faceswapper.py --source "image or video path to be swapped" --dst_face_paths "dst_face1_path" "dst_face2_path" ... --src_face_paths "src_face1_path" "src_face2_path" ... 111 | ``` 112 | 113 | The command follow will replace dst_face1 and dst_face2 detected in input_video.mp4 with src_face1 and src_face2: 114 | ```bash 115 | python run_faceswapper.py --source input_video.mp4 --dst_face_paths dst_face1.jpg dst_face2.jpg --src_face_paths src_face1.jpg src_face2.jpg 116 | ``` 117 | 118 | |args|description| 119 | |:---:|:---:| 120 | |source|The image or video to be swapped| 121 | |dst_face_paths|The images includding faces in source to be swapped. If None, replace all faces in source media.| 122 | |src_face_paths|The images includding faces in source to be swapped| 123 | 124 | 125 | # Attention 126 | Do not apply this software to scenarios that violate morality, law, or infringement. The consequences caused by using this software shall be borne by the user themselves. 127 | 128 | # Sponsor 129 | [Thank you for support](https://www.paypal.com/paypalme/justldu) 130 | 131 | # Thanks 132 | - [insightface](https://github.com/deepinsight/insightface) 133 | - [GFPGAN](https://github.com/TencentARC/GFPGAN) 134 | - [GFPGAN-onnxruntime-demo](https://github.com/xuanandsix/GFPGAN-onnxruntime-demo) 135 | - [BSRGAN](https://github.com/cszn/BSRGAN) 136 | - [pose-transfer](https://github.com/prasunroy/pose-transfer) 137 | - [openpose-pytorch](https://github.com/prasunroy/openpose-pytorch) 138 | -------------------------------------------------------------------------------- /README_ch.md: -------------------------------------------------------------------------------- 1 | [English](README.md)|简体中文 2 | 3 | [![aistudio](https://img.shields.io/static/v1?label=aistudio&message=aistudio&color=blue)](https://aistudio.baidu.com/projectdetail/6759162) 4 | 5 | # DoFaker: 一个简单易用的换脸工具 6 | 基于insightface开发,可以轻松替换视频或图片中的人脸。支持windows和linux系统,CPU和GPU推理。onnxruntime推理,无需pytorch。 7 | 8 |

9 | 10 |

11 | 12 |

13 | 14 |

15 | 16 |

17 | 18 | 19 |

20 | 21 | # 更新 22 | - 2023/9/16 更新动作迁移算法 23 | - 2023/9/14 更新脸部增强算法(GFPGAN)和超分算法(BSRGAN) 24 | 25 | # 教程 26 | - [B站视频使用教程](https://www.bilibili.com/video/BV1b8411i7A8/) 27 | - [AiStudio在线免费体验](https://aistudio.baidu.com/projectdetail/6759162) 28 | 29 | 30 | # 快速开始 31 | 克隆代码,安装dofaker 32 | ```bash 33 | git clone https://github.com/justld/dofaker.git 34 | cd dofaker 35 | conda create -n dofaker 36 | conda activate dofaker 37 | pip install onnxruntime # onnxruntime-gpu 38 | pip install -e . 39 | ``` 40 | 41 | 打开web服务(权重自动下载): 42 | ```bash 43 | dofaker 44 | ``` 45 | 46 | 命令行: 47 | ``` 48 | bash test.sh 49 | ``` 50 | 51 | 52 | ## 源码安装 53 | 手动安装onnxruntime或onnxruntime-gpu. 54 | 55 | ### conda install 56 | 创建conda虚拟环境: 57 | ```bash 58 | git clone https://github.com/justld/dofaker.git 59 | cd dofaker 60 | conda create -n dofaker 61 | conda activate dofaker 62 | pip install -r requirements.txt 63 | pip install onnxruntime # onnxruntime-gpu 64 | ``` 65 | 66 | ### pip install 67 | ```bash 68 | git clone https://github.com/justld/dofaker.git 69 | cd dofaker 70 | pip install -r requirements.txt 71 | pip install onnxruntime # onnxruntime-gpu 72 | ``` 73 | 74 | ## 二、Download Weight 75 | 所有的权重来自[release](https://github.com/justld/dofaker/releases),权重来自底部的链接。 76 | 77 | 解压下载好的权重文件,目录结构如下所示: 78 | ``` 79 | |-dofaker 80 | |-docs 81 | |-weights 82 | ----|-models 83 | --------|-buffalo_l 84 | ----------|-1k3d68.onnx 85 | ----------|-2d106det.onnx 86 | ----------|-... 87 | --------|-buffalo_l.zip 88 | --------|-inswapper_128.onnx 89 | --------|-GFPGANv1.3.onnx 90 | --------|-bsrgan_4.onnx 91 | |-run_faceswapper.py 92 | |-web_ui.py 93 | ``` 94 | 95 | 96 | ## 三、使用 97 | 您可以以web或命令行的方式进行使用 98 | ### web ui 99 | web使用方式只支持单个人脸替换,同时替换多个人脸请使用命令行的方式: 100 | ```bash 101 | python web_ui.py 102 | ``` 103 | 104 | ### command 105 | 命令行的使用方法支持一次性多个人脸替换: 106 | ```bash 107 | python run_faceswapper.py --source "image or video path to be swapped" --dst_face_paths "dst_face1_path" "dst_face2_path" ... --src_face_paths "src_face1_path" "src_face2_path" ... 108 | ``` 109 | 110 | 以下的命令会使用src_face1和src_face2替换视频input_video.mp4中的dst_face1和dst_face2 : 111 | ```bash 112 | python run_faceswapper.py --source input_video.mp4 --dst_face_paths dst_face1.jpg dst_face2.jpg --src_face_paths src_face1.jpg src_face2.jpg 113 | ``` 114 | 115 | |参数|说明| 116 | |:---:|:---:| 117 | |source|需要替换人脸的图片或视频| 118 | |dst_face_paths|待替换的图片或视频中的目标人脸路径,如果为None,待替换的图片和视频中的所有人脸都被替换为src_face| 119 | |src_face_paths|新的人脸图片路径,用于替换目标图片或视频| 120 | 121 | 122 | # 声明 123 | 禁止将本软件用于违反法律、道德,侵权等场合,本软件仅供学习用途,使用本软件造成的一切后果由使用者承担。 124 | 125 | # 赞助 126 | [您的支持是我们持续开发的动力](https://justld.github.io/) 127 | 128 | # Thanks 129 | - [insightface](https://github.com/deepinsight/insightface) 130 | - [GFPGAN](https://github.com/TencentARC/GFPGAN) 131 | - [GFPGAN-onnxruntime-demo](https://github.com/xuanandsix/GFPGAN-onnxruntime-demo) 132 | - [BSRGAN](https://github.com/cszn/BSRGAN) 133 | - [pose-transfer](https://github.com/prasunroy/pose-transfer) 134 | - [openpose-pytorch](https://github.com/prasunroy/openpose-pytorch) 135 | -------------------------------------------------------------------------------- /docs/images/andy.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justld/dofaker/d81dc0c49f37f91430a34e20b5d3eab56ca58b9d/docs/images/andy.png -------------------------------------------------------------------------------- /docs/images/multi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justld/dofaker/d81dc0c49f37f91430a34e20b5d3eab56ca58b9d/docs/images/multi.png -------------------------------------------------------------------------------- /docs/images/source.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justld/dofaker/d81dc0c49f37f91430a34e20b5d3eab56ca58b9d/docs/images/source.gif -------------------------------------------------------------------------------- /docs/images/swapped.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justld/dofaker/d81dc0c49f37f91430a34e20b5d3eab56ca58b9d/docs/images/swapped.gif -------------------------------------------------------------------------------- /docs/images/trump.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justld/dofaker/d81dc0c49f37f91430a34e20b5d3eab56ca58b9d/docs/images/trump.jpg -------------------------------------------------------------------------------- /docs/test/condition.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justld/dofaker/d81dc0c49f37f91430a34e20b5d3eab56ca58b9d/docs/test/condition.jpg -------------------------------------------------------------------------------- /docs/test/dst1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justld/dofaker/d81dc0c49f37f91430a34e20b5d3eab56ca58b9d/docs/test/dst1.png -------------------------------------------------------------------------------- /docs/test/dst2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justld/dofaker/d81dc0c49f37f91430a34e20b5d3eab56ca58b9d/docs/test/dst2.png -------------------------------------------------------------------------------- /docs/test/multi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justld/dofaker/d81dc0c49f37f91430a34e20b5d3eab56ca58b9d/docs/test/multi.png -------------------------------------------------------------------------------- /docs/test/taitan.jpeg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justld/dofaker/d81dc0c49f37f91430a34e20b5d3eab56ca58b9d/docs/test/taitan.jpeg -------------------------------------------------------------------------------- /docs/test/target_pose_reference.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justld/dofaker/d81dc0c49f37f91430a34e20b5d3eab56ca58b9d/docs/test/target_pose_reference.jpg -------------------------------------------------------------------------------- /docs/test/trump.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justld/dofaker/d81dc0c49f37f91430a34e20b5d3eab56ca58b9d/docs/test/trump.jpg -------------------------------------------------------------------------------- /dofaker/__init__.py: -------------------------------------------------------------------------------- 1 | from .face_det import FaceAnalysis 2 | from .face_swap import InSwapper 3 | from .face_enhance import GFPGAN 4 | from .super_resolution import BSRGAN 5 | from .pose import PoseEstimator 6 | from .face_core import FaceSwapper 7 | from .pose_core import PoseSwapper 8 | -------------------------------------------------------------------------------- /dofaker/face_core.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | import numpy as np 4 | import cv2 5 | from moviepy.editor import VideoFileClip 6 | 7 | from .face_det import FaceAnalysis 8 | from .super_resolution import BSRGAN 9 | from dofaker.face_swap import get_swapper_model 10 | from dofaker.face_enhance import GFPGAN 11 | 12 | 13 | class FaceSwapper: 14 | 15 | def __init__(self, 16 | face_det_model='buffalo_l', 17 | face_swap_model='inswapper', 18 | image_sr_model='bsrgan', 19 | face_enhance_model='gfpgan', 20 | face_det_model_dir='weights/models', 21 | face_swap_model_dir='weights/models', 22 | image_sr_model_dir='weights/models', 23 | face_enhance_model_dir='weights/models', 24 | face_sim_thre=0.5, 25 | log_iters=10, 26 | use_enhancer=True, 27 | use_sr=True, 28 | scale=1): 29 | self.face_sim_thre = face_sim_thre 30 | self.log_iters = log_iters 31 | 32 | self.det_model = FaceAnalysis(name=face_det_model, 33 | root=face_det_model_dir) 34 | self.det_model.prepare(ctx_id=1, det_size=(640, 640)) 35 | 36 | self.swapper_model = get_swapper_model(name=face_swap_model, 37 | root=face_swap_model_dir) 38 | if use_enhancer: 39 | self.face_enhance = GFPGAN(name=face_enhance_model, 40 | root=face_enhance_model_dir) 41 | else: 42 | self.face_enhance = None 43 | 44 | if use_sr: 45 | self.sr = BSRGAN(name=image_sr_model, 46 | root=image_sr_model_dir, 47 | scale=scale) 48 | self.scale = scale 49 | else: 50 | self.sr = None 51 | self.scale = scale 52 | 53 | def run(self, 54 | input_path: str, 55 | dst_face_paths, 56 | src_face_paths, 57 | output_dir='output'): 58 | if isinstance(dst_face_paths, str): 59 | dst_face_paths = [dst_face_paths] 60 | if isinstance(src_face_paths, str): 61 | src_face_paths = [src_face_paths] 62 | if input_path.lower().endswith(('jpg', 'jpeg', 'webp', 'png', 'bmp')): 63 | return self.swap_image(input_path, dst_face_paths, src_face_paths, 64 | output_dir) 65 | else: 66 | return self.swap_video(input_path, dst_face_paths, src_face_paths, 67 | output_dir) 68 | 69 | def swap_video(self, 70 | input_video_path, 71 | dst_face_paths, 72 | src_face_paths, 73 | output_dir='output'): 74 | assert os.path.exists( 75 | input_video_path), 'The input video path {} not exist.' 76 | os.makedirs(output_dir, exist_ok=True) 77 | src_faces = self.get_faces(src_face_paths) 78 | if dst_face_paths is not None: 79 | dst_faces = self.get_faces(dst_face_paths) 80 | dst_face_embeddings = self.get_faces_embeddings(dst_faces) 81 | assert len(dst_faces) == len( 82 | src_faces 83 | ), 'The detected faces in source images not equal target image faces.' 84 | 85 | video = cv2.VideoCapture(input_video_path) 86 | fps = video.get(cv2.CAP_PROP_FPS) 87 | total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) 88 | width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) 89 | height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) 90 | frame_size = (width, height) 91 | print('video fps: {}, total_frames: {}, width: {}, height: {}'.format( 92 | fps, total_frames, width, height)) 93 | 94 | video_name = os.path.basename(input_video_path).split('.')[0] 95 | four_cc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') 96 | temp_video_path = os.path.join(output_dir, 97 | 'temp_{}.mp4'.format(video_name)) 98 | save_video_path = os.path.join(output_dir, '{}.mp4'.format(video_name)) 99 | output_video = cv2.VideoWriter( 100 | temp_video_path, four_cc, fps, 101 | (int(frame_size[0] * self.scale), int(frame_size[1] * self.scale))) 102 | 103 | i = 0 104 | while video.isOpened(): 105 | ret, frame = video.read() 106 | if ret: 107 | if dst_face_paths is not None: 108 | swapped_image = self.swap_faces(frame, 109 | dst_face_embeddings, 110 | src_faces=src_faces) 111 | else: 112 | swapped_image = self.swap_all_faces(frame, 113 | src_faces=src_faces) 114 | i += 1 115 | if i % self.log_iters == 0: 116 | print('processing {}/{}'.format(i, total_frames)) 117 | output_video.write(swapped_image) 118 | else: 119 | break 120 | 121 | video.release() 122 | output_video.release() 123 | self.add_audio_to_video(input_video_path, temp_video_path, 124 | save_video_path) 125 | os.remove(temp_video_path) 126 | return save_video_path 127 | 128 | def swap_image(self, 129 | image_path, 130 | dst_face_paths, 131 | src_face_paths, 132 | output_dir='output'): 133 | os.makedirs(output_dir, exist_ok=True) 134 | src_faces = self.get_faces(src_face_paths) 135 | if dst_face_paths is not None: 136 | dst_faces = self.get_faces(dst_face_paths) 137 | dst_face_embeddings = self.get_faces_embeddings(dst_faces) 138 | assert len(dst_faces) == len( 139 | src_faces 140 | ), 'The detected faces in source images not equal target image faces.' 141 | 142 | image = cv2.imread(image_path) 143 | if dst_face_paths is not None: 144 | swapped_image = self.swap_faces(image, 145 | dst_face_embeddings, 146 | src_faces=src_faces) 147 | else: 148 | swapped_image = self.swap_all_faces(image, src_faces=src_faces) 149 | base_name = os.path.basename(image_path) 150 | save_path = os.path.join(output_dir, base_name) 151 | cv2.imwrite(save_path, swapped_image) 152 | return save_path 153 | 154 | def add_audio_to_video(self, src_video_path, target_video_path, 155 | save_video_path): 156 | audio = VideoFileClip(src_video_path).audio 157 | target_video = VideoFileClip(target_video_path) 158 | target_video = target_video.set_audio(audio) 159 | target_video.write_videofile(save_video_path) 160 | return target_video_path 161 | 162 | def get_faces(self, image_paths): 163 | if isinstance(image_paths, str): 164 | image_paths = [image_paths] 165 | faces = [] 166 | for image_path in image_paths: 167 | image = cv2.imread(image_path) 168 | assert image is not None, "the source image is None, please check your image {} format.".format( 169 | image_path) 170 | img_faces = self.det_model.get(image, max_num=1) 171 | assert len( 172 | img_faces 173 | ) == 1, 'The detected face in image {} must be 1, but got {}, please ensure your image including one face.'.format( 174 | image_path, len(img_faces)) 175 | faces += img_faces 176 | return faces 177 | 178 | def swap_faces(self, image, dst_face_embeddings: np.ndarray, 179 | src_faces: list) -> np.ndarray: 180 | res = image.copy() 181 | image_faces = self.det_model.get(image) 182 | if len(image_faces) == 0: 183 | return res 184 | image_face_embeddings = self.get_faces_embeddings(image_faces) 185 | sim = np.dot(dst_face_embeddings, image_face_embeddings.T) 186 | 187 | for i in range(dst_face_embeddings.shape[0]): 188 | index = np.where(sim[i] > self.face_sim_thre)[0].tolist() 189 | for idx in index: 190 | res = self.swapper_model.get(res, 191 | image_faces[idx], 192 | src_faces[i], 193 | paste_back=True) 194 | if self.face_enhance is not None: 195 | res = self.face_enhance.get(res, 196 | image_faces[idx], 197 | paste_back=True) 198 | 199 | if self.sr is not None: 200 | res = self.sr.get(res, image_format='bgr') 201 | return res 202 | 203 | def swap_all_faces(self, image, src_faces: list) -> np.ndarray: 204 | assert len( 205 | src_faces 206 | ) == 1, 'If replace all faces in source, the number of src face should be 1, but got {}.'.format( 207 | len(src_faces)) 208 | res = image.copy() 209 | image_faces = self.det_model.get(image) 210 | if len(image_faces) == 0: 211 | return res 212 | for image_face in image_faces: 213 | res = self.swapper_model.get(res, 214 | image_face, 215 | src_faces[0], 216 | paste_back=True) 217 | if self.face_enhance is not None: 218 | res = self.face_enhance.get(res, image_face, paste_back=True) 219 | if self.sr is not None: 220 | res = self.sr.get(res, image_format='bgr') 221 | return res 222 | 223 | def get_faces_embeddings(self, faces): 224 | feats = [] 225 | for face in faces: 226 | feats.append(face.normed_embedding) 227 | if len(feats) == 1: 228 | feats = np.array(feats, dtype=np.float32).reshape(1, -1) 229 | else: 230 | feats = np.array(feats, dtype=np.float32) 231 | return feats 232 | -------------------------------------------------------------------------------- /dofaker/face_det/__init__.py: -------------------------------------------------------------------------------- 1 | from .face_analysis import FaceAnalysis 2 | -------------------------------------------------------------------------------- /dofaker/face_det/face_analysis.py: -------------------------------------------------------------------------------- 1 | ''' 2 | The following code references:: https://github.com/deepinsight/insightface 3 | ''' 4 | 5 | import glob 6 | import os.path as osp 7 | 8 | import onnxruntime 9 | 10 | from insightface import model_zoo 11 | from insightface.utils import ensure_available 12 | from insightface.app.common import Face 13 | 14 | from dofaker.utils import download_file, get_model_url 15 | 16 | __all__ = ['FaceAnalysis'] 17 | 18 | 19 | class FaceAnalysis: 20 | 21 | def __init__(self, 22 | name='buffalo_l', 23 | root='weights', 24 | allowed_modules=None, 25 | **kwargs): 26 | self.model_dir, _ = download_file(get_model_url(name), 27 | save_dir=root, 28 | overwrite=False) 29 | onnxruntime.set_default_logger_severity(3) 30 | 31 | self.models = {} 32 | print(self.model_dir) 33 | onnx_files = glob.glob(osp.join(self.model_dir, '*.onnx')) 34 | onnx_files = sorted(onnx_files) 35 | for onnx_file in onnx_files: 36 | model = model_zoo.get_model(onnx_file, **kwargs) 37 | if model is None: 38 | print('model not recognized:', onnx_file) 39 | elif allowed_modules is not None and model.taskname not in allowed_modules: 40 | print('model ignore:', onnx_file, model.taskname) 41 | del model 42 | elif model.taskname not in self.models and (allowed_modules is None 43 | or model.taskname 44 | in allowed_modules): 45 | print('find model:', onnx_file, model.taskname, 46 | model.input_shape, model.input_mean, model.input_std) 47 | self.models[model.taskname] = model 48 | else: 49 | print('duplicated model task type, ignore:', onnx_file, 50 | model.taskname) 51 | del model 52 | assert 'detection' in self.models 53 | self.det_model = self.models['detection'] 54 | 55 | def prepare(self, ctx_id, det_thresh=0.5, det_size=(640, 640)): 56 | self.det_thresh = det_thresh 57 | assert det_size is not None, "det_size can't be None." 58 | self.det_size = det_size 59 | for taskname, model in self.models.items(): 60 | if taskname == 'detection': 61 | model.prepare(ctx_id, 62 | input_size=det_size, 63 | det_thresh=det_thresh) 64 | else: 65 | model.prepare(ctx_id) 66 | 67 | def get(self, img, max_num=0): 68 | bboxes, kpss = self.det_model.detect(img, 69 | max_num=max_num, 70 | metric='default') 71 | if bboxes.shape[0] == 0: 72 | return [] 73 | ret = [] 74 | for i in range(bboxes.shape[0]): 75 | bbox = bboxes[i, 0:4] 76 | det_score = bboxes[i, 4] 77 | kps = None 78 | if kpss is not None: 79 | kps = kpss[i] 80 | face = Face(bbox=bbox, kps=kps, det_score=det_score) 81 | for taskname, model in self.models.items(): 82 | if taskname == 'detection': 83 | continue 84 | model.get(img, face) 85 | ret.append(face) 86 | return ret 87 | 88 | def draw_on(self, img, faces): 89 | import cv2 90 | dimg = img.copy() 91 | for i in range(len(faces)): 92 | face = faces[i] 93 | box = face.bbox.astype('int') 94 | color = (0, 0, 255) 95 | cv2.rectangle(dimg, (box[0], box[1]), (box[2], box[3]), color, 2) 96 | if face.kps is not None: 97 | kps = face.kps.astype('int') 98 | for l in range(kps.shape[0]): 99 | color = (0, 0, 255) 100 | if l == 0 or l == 3: 101 | color = (0, 255, 0) 102 | cv2.circle(dimg, (kps[l][0], kps[l][1]), 1, color, 2) 103 | if face.gender is not None and face.age is not None: 104 | cv2.putText(dimg, '%s,%d' % (face.sex, face.age), 105 | (box[0] - 1, box[1] - 4), cv2.FONT_HERSHEY_COMPLEX, 106 | 0.7, (0, 255, 0), 1) 107 | return dimg 108 | -------------------------------------------------------------------------------- /dofaker/face_enhance/__init__.py: -------------------------------------------------------------------------------- 1 | from .gfpgan import GFPGAN 2 | -------------------------------------------------------------------------------- /dofaker/face_enhance/gfpgan.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | import cv2 4 | 5 | from insightface.utils import face_align 6 | from insightface import model_zoo 7 | from dofaker.utils import download_file, get_model_url 8 | 9 | 10 | class GFPGAN: 11 | 12 | def __init__(self, name='gfpgan', root='weights/models') -> None: 13 | _, model_file = download_file(get_model_url(name), 14 | save_dir=root, 15 | overwrite=False) 16 | providers = model_zoo.model_zoo.get_default_providers() 17 | self.session = model_zoo.model_zoo.PickableInferenceSession( 18 | model_file, providers=providers) 19 | 20 | self.input_mean = 127.5 21 | self.input_std = 127.5 22 | inputs = self.session.get_inputs() 23 | self.input_names = [] 24 | for inp in inputs: 25 | self.input_names.append(inp.name) 26 | outputs = self.session.get_outputs() 27 | output_names = [] 28 | for out in outputs: 29 | output_names.append(out.name) 30 | self.output_names = output_names 31 | assert len( 32 | self.output_names 33 | ) == 1, "The output number of GFPGAN model should be 1, but got {}, please check your model.".format( 34 | len(self.output_names)) 35 | output_shape = outputs[0].shape 36 | input_cfg = inputs[0] 37 | input_shape = input_cfg.shape 38 | self.input_shape = input_shape 39 | print('face_enhance-shape:', self.input_shape) 40 | self.input_size = tuple(input_shape[2:4][::-1]) 41 | 42 | def forward(self, image, image_format='bgr'): 43 | if isinstance(image, str): 44 | image = cv2.imread(image, 1) 45 | elif isinstance(image, np.ndarray): 46 | if image_format == 'bgr': 47 | image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 48 | elif image_format == 'rgb': 49 | pass 50 | else: 51 | raise UserWarning( 52 | "gfpgan not support image format {}".format(image_format)) 53 | else: 54 | raise UserWarning( 55 | "gfpgan input must be str or np.ndarray, but got {}.".format( 56 | type(image))) 57 | img = (image - self.input_mean) / self.input_std 58 | pred = self.session.run(self.output_names, 59 | {self.input_names[0]: img})[0] 60 | return pred 61 | 62 | def _get(self, img, image_format='bgr'): 63 | if image_format.lower() == 'bgr': 64 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 65 | elif image_format.lower() == 'rgb': 66 | pass 67 | else: 68 | raise UserWarning( 69 | "gfpgan not support image format {}".format(image_format)) 70 | h, w, c = img.shape 71 | img = cv2.resize(img, (self.input_shape[-1], self.input_shape[-2])) 72 | blob = cv2.dnn.blobFromImage( 73 | img, 74 | 1.0 / self.input_std, 75 | self.input_size, 76 | (self.input_mean, self.input_mean, self.input_mean), 77 | swapRB=False) 78 | pred = self.session.run(self.output_names, 79 | {self.input_names[0]: blob})[0] 80 | image_aug = pred.transpose((0, 2, 3, 1))[0] 81 | rgb_aug = np.clip(self.input_std * image_aug + self.input_mean, 0, 82 | 255).astype(np.uint8) 83 | rgb_aug = cv2.resize(rgb_aug, (w, h)) 84 | bgr_image = rgb_aug[:, :, ::-1] 85 | return bgr_image 86 | 87 | def get(self, img, target_face, paste_back=True, image_format='bgr'): 88 | aimg, M = face_align.norm_crop2(img, target_face.kps, 89 | self.input_size[0]) 90 | bgr_fake = self._get(aimg, image_format='bgr') 91 | if not paste_back: 92 | return bgr_fake, M 93 | else: 94 | target_img = img 95 | fake_diff = bgr_fake.astype(np.float32) - aimg.astype(np.float32) 96 | fake_diff = np.abs(fake_diff).mean(axis=2) 97 | fake_diff[:2, :] = 0 98 | fake_diff[-2:, :] = 0 99 | fake_diff[:, :2] = 0 100 | fake_diff[:, -2:] = 0 101 | IM = cv2.invertAffineTransform(M) 102 | img_white = np.full((aimg.shape[0], aimg.shape[1]), 103 | 255, 104 | dtype=np.float32) 105 | bgr_fake = cv2.warpAffine( 106 | bgr_fake, 107 | IM, (target_img.shape[1], target_img.shape[0]), 108 | borderValue=0.0) 109 | img_white = cv2.warpAffine( 110 | img_white, 111 | IM, (target_img.shape[1], target_img.shape[0]), 112 | borderValue=0.0) 113 | fake_diff = cv2.warpAffine( 114 | fake_diff, 115 | IM, (target_img.shape[1], target_img.shape[0]), 116 | borderValue=0.0) 117 | img_white[img_white > 20] = 255 118 | fthresh = 10 119 | fake_diff[fake_diff < fthresh] = 0 120 | fake_diff[fake_diff >= fthresh] = 255 121 | img_mask = img_white 122 | mask_h_inds, mask_w_inds = np.where(img_mask == 255) 123 | mask_h = np.max(mask_h_inds) - np.min(mask_h_inds) 124 | mask_w = np.max(mask_w_inds) - np.min(mask_w_inds) 125 | mask_size = int(np.sqrt(mask_h * mask_w)) 126 | k = max(mask_size // 10, 10) 127 | #k = max(mask_size//20, 6) 128 | #k = 6 129 | kernel = np.ones((k, k), np.uint8) 130 | img_mask = cv2.erode(img_mask, kernel, iterations=1) 131 | kernel = np.ones((2, 2), np.uint8) 132 | fake_diff = cv2.dilate(fake_diff, kernel, iterations=1) 133 | k = max(mask_size // 20, 5) 134 | kernel_size = (k, k) 135 | blur_size = tuple(2 * i + 1 for i in kernel_size) 136 | img_mask = cv2.GaussianBlur(img_mask, blur_size, 0) 137 | k = 5 138 | kernel_size = (k, k) 139 | blur_size = tuple(2 * i + 1 for i in kernel_size) 140 | fake_diff = cv2.GaussianBlur(fake_diff, blur_size, 0) 141 | img_mask /= 255 142 | fake_diff /= 255 143 | img_mask = np.reshape(img_mask, 144 | [img_mask.shape[0], img_mask.shape[1], 1]) 145 | fake_merged = img_mask * bgr_fake + ( 146 | 1 - img_mask) * target_img.astype(np.float32) 147 | fake_merged = fake_merged.astype(np.uint8) 148 | return fake_merged 149 | -------------------------------------------------------------------------------- /dofaker/face_swap/__init__.py: -------------------------------------------------------------------------------- 1 | from .inswapper import InSwapper 2 | 3 | 4 | def get_swapper_model(name='', root=None, **kwargs): 5 | if name.lower() == 'inswapper': 6 | return InSwapper(name=name, root=root, **kwargs) 7 | else: 8 | raise UserWarning('The swapper model {} not support.'.format(name)) 9 | -------------------------------------------------------------------------------- /dofaker/face_swap/base_swapper.py: -------------------------------------------------------------------------------- 1 | class BaseSwapper: 2 | 3 | def forward(self, img, latent, *args, **kwargs): 4 | raise NotImplementedError 5 | 6 | def get(self, 7 | img, 8 | target_face, 9 | source_face, 10 | paste_back=True, 11 | *args, 12 | **kwargs): 13 | raise NotImplementedError 14 | -------------------------------------------------------------------------------- /dofaker/face_swap/inswapper.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | import cv2 3 | import onnx 4 | from onnx import numpy_helper 5 | 6 | from insightface import model_zoo 7 | from insightface.utils import face_align 8 | from .base_swapper import BaseSwapper 9 | 10 | from dofaker.utils import download_file, get_model_url 11 | 12 | 13 | class InSwapper(BaseSwapper): 14 | 15 | def __init__(self, name='inswapper', root='weights/models'): 16 | _, model_file = download_file(get_model_url(name), 17 | save_dir=root, 18 | overwrite=False) 19 | providers = model_zoo.model_zoo.get_default_providers() 20 | self.session = model_zoo.model_zoo.PickableInferenceSession( 21 | model_file, providers=providers) 22 | 23 | model = onnx.load(model_file) 24 | graph = model.graph 25 | self.emap = numpy_helper.to_array(graph.initializer[-1]) 26 | self.input_mean = 0.0 27 | self.input_std = 255.0 28 | 29 | inputs = self.session.get_inputs() 30 | self.input_names = [] 31 | for inp in inputs: 32 | self.input_names.append(inp.name) 33 | outputs = self.session.get_outputs() 34 | output_names = [] 35 | for out in outputs: 36 | output_names.append(out.name) 37 | self.output_names = output_names 38 | assert len( 39 | self.output_names 40 | ) == 1, "The output number of inswapper model should be 1, but got {}, please check your model.".format( 41 | len(self.output_names)) 42 | output_shape = outputs[0].shape 43 | input_cfg = inputs[0] 44 | input_shape = input_cfg.shape 45 | self.input_shape = input_shape 46 | print('inswapper-shape:', self.input_shape) 47 | self.input_size = tuple(input_shape[2:4][::-1]) 48 | 49 | def forward(self, img, latent): 50 | img = (img - self.input_mean) / self.input_std 51 | pred = self.session.run(self.output_names, { 52 | self.input_names[0]: img, 53 | self.input_names[1]: latent 54 | })[0] 55 | return pred 56 | 57 | def get(self, img, target_face, source_face, paste_back=True): 58 | aimg, M = face_align.norm_crop2(img, target_face.kps, 59 | self.input_size[0]) 60 | blob = cv2.dnn.blobFromImage( 61 | aimg, 62 | 1.0 / self.input_std, 63 | self.input_size, 64 | (self.input_mean, self.input_mean, self.input_mean), 65 | swapRB=True) 66 | latent = source_face.normed_embedding.reshape((1, -1)) 67 | latent = np.dot(latent, self.emap) 68 | latent /= np.linalg.norm(latent) 69 | pred = self.session.run(self.output_names, { 70 | self.input_names[0]: blob, 71 | self.input_names[1]: latent 72 | })[0] 73 | img_fake = pred.transpose((0, 2, 3, 1))[0] 74 | bgr_fake = np.clip(255 * img_fake, 0, 255).astype(np.uint8)[:, :, ::-1] 75 | if not paste_back: 76 | return bgr_fake, M 77 | else: 78 | target_img = img 79 | fake_diff = bgr_fake.astype(np.float32) - aimg.astype(np.float32) 80 | fake_diff = np.abs(fake_diff).mean(axis=2) 81 | fake_diff[:2, :] = 0 82 | fake_diff[-2:, :] = 0 83 | fake_diff[:, :2] = 0 84 | fake_diff[:, -2:] = 0 85 | IM = cv2.invertAffineTransform(M) 86 | img_white = np.full((aimg.shape[0], aimg.shape[1]), 87 | 255, 88 | dtype=np.float32) 89 | bgr_fake = cv2.warpAffine( 90 | bgr_fake, 91 | IM, (target_img.shape[1], target_img.shape[0]), 92 | borderValue=0.0) 93 | img_white = cv2.warpAffine( 94 | img_white, 95 | IM, (target_img.shape[1], target_img.shape[0]), 96 | borderValue=0.0) 97 | fake_diff = cv2.warpAffine( 98 | fake_diff, 99 | IM, (target_img.shape[1], target_img.shape[0]), 100 | borderValue=0.0) 101 | img_white[img_white > 20] = 255 102 | fthresh = 10 103 | fake_diff[fake_diff < fthresh] = 0 104 | fake_diff[fake_diff >= fthresh] = 255 105 | img_mask = img_white 106 | mask_h_inds, mask_w_inds = np.where(img_mask == 255) 107 | mask_h = np.max(mask_h_inds) - np.min(mask_h_inds) 108 | mask_w = np.max(mask_w_inds) - np.min(mask_w_inds) 109 | mask_size = int(np.sqrt(mask_h * mask_w)) 110 | k = max(mask_size // 10, 10) 111 | #k = max(mask_size//20, 6) 112 | #k = 6 113 | kernel = np.ones((k, k), np.uint8) 114 | img_mask = cv2.erode(img_mask, kernel, iterations=1) 115 | kernel = np.ones((2, 2), np.uint8) 116 | fake_diff = cv2.dilate(fake_diff, kernel, iterations=1) 117 | k = max(mask_size // 20, 5) 118 | #k = 3 119 | #k = 3 120 | kernel_size = (k, k) 121 | blur_size = tuple(2 * i + 1 for i in kernel_size) 122 | img_mask = cv2.GaussianBlur(img_mask, blur_size, 0) 123 | k = 5 124 | kernel_size = (k, k) 125 | blur_size = tuple(2 * i + 1 for i in kernel_size) 126 | fake_diff = cv2.GaussianBlur(fake_diff, blur_size, 0) 127 | img_mask /= 255 128 | fake_diff /= 255 129 | #img_mask = fake_diff 130 | img_mask = np.reshape(img_mask, 131 | [img_mask.shape[0], img_mask.shape[1], 1]) 132 | fake_merged = img_mask * bgr_fake + ( 133 | 1 - img_mask) * target_img.astype(np.float32) 134 | fake_merged = fake_merged.astype(np.uint8) 135 | return fake_merged 136 | -------------------------------------------------------------------------------- /dofaker/pose/__init__.py: -------------------------------------------------------------------------------- 1 | from .pose_estimator import PoseEstimator 2 | from .pose_transfer import PoseTransfer 3 | -------------------------------------------------------------------------------- /dofaker/pose/pose_estimator.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | import cv2 4 | from scipy.ndimage.filters import gaussian_filter 5 | 6 | from .pose_utils import _get_keypoints, _pad_image 7 | from insightface import model_zoo 8 | from dofaker.utils import download_file, get_model_url 9 | 10 | 11 | class PoseEstimator: 12 | 13 | def __init__(self, name='openpose_body', root='weights/models'): 14 | _, model_file = download_file(get_model_url(name), 15 | save_dir=root, 16 | overwrite=False) 17 | providers = model_zoo.model_zoo.get_default_providers() 18 | self.session = model_zoo.model_zoo.PickableInferenceSession( 19 | model_file, providers=providers) 20 | 21 | self.input_mean = 127.5 22 | self.input_std = 255.0 23 | inputs = self.session.get_inputs() 24 | self.input_names = [] 25 | for inp in inputs: 26 | self.input_names.append(inp.name) 27 | outputs = self.session.get_outputs() 28 | output_names = [] 29 | for out in outputs: 30 | output_names.append(out.name) 31 | self.output_names = output_names 32 | assert len( 33 | self.output_names 34 | ) == 2, "The output number of PoseEstimator model should be 2, but got {}, please check your model.".format( 35 | len(self.output_names)) 36 | output_shape = outputs[0].shape 37 | input_cfg = inputs[0] 38 | input_shape = input_cfg.shape 39 | self.input_shape = input_shape 40 | print('pose estimator shape:', self.input_shape) 41 | 42 | def forward(self, image, image_format='rgb'): 43 | if isinstance(image, str): 44 | image = cv2.imread(image, 1) 45 | image_format = 'bgr' 46 | elif isinstance(image, np.ndarray): 47 | if image_format == 'bgr': 48 | pass 49 | elif image_format == 'rgb': 50 | image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR) 51 | image_format = 'bgr' 52 | else: 53 | raise UserWarning( 54 | "PoseEstimator not support image format {}".format( 55 | image_format)) 56 | else: 57 | raise UserWarning( 58 | "PoseEstimator input must be str or np.ndarray, but got {}.". 59 | format(type(image))) 60 | 61 | scales = [0.5] 62 | stride = 8 63 | bboxsize = 368 64 | padvalue = 128 65 | thresh_1 = 0.1 66 | thresh_2 = 0.05 67 | 68 | multipliers = [scale * bboxsize / image.shape[0] for scale in scales] 69 | heatmap_avg = np.zeros((image.shape[0], image.shape[1], 19)) 70 | paf_avg = np.zeros((image.shape[0], image.shape[1], 38)) 71 | 72 | for scale in multipliers: 73 | image_scaled = cv2.resize(image, (0, 0), 74 | fx=scale, 75 | fy=scale, 76 | interpolation=cv2.INTER_CUBIC) 77 | image_padded, pads = _pad_image(image_scaled, stride, padvalue) 78 | 79 | image_tensor = np.expand_dims(np.transpose(image_padded, (2, 0, 1)), 80 | 0) 81 | blob = (np.float32(image_tensor) - self.input_mean) / self.input_std 82 | 83 | pred = self.session.run(self.output_names, 84 | {self.input_names[0]: blob}) 85 | Mconv7_stage6_L1, Mconv7_stage6_L2 = pred[0], pred[1] 86 | 87 | heatmap = np.transpose(np.squeeze(Mconv7_stage6_L2), (1, 2, 0)) 88 | heatmap = cv2.resize(heatmap, (0, 0), 89 | fx=stride, 90 | fy=stride, 91 | interpolation=cv2.INTER_CUBIC) 92 | heatmap = heatmap[:image_padded.shape[0] - 93 | pads[3], :image_padded.shape[1] - pads[2], :] 94 | heatmap = cv2.resize(heatmap, (image.shape[1], image.shape[0]), 95 | interpolation=cv2.INTER_CUBIC) 96 | 97 | paf = np.transpose(np.squeeze(Mconv7_stage6_L1), (1, 2, 0)) 98 | paf = cv2.resize(paf, (0, 0), 99 | fx=stride, 100 | fy=stride, 101 | interpolation=cv2.INTER_CUBIC) 102 | paf = paf[:image_padded.shape[0] - pads[3], :image_padded.shape[1] - 103 | pads[2], :] 104 | paf = cv2.resize(paf, (image.shape[1], image.shape[0]), 105 | interpolation=cv2.INTER_CUBIC) 106 | 107 | heatmap_avg += (heatmap / len(multipliers)) 108 | paf_avg += (paf / len(multipliers)) 109 | 110 | all_peaks = [] 111 | num_peaks = 0 112 | 113 | for part in range(18): 114 | map_orig = heatmap_avg[:, :, part] 115 | map_filt = gaussian_filter(map_orig, sigma=3) 116 | 117 | map_L = np.zeros_like(map_filt) 118 | map_T = np.zeros_like(map_filt) 119 | map_R = np.zeros_like(map_filt) 120 | map_B = np.zeros_like(map_filt) 121 | map_L[1:, :] = map_filt[:-1, :] 122 | map_T[:, 1:] = map_filt[:, :-1] 123 | map_R[:-1, :] = map_filt[1:, :] 124 | map_B[:, :-1] = map_filt[:, 1:] 125 | 126 | peaks_binary = np.logical_and.reduce( 127 | (map_filt >= map_L, map_filt >= map_T, map_filt 128 | >= map_R, map_filt >= map_B, map_filt > thresh_1)) 129 | peaks = list( 130 | zip(np.nonzero(peaks_binary)[1], 131 | np.nonzero(peaks_binary)[0])) 132 | peaks_ids = range(num_peaks, num_peaks + len(peaks)) 133 | peaks_with_scores = [ 134 | peak + (map_orig[peak[1], peak[0]], ) for peak in peaks 135 | ] 136 | peaks_with_scores_and_ids = [peaks_with_scores[i] + (peaks_ids[i],) \ 137 | for i in range(len(peaks_ids))] 138 | all_peaks.append(peaks_with_scores_and_ids) 139 | num_peaks += len(peaks) 140 | 141 | map_idx = [[31, 32], [39, 40], [33, 34], [35, 36], [41, 42], [43, 44], 142 | [19, 20], [21, 22], [23, 24], [25, 26], [27, 28], [29, 30], 143 | [47, 48], [49, 50], [53, 54], [51, 52], [55, 56], [37, 38], 144 | [45, 46]] 145 | limbseq = [[2, 3], [2, 6], [3, 4], [4, 5], [6, 7], [7, 8], [2, 9], 146 | [9, 10], [10, 11], [2, 12], [12, 13], [13, 14], [2, 1], 147 | [1, 15], [15, 17], [1, 16], [16, 18], [3, 17], [6, 18]] 148 | 149 | all_connections = [] 150 | spl_k = [] 151 | mid_n = 10 152 | 153 | for k in range(len(map_idx)): 154 | score_mid = paf_avg[:, :, [x - 19 for x in map_idx[k]]] 155 | candidate_A = all_peaks[limbseq[k][0] - 1] 156 | candidate_B = all_peaks[limbseq[k][1] - 1] 157 | n_A = len(candidate_A) 158 | n_B = len(candidate_B) 159 | index_A, index_B = limbseq[k] 160 | if n_A != 0 and n_B != 0: 161 | connection_candidates = [] 162 | for i in range(n_A): 163 | for j in range(n_B): 164 | v = np.subtract(candidate_B[j][:2], candidate_A[i][:2]) 165 | n = np.sqrt(v[0] * v[0] + v[1] * v[1]) 166 | v = np.divide(v, n) 167 | 168 | ab = list( 169 | zip( 170 | np.linspace(candidate_A[i][0], 171 | candidate_B[j][0], 172 | num=mid_n), 173 | np.linspace(candidate_A[i][1], 174 | candidate_B[j][1], 175 | num=mid_n))) 176 | vx = np.array([ 177 | score_mid[int(round(ab[x][1])), 178 | int(round(ab[x][0])), 0] 179 | for x in range(len(ab)) 180 | ]) 181 | vy = np.array([ 182 | score_mid[int(round(ab[x][1])), 183 | int(round(ab[x][0])), 1] 184 | for x in range(len(ab)) 185 | ]) 186 | score_midpoints = np.multiply(vx, v[0]) + np.multiply( 187 | vy, v[1]) 188 | score_with_dist_prior = sum( 189 | score_midpoints) / len(score_midpoints) + min( 190 | 0.5 * image.shape[0] / n - 1, 0) 191 | criterion_1 = len( 192 | np.nonzero(score_midpoints > thresh_2) 193 | [0]) > 0.8 * len(score_midpoints) 194 | criterion_2 = score_with_dist_prior > 0 195 | if criterion_1 and criterion_2: 196 | connection_candidate = [ 197 | i, j, score_with_dist_prior, 198 | score_with_dist_prior + candidate_A[i][2] + 199 | candidate_B[j][2] 200 | ] 201 | connection_candidates.append(connection_candidate) 202 | connection_candidates = sorted(connection_candidates, 203 | key=lambda x: x[2], 204 | reverse=True) 205 | connection = np.zeros((0, 5)) 206 | for candidate in connection_candidates: 207 | i, j, s = candidate[0:3] 208 | if i not in connection[:, 3] and j not in connection[:, 4]: 209 | connection = np.vstack([ 210 | connection, 211 | [candidate_A[i][3], candidate_B[j][3], s, i, j] 212 | ]) 213 | if len(connection) >= min(n_A, n_B): 214 | break 215 | all_connections.append(connection) 216 | else: 217 | spl_k.append(k) 218 | all_connections.append([]) 219 | 220 | candidate = np.array( 221 | [item for sublist in all_peaks for item in sublist]) 222 | subset = np.ones((0, 20)) * -1 223 | 224 | for k in range(len(map_idx)): 225 | if k not in spl_k: 226 | part_As = all_connections[k][:, 0] 227 | part_Bs = all_connections[k][:, 1] 228 | index_A, index_B = np.array(limbseq[k]) - 1 229 | for i in range(len(all_connections[k])): 230 | found = 0 231 | subset_idx = [-1, -1] 232 | for j in range(len(subset)): 233 | if subset[j][index_A] == part_As[i] or subset[j][ 234 | index_B] == part_Bs[i]: 235 | subset_idx[found] = j 236 | found += 1 237 | if found == 1: 238 | j = subset_idx[0] 239 | if subset[j][index_B] != part_Bs[i]: 240 | subset[j][index_B] = part_Bs[i] 241 | subset[j][-1] += 1 242 | subset[j][-2] += candidate[ 243 | part_Bs[i].astype(int), 244 | 2] + all_connections[k][i][2] 245 | elif found == 2: 246 | j1, j2 = subset_idx 247 | membership = ((subset[j1] >= 0).astype(int) + 248 | (subset[j2] >= 0).astype(int))[:-2] 249 | if len(np.nonzero(membership == 2)[0]) == 0: 250 | subset[j1][:-2] += (subset[j2][:-2] + 1) 251 | subset[j1][-2:] += subset[j2][-2:] 252 | subset[j1][-2] += all_connections[k][i][2] 253 | subset = np.delete(subset, j2, 0) 254 | else: 255 | subset[j1][index_B] = part_Bs[i] 256 | subset[j1][-1] += 1 257 | subset[j1][-2] += candidate[ 258 | part_Bs[i].astype(int), 259 | 2] + all_connections[k][i][2] 260 | elif not found and k < 17: 261 | row = np.ones(20) * -1 262 | row[index_A] = part_As[i] 263 | row[index_B] = part_Bs[i] 264 | row[-1] = 2 265 | row[-2] = sum( 266 | candidate[all_connections[k][i, :2].astype(int), 267 | 2]) + all_connections[k][i][2] 268 | subset = np.vstack([subset, row]) 269 | 270 | del_idx = [] 271 | 272 | for i in range(len(subset)): 273 | if subset[i][-1] < 4 or subset[i][-2] / subset[i][-1] < 0.4: 274 | del_idx.append(i) 275 | subset = np.delete(subset, del_idx, axis=0) 276 | 277 | return _get_keypoints(candidate, subset) 278 | 279 | def get(self, image, image_format='rgb'): 280 | return self.forward(image, image_format) 281 | -------------------------------------------------------------------------------- /dofaker/pose/pose_transfer.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import numpy as np 3 | from scipy.ndimage.filters import gaussian_filter 4 | 5 | from .pose_utils import _get_keypoints, _pad_image 6 | from insightface import model_zoo 7 | from dofaker.utils import download_file, get_model_url 8 | from dofaker.transforms import center_crop, pad 9 | 10 | 11 | class PoseTransfer: 12 | 13 | def __init__(self, 14 | name='pose_transfer', 15 | root='weights/models', 16 | pose_estimator=None): 17 | assert pose_estimator is not None, "The pose_estimator of PoseTransfer shouldn't be None" 18 | self.pose_estimator = pose_estimator 19 | _, model_file = download_file(get_model_url(name), 20 | save_dir=root, 21 | overwrite=False) 22 | providers = model_zoo.model_zoo.get_default_providers() 23 | self.session = model_zoo.model_zoo.PickableInferenceSession( 24 | model_file, providers=providers) 25 | 26 | self.input_mean = 127.5 27 | self.input_std = 127.5 28 | inputs = self.session.get_inputs() 29 | self.input_names = [] 30 | for inp in inputs: 31 | self.input_names.append(inp.name) 32 | outputs = self.session.get_outputs() 33 | output_names = [] 34 | for out in outputs: 35 | output_names.append(out.name) 36 | self.output_names = output_names 37 | assert len( 38 | self.output_names 39 | ) == 1, "The output number of PoseTransfer model should be 1, but got {}, please check your model.".format( 40 | len(self.output_names)) 41 | output_shape = outputs[0].shape 42 | input_cfg = inputs[0] 43 | input_shape = input_cfg.shape 44 | self.input_shape = input_shape 45 | print('pose transfer shape:', self.input_shape) 46 | 47 | def forward(self, source_image, target_image, image_format='rgb'): 48 | h, w, c = source_image.shape 49 | if image_format == 'rgb': 50 | pass 51 | elif image_format == 'bgr': 52 | source_image = cv2.cvtColor(source_image, cv2.COLOR_BGR2RGB) 53 | target_image = cv2.cvtColor(target_image, cv2.COLOR_BGR2RGB) 54 | image_format = 'rgb' 55 | else: 56 | raise UserWarning( 57 | "PoseTransfer not support image format {}".format(image_format)) 58 | imgA = self._resize_and_pad_image(source_image) 59 | kptA = self._estimate_keypoints(imgA, image_format=image_format) 60 | mapA = self._keypoints2heatmaps(kptA) 61 | 62 | imgB = self._resize_and_pad_image(target_image) 63 | kptB = self._estimate_keypoints(imgB) 64 | mapB = self._keypoints2heatmaps(kptB) 65 | 66 | imgA_t = (imgA.astype('float32') - self.input_mean) / self.input_std 67 | imgA_t = imgA_t.transpose([2, 0, 1])[None, ...] 68 | mapA_t = mapA.transpose([2, 0, 1])[None, ...] 69 | mapB_t = mapB.transpose([2, 0, 1])[None, ...] 70 | mapAB_t = np.concatenate((mapA_t, mapB_t), axis=1) 71 | pred = self.session.run(self.output_names, { 72 | self.input_names[0]: imgA_t, 73 | self.input_names[1]: mapAB_t 74 | })[0] 75 | target_image = pred.transpose((0, 2, 3, 1))[0] 76 | bgr_target_image = np.clip( 77 | self.input_std * target_image + self.input_mean, 0, 78 | 255).astype(np.uint8)[:, :, ::-1] 79 | crop_size = (256, 80 | min((256 * target_image.shape[1] // target_image.shape[0]), 81 | 176)) 82 | bgr_image = center_crop(bgr_target_image, crop_size) 83 | bgr_image = cv2.resize(bgr_image, (w, h), interpolation=cv2.INTER_CUBIC) 84 | return bgr_image 85 | 86 | def get(self, source_image, target_image, image_format='rgb'): 87 | return self.forward(source_image, target_image, image_format) 88 | 89 | def _resize_and_pad_image(self, image: np.ndarray, size=256): 90 | w = size * image.shape[1] // image.shape[0] 91 | w_box = min(w, size * 11 // 16) 92 | image = cv2.resize(image, (w, size), interpolation=cv2.INTER_CUBIC) 93 | image = center_crop(image, (size, w_box)) 94 | image = pad(image, 95 | size - w_box, 96 | size - w_box, 97 | size - w_box, 98 | size - w_box, 99 | fill=255) 100 | image = center_crop(image, (size, size)) 101 | return image 102 | 103 | def _estimate_keypoints(self, image: np.ndarray, image_format='rgb'): 104 | keypoints = self.pose_estimator.get(image, image_format) 105 | keypoints = keypoints[0] if len(keypoints) > 0 else np.zeros( 106 | (18, 3), dtype=np.int32) 107 | keypoints[np.where(keypoints[:, 2] == 0), :2] = -1 108 | keypoints = keypoints[:, :2] 109 | return keypoints 110 | 111 | def _keypoints2heatmaps(self, keypoints, size=256): 112 | heatmaps = np.zeros((size, size, keypoints.shape[0]), dtype=np.float32) 113 | for k in range(keypoints.shape[0]): 114 | x, y = keypoints[k] 115 | if x == -1 or y == -1: 116 | continue 117 | heatmaps[y, x, k] = 1.0 118 | return heatmaps 119 | -------------------------------------------------------------------------------- /dofaker/pose/pose_utils.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | 4 | def _pad_image(image, stride=1, padvalue=0): 5 | assert len(image.shape) == 2 or len(image.shape) == 3 6 | h, w = image.shape[:2] 7 | pads = [None] * 4 8 | pads[0] = 0 # left 9 | pads[1] = 0 # top 10 | pads[2] = 0 if (w % stride == 0) else stride - (w % stride) # right 11 | pads[3] = 0 if (h % stride == 0) else stride - (h % stride) # bottom 12 | num_channels = 1 if len(image.shape) == 2 else image.shape[2] 13 | image_padded = np.ones( 14 | (h + pads[3], w + pads[2], num_channels), dtype=np.uint8) * padvalue 15 | image_padded = np.squeeze(image_padded) 16 | image_padded[:h, :w] = image 17 | return image_padded, pads 18 | 19 | 20 | def _get_keypoints(candidates, subsets): 21 | k = subsets.shape[0] 22 | keypoints = np.zeros((k, 18, 3), dtype=np.int32) 23 | for i in range(k): 24 | for j in range(18): 25 | index = np.int32(subsets[i][j]) 26 | if index != -1: 27 | x, y = np.int32(candidates[index][:2]) 28 | keypoints[i][j] = (x, y, 1) 29 | return keypoints 30 | -------------------------------------------------------------------------------- /dofaker/pose_core.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | 4 | import numpy as np 5 | from moviepy.editor import VideoFileClip 6 | 7 | from .pose import PoseEstimator, PoseTransfer 8 | from .face_enhance import GFPGAN 9 | from .super_resolution import BSRGAN 10 | from .face_det import FaceAnalysis 11 | 12 | 13 | class PoseSwapper: 14 | 15 | def __init__(self, 16 | pose_estimator_name='openpose_body', 17 | pose_estimator_model_dir='weights/models', 18 | pose_transfer_name='pose_transfer', 19 | pose_transfer_model_dir='weights/models', 20 | image_sr_model='bsrgan', 21 | image_sr_model_dir='weights/models', 22 | face_enhance_name='gfpgan', 23 | face_enhance_model_dir='weights/models/', 24 | face_det_model='buffalo_l', 25 | face_det_model_dir='weights/models', 26 | log_iters=10, 27 | use_enhancer=True, 28 | use_sr=True, 29 | scale=1): 30 | pose_estimator = PoseEstimator(name=pose_estimator_name, 31 | root=pose_estimator_model_dir) 32 | self.pose_transfer = PoseTransfer(name=pose_transfer_name, 33 | root=pose_transfer_model_dir, 34 | pose_estimator=pose_estimator) 35 | 36 | if use_enhancer: 37 | self.det_model = FaceAnalysis(name=face_det_model, 38 | root=face_det_model_dir) 39 | self.det_model.prepare(ctx_id=1, det_size=(640, 640)) 40 | self.face_enhance = GFPGAN(name=face_enhance_name, 41 | root=face_enhance_model_dir) 42 | self.use_enhancer = use_enhancer 43 | 44 | if use_sr: 45 | self.sr_model = BSRGAN(name=image_sr_model, 46 | root=image_sr_model_dir, 47 | scale=scale) 48 | self.scale = scale 49 | else: 50 | self.scale = 1 51 | self.use_sr = use_sr 52 | self.log_iters = log_iters 53 | 54 | def run(self, input_path, target_path, output_dir='output'): 55 | assert os.path.exists( 56 | input_path), "The input path {} not exists.".format(input_path) 57 | assert os.path.exists( 58 | target_path), "The target path {} not exists.".format(target_path) 59 | os.makedirs(output_dir, exist_ok=True) 60 | assert input_path.lower().endswith( 61 | ('jpg', 'jpeg', 'webp', 'png', 'bmp') 62 | ), "pose swapper input must be image endswith ('jpg', 'jpeg', 'webp', 'png', 'bmp'), but got {}.".format( 63 | input_path) 64 | if target_path.lower().endswith(('jpg', 'jpeg', 'webp', 'png', 'bmp')): 65 | return self.transfer_image(input_path, target_path, output_dir) 66 | else: 67 | return self.transfer_video(input_path, target_path, output_dir) 68 | 69 | def transfer_image(self, input_path, target_path, output_dir): 70 | source = cv2.imread(input_path) 71 | target = cv2.imread(target_path) 72 | transferred_image = self.transfer_pose(source, 73 | target, 74 | image_format='bgr') 75 | base_name = os.path.basename(input_path) 76 | output_path = os.path.join(output_dir, base_name) 77 | cv2.imwrite(output_path, transferred_image) 78 | return output_path 79 | 80 | def transfer_video(self, input_path, target_path, output_dir): 81 | source = cv2.imread(input_path) 82 | video = cv2.VideoCapture(target_path) 83 | fps = video.get(cv2.CAP_PROP_FPS) 84 | total_frames = int(video.get(cv2.CAP_PROP_FRAME_COUNT)) 85 | height, width, _ = source.shape 86 | frame_size = (width, height) 87 | print('video fps: {}, total_frames: {}, width: {}, height: {}'.format( 88 | fps, total_frames, width, height)) 89 | 90 | video_name = os.path.basename(input_path).split('.')[0] 91 | four_cc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') 92 | temp_video_path = os.path.join(output_dir, 93 | 'temp_{}.mp4'.format(video_name)) 94 | save_video_path = os.path.join(output_dir, '{}.mp4'.format(video_name)) 95 | output_video = cv2.VideoWriter( 96 | temp_video_path, four_cc, fps, 97 | (int(frame_size[0] * self.scale), int(frame_size[1] * self.scale))) 98 | i = 0 99 | while video.isOpened(): 100 | ret, frame = video.read() 101 | if ret: 102 | transferred_image = self.transfer_pose(source, 103 | frame, 104 | image_format='bgr') 105 | i += 1 106 | if i % self.log_iters == 0: 107 | print('processing {}/{}'.format(i, total_frames)) 108 | output_video.write(transferred_image) 109 | else: 110 | break 111 | 112 | video.release() 113 | output_video.release() 114 | print(temp_video_path) 115 | self.add_audio_to_video(target_path, temp_video_path, save_video_path) 116 | os.remove(temp_video_path) 117 | return save_video_path 118 | 119 | def transfer_pose(self, source, target, image_format='bgr'): 120 | transferred_image = self.pose_transfer.get(source, 121 | target, 122 | image_format=image_format) 123 | if self.use_enhancer: 124 | faces = self.det_model.get(transferred_image, max_num=1) 125 | for face in faces: 126 | transferred_image = self.face_enhance.get( 127 | transferred_image, 128 | face, 129 | paste_back=True, 130 | image_format=image_format) 131 | 132 | if self.use_sr: 133 | transferred_image = self.sr_model.get(transferred_image, 134 | image_format=image_format) 135 | return transferred_image 136 | 137 | def add_audio_to_video(self, src_video_path, target_video_path, 138 | save_video_path): 139 | audio = VideoFileClip(src_video_path).audio 140 | target_video = VideoFileClip(target_video_path) 141 | target_video = target_video.set_audio(audio) 142 | target_video.write_videofile(save_video_path) 143 | return target_video_path 144 | -------------------------------------------------------------------------------- /dofaker/super_resolution/__init__.py: -------------------------------------------------------------------------------- 1 | from .bsrgan import BSRGAN 2 | -------------------------------------------------------------------------------- /dofaker/super_resolution/bsrgan.py: -------------------------------------------------------------------------------- 1 | import numpy as np 2 | 3 | import cv2 4 | 5 | from insightface import model_zoo 6 | from dofaker.utils import download_file, get_model_url 7 | 8 | 9 | class BSRGAN: 10 | 11 | def __init__(self, name='bsrgan', root='weights/models', scale=1) -> None: 12 | _, model_file = download_file(get_model_url(name), 13 | save_dir=root, 14 | overwrite=False) 15 | self.scale = scale 16 | providers = model_zoo.model_zoo.get_default_providers() 17 | self.session = model_zoo.model_zoo.PickableInferenceSession( 18 | model_file, providers=providers) 19 | 20 | self.input_mean = 0.0 21 | self.input_std = 255.0 22 | inputs = self.session.get_inputs() 23 | self.input_names = [] 24 | for inp in inputs: 25 | self.input_names.append(inp.name) 26 | outputs = self.session.get_outputs() 27 | output_names = [] 28 | for out in outputs: 29 | output_names.append(out.name) 30 | self.output_names = output_names 31 | assert len( 32 | self.output_names 33 | ) == 1, "The output number of BSRGAN model should be 1, but got {}, please check your model.".format( 34 | len(self.output_names)) 35 | output_shape = outputs[0].shape 36 | input_cfg = inputs[0] 37 | input_shape = input_cfg.shape 38 | self.input_shape = input_shape 39 | print('image super resolution shape:', self.input_shape) 40 | 41 | def forward(self, image, image_format='bgr'): 42 | if isinstance(image, str): 43 | image = cv2.imread(image, 1) 44 | image_format = 'bgr' 45 | elif isinstance(image, np.ndarray): 46 | if image_format == 'bgr': 47 | image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) 48 | elif image_format == 'rgb': 49 | pass 50 | else: 51 | raise UserWarning( 52 | "BSRGAN not support image format {}".format(image_format)) 53 | else: 54 | raise UserWarning( 55 | "BSRGAN input must be str or np.ndarray, but got {}.".format( 56 | type(image))) 57 | img = (image - self.input_mean) / self.input_std 58 | pred = self.session.run(self.output_names, 59 | {self.input_names[0]: img})[0] 60 | return pred 61 | 62 | def get(self, img, image_format='bgr'): 63 | if image_format.lower() == 'bgr': 64 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 65 | elif image_format.lower() == 'rgb': 66 | pass 67 | else: 68 | raise UserWarning( 69 | "gfpgan not support image format {}".format(image_format)) 70 | h, w, c = img.shape 71 | blob = cv2.dnn.blobFromImage( 72 | img, 73 | 1.0 / self.input_std, (w, h), 74 | (self.input_mean, self.input_mean, self.input_mean), 75 | swapRB=False) 76 | pred = self.session.run(self.output_names, 77 | {self.input_names[0]: blob})[0] 78 | image_aug = pred.transpose((0, 2, 3, 1))[0] 79 | rgb_aug = np.clip(self.input_std * image_aug + self.input_mean, 0, 80 | 255).astype(np.uint8) 81 | rgb_aug = cv2.resize(rgb_aug, 82 | (int(w * self.scale), int(h * self.scale))) 83 | bgr_aug = rgb_aug[:, :, ::-1] 84 | return bgr_aug 85 | -------------------------------------------------------------------------------- /dofaker/transforms/__init__.py: -------------------------------------------------------------------------------- 1 | from .functional import center_crop, pad 2 | -------------------------------------------------------------------------------- /dofaker/transforms/functional.py: -------------------------------------------------------------------------------- 1 | import numbers 2 | import numpy as np 3 | 4 | import cv2 5 | 6 | 7 | def center_crop(image: np.ndarray, output_size): 8 | if isinstance(output_size, numbers.Number): 9 | output_size = (int(output_size), int(output_size)) 10 | elif isinstance(output_size, (tuple, list)) and len(output_size) == 1: 11 | output_size = (output_size[0], output_size[0]) 12 | 13 | image_height, image_width, c = image.shape 14 | crop_height, crop_width = output_size 15 | 16 | if crop_width > image_width or crop_height > image_height: 17 | padding_ltrb = [ 18 | (crop_width - image_width) // 2 if crop_width > image_width else 0, 19 | (crop_height - image_height) // 20 | 2 if crop_height > image_height else 0, 21 | (crop_width - image_width + 1) // 22 | 2 if crop_width > image_width else 0, 23 | (crop_height - image_height + 1) // 24 | 2 if crop_height > image_height else 0, 25 | ] 26 | image = cv2.copyMakeBorder(image, 27 | padding_ltrb[1], 28 | padding_ltrb[3], 29 | padding_ltrb[0], 30 | padding_ltrb[2], 31 | cv2.BORDER_CONSTANT, 32 | value=(0, 0, 0)) 33 | image_height, image_width, c = image.shape 34 | if crop_width == image_width and crop_height == image_height: 35 | return image 36 | 37 | crop_top = int(round((image_height - crop_height) / 2.0)) 38 | crop_left = int(round((image_width - crop_width) / 2.0)) 39 | return image[crop_top:crop_top + crop_height, 40 | crop_left:crop_left + crop_width] 41 | 42 | 43 | def pad(image, 44 | left, 45 | top, 46 | right, 47 | bottom, 48 | fill: int = 0, 49 | padding_mode: str = "constant"): 50 | if padding_mode == 'constant': 51 | return cv2.copyMakeBorder(image, 52 | top, 53 | bottom, 54 | left, 55 | right, 56 | cv2.BORDER_CONSTANT, 57 | value=(fill, fill, fill)) 58 | else: 59 | raise UserWarning('padding mode {} not supported.'.format(padding_mode)) 60 | -------------------------------------------------------------------------------- /dofaker/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .download import download_file 2 | from .weights_urls import get_model_url 3 | -------------------------------------------------------------------------------- /dofaker/utils/download.py: -------------------------------------------------------------------------------- 1 | import os 2 | import requests 3 | import zipfile 4 | 5 | from tqdm import tqdm 6 | 7 | 8 | def download_file(url: str, save_dir='./', overwrite=False, unzip=True): 9 | os.makedirs(save_dir, exist_ok=True) 10 | file_name = url.split('/')[-1] 11 | file_path = os.path.join(save_dir, file_name) 12 | 13 | if os.path.exists(file_path) and not overwrite: 14 | pass 15 | else: 16 | print('Downloading file {} from {}...'.format(file_path, url)) 17 | 18 | r = requests.get(url, stream=True) 19 | print(r.status_code) 20 | if r.status_code != 200: 21 | raise RuntimeError('Failed downloading url {}!'.format(url)) 22 | total_length = r.headers.get('content-length') 23 | with open(file_path, 'wb') as f: 24 | if total_length is None: # no content length header 25 | for chunk in r.iter_content(chunk_size=1024): 26 | if chunk: # filter out keep-alive new chunks 27 | f.write(chunk) 28 | else: 29 | total_length = int(total_length) 30 | print('file length: ', int(total_length / 1024. + 0.5)) 31 | for chunk in tqdm(r.iter_content(chunk_size=1024), 32 | total=int(total_length / 1024. + 0.5), 33 | unit='KB', 34 | unit_scale=False, 35 | dynamic_ncols=True): 36 | f.write(chunk) 37 | if unzip and file_path.endswith('.zip'): 38 | save_dir = file_path.split('.')[0] 39 | if os.path.isdir(save_dir) and os.path.exists(save_dir): 40 | pass 41 | else: 42 | with zipfile.ZipFile(file_path, 'r') as zip_ref: 43 | zip_ref.extractall(save_dir) 44 | 45 | return save_dir, file_path 46 | -------------------------------------------------------------------------------- /dofaker/utils/utils.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/justld/dofaker/d81dc0c49f37f91430a34e20b5d3eab56ca58b9d/dofaker/utils/utils.py -------------------------------------------------------------------------------- /dofaker/utils/weights_urls.py: -------------------------------------------------------------------------------- 1 | WEIGHT_URLS = { 2 | 'buffalo_l': 3 | 'https://github.com/justld/dofaker/releases/download/v0.1/buffalo_l.zip', 4 | 'buffalo_s': 5 | 'https://github.com/justld/dofaker/releases/download/v0.1/buffalo_s.zip', 6 | 'buffalo_sc': 7 | 'https://github.com/justld/dofaker/releases/download/v0.1/buffalo_sc.zip', 8 | 'inswapper': 9 | 'https://github.com/justld/dofaker/releases/download/v0.1/inswapper_128.onnx', 10 | 'gfpgan': 11 | 'https://github.com/justld/dofaker/releases/download/v0.1/GFPGANv1.3.onnx', 12 | 'bsrgan': 13 | 'https://github.com/justld/dofaker/releases/download/v0.1/bsrgan_4.onnx', 14 | 'openpose_body': 15 | 'https://github.com/justld/dofaker/releases/download/v0.1/openpose_body.onnx', 16 | 'pose_transfer': 17 | 'https://github.com/justld/dofaker/releases/download/v0.1/pose_transfer.onnx', 18 | } 19 | 20 | 21 | def get_model_url(model_name): 22 | return WEIGHT_URLS[model_name] 23 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | moviepy 2 | gradio>=4.8 3 | insightface 4 | flake8 5 | yapf 6 | -------------------------------------------------------------------------------- /run_faceswapper.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from dofaker import FaceSwapper 3 | 4 | 5 | def parse_args(): 6 | parser = argparse.ArgumentParser(description='running face swap') 7 | parser.add_argument('--source', 8 | help='select an image or video to be swapped', 9 | dest='source', 10 | required=True) 11 | parser.add_argument('--dst_face_paths', 12 | help='select images in source to be swapped', 13 | dest='dst_face_paths', 14 | nargs='+', 15 | default=None) 16 | parser.add_argument( 17 | '--src_face_paths', 18 | help='select images to replace dst_faces in source image or video.', 19 | dest='src_face_paths', 20 | nargs='+', 21 | required=True) 22 | parser.add_argument('--output_dir', 23 | help='output directory', 24 | dest='output_dir', 25 | default='output') 26 | parser.add_argument('--det_model_name', 27 | help='detection model name for insightface', 28 | dest='det_model_name', 29 | default='buffalo_l') 30 | parser.add_argument('--det_model_dir', 31 | help='detection model dir for insightface', 32 | dest='det_model_dir', 33 | default='weights/models') 34 | parser.add_argument('--swap_model_name', 35 | help='swap model name', 36 | dest='swap_model_name', 37 | default='inswapper') 38 | parser.add_argument('--image_sr_model', 39 | help='image super resolution model', 40 | dest='image_sr_model', 41 | default='bsrgan') 42 | parser.add_argument('--face_swap_model_dir', 43 | help='swap model path', 44 | dest='face_swap_model_dir', 45 | default='weights/models') 46 | parser.add_argument('--image_sr_model_dir', 47 | help='image super resolution model dir', 48 | dest='image_sr_model_dir', 49 | default='weights/models') 50 | parser.add_argument('--face_enhance_name', 51 | help='face enhance model', 52 | dest='face_enhance_name', 53 | default='gfpgan') 54 | parser.add_argument('--face_enhance_model_dir', 55 | help='face enhance model dir', 56 | dest='face_enhance_model_dir', 57 | default='weights/models') 58 | parser.add_argument('--face_sim_thre', 59 | help='similarity of face embedding threshold', 60 | dest='face_sim_thre', 61 | default=0.5) 62 | parser.add_argument('--log_iters', 63 | help='print log intervals', 64 | dest='log_iters', 65 | default=10, 66 | type=int) 67 | parser.add_argument('--use_enhancer', 68 | help='whether use face enhance model', 69 | dest='use_enhancer', 70 | action='store_true') 71 | parser.add_argument('--use_sr', 72 | help='whether use image super resolution model', 73 | dest='use_sr', 74 | action='store_true') 75 | parser.add_argument('--sr_scale', 76 | help='image super resolution scale', 77 | dest='sr_scale', 78 | default=1, 79 | type=float) 80 | return parser.parse_args() 81 | 82 | 83 | if __name__ == '__main__': 84 | args = parse_args() 85 | faker = FaceSwapper( 86 | face_det_model=args.det_model_name, 87 | face_det_model_dir=args.det_model_dir, 88 | face_swap_model=args.swap_model_name, 89 | face_swap_model_dir=args.face_swap_model_dir, 90 | image_sr_model=args.image_sr_model, 91 | image_sr_model_dir=args.image_sr_model_dir, 92 | face_enhance_model=args.face_enhance_name, 93 | face_enhance_model_dir=args.face_enhance_model_dir, 94 | face_sim_thre=args.face_sim_thre, 95 | log_iters=args.log_iters, 96 | use_enhancer=args.use_enhancer, 97 | use_sr=args.use_sr, 98 | scale=args.sr_scale, 99 | ) 100 | 101 | faker.run( 102 | input_path=args.source, 103 | dst_face_paths=args.dst_face_paths, 104 | src_face_paths=args.src_face_paths, 105 | output_dir=args.output_dir, 106 | ) 107 | -------------------------------------------------------------------------------- /run_posetransfer.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | from dofaker import PoseSwapper 3 | 4 | 5 | def parse_args(): 6 | parser = argparse.ArgumentParser(description='running face swap') 7 | parser.add_argument('--source', 8 | help='select an image or video to be swapped', 9 | dest='source', 10 | required=True) 11 | parser.add_argument('--target', 12 | help='the target pose image', 13 | dest='target', 14 | required=True) 15 | parser.add_argument('--output_dir', 16 | help='output directory', 17 | dest='output_dir', 18 | default='output') 19 | parser.add_argument('--pose_estimator_name', 20 | help='pose estimator name', 21 | dest='pose_estimator_name', 22 | default='openpose_body') 23 | parser.add_argument('--pose_estimator_model_dir', 24 | help='pose estimator model dir', 25 | dest='pose_estimator_model_dir', 26 | default='weights/models') 27 | parser.add_argument('--pose_transfer_name', 28 | help='pose transfer name', 29 | dest='pose_transfer_name', 30 | default='pose_transfer') 31 | parser.add_argument('--pose_transfer_model_dir', 32 | help='pose transfer model dir', 33 | dest='pose_transfer_model_dir', 34 | default='weights/models') 35 | parser.add_argument('--det_model_name', 36 | help='detection model name for insightface', 37 | dest='det_model_name', 38 | default='buffalo_l') 39 | parser.add_argument('--det_model_dir', 40 | help='detection model dir for insightface', 41 | dest='det_model_dir', 42 | default='weights/models') 43 | parser.add_argument('--image_sr_model', 44 | help='image super resolution model', 45 | dest='image_sr_model', 46 | default='bsrgan') 47 | parser.add_argument('--image_sr_model_dir', 48 | help='image super resolution model dir', 49 | dest='image_sr_model_dir', 50 | default='weights/models') 51 | parser.add_argument('--face_enhance_name', 52 | help='face enhance model', 53 | dest='face_enhance_name', 54 | default='gfpgan') 55 | parser.add_argument('--face_enhance_model_dir', 56 | help='face enhance model dir', 57 | dest='face_enhance_model_dir', 58 | default='weights/models') 59 | parser.add_argument('--log_iters', 60 | help='print log intervals', 61 | dest='log_iters', 62 | default=10, 63 | type=int) 64 | parser.add_argument('--use_enhancer', 65 | help='whether use face enhance model', 66 | dest='use_enhancer', 67 | action='store_true') 68 | parser.add_argument('--use_sr', 69 | help='whether use image super resolution model', 70 | dest='use_sr', 71 | action='store_true') 72 | parser.add_argument('--sr_scale', 73 | help='image super resolution scale', 74 | dest='sr_scale', 75 | default=1, 76 | type=float) 77 | return parser.parse_args() 78 | 79 | 80 | if __name__ == '__main__': 81 | args = parse_args() 82 | faker = PoseSwapper( 83 | pose_estimator_name=args.pose_estimator_name, 84 | pose_estimator_model_dir=args.pose_estimator_model_dir, 85 | pose_transfer_name=args.pose_transfer_name, 86 | pose_transfer_model_dir=args.pose_transfer_model_dir, 87 | face_det_model=args.det_model_name, 88 | face_det_model_dir=args.det_model_dir, 89 | image_sr_model=args.image_sr_model, 90 | image_sr_model_dir=args.image_sr_model_dir, 91 | face_enhance_name=args.face_enhance_name, 92 | face_enhance_model_dir=args.face_enhance_model_dir, 93 | log_iters=args.log_iters, 94 | use_enhancer=args.use_enhancer, 95 | use_sr=args.use_sr, 96 | scale=args.sr_scale, 97 | ) 98 | 99 | faker.run( 100 | input_path=args.source, 101 | target_path=args.target, 102 | output_dir=args.output_dir, 103 | ) 104 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | with open('requirements.txt') as file: 4 | REQUIRED_PACKAGES = file.read() 5 | 6 | setup(name='dofaker', 7 | version='0.1', 8 | keywords=('face swap'), 9 | description='A simple face swap tool', 10 | url='https://github.com/justld/dofaker', 11 | author='justld', 12 | author_email='1207540056@qq.com', 13 | packages=find_packages(), 14 | include_package_data=True, 15 | platforms='any', 16 | install_requires=REQUIRED_PACKAGES, 17 | scripts=[], 18 | license='GPL 3.0', 19 | entry_points={'console_scripts': [ 20 | 'dofaker = web_ui:main', 21 | ]}) 22 | -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | # python run_faceswapper.py --source docs/test/multi.png --dst_face_paths docs/test/dst1.png --src_face_paths docs/test/trump.jpg 2 | 3 | # python run_faceswapper.py --source docs/test/multi.png --dst_face_paths docs/test/dst1.png docs/test/dst2.png --src_face_paths docs/test/trump.jpg docs/test/taitan.jpeg 4 | 5 | # python run_faceswapper.py --source docs/test/multi.png --dst_face_paths docs/test/dst1.png docs/test/dst2.png --src_face_paths docs/test/trump.jpg docs/test/taitan.jpeg --use_enhancer 6 | 7 | python run_faceswapper.py --source docs/test/multi.png --dst_face_paths docs/test/dst1.png docs/test/dst2.png --src_face_paths docs/test/trump.jpg docs/test/taitan.jpeg --use_enhancer --use_sr --sr_scale 2.0 8 | 9 | # python run_posetransfer.py --source docs/test/condition.jpg --target docs/test/target_pose_reference.jpg 10 | 11 | # python run_posetransfer.py --source docs/test/condition.jpg --target docs/test/target_pose_reference.jpg --use_enhancer 12 | 13 | python run_posetransfer.py --source docs/test/condition.jpg --target docs/test/target_pose_reference.jpg --use_enhancer --use_sr --sr_scale 2.0 14 | -------------------------------------------------------------------------------- /web_ui.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | import gradio as gr 4 | from dofaker import FaceSwapper, PoseSwapper 5 | 6 | 7 | def parse_args(): 8 | parser = argparse.ArgumentParser(description='running face swap') 9 | parser.add_argument( 10 | '--inbrowser', 11 | help= 12 | 'whether to automatically launch the interface in a new tab on the default browser.', 13 | dest='inbrowser', 14 | default=True) 15 | parser.add_argument( 16 | '--server_port', 17 | help= 18 | 'will start gradio app on this port (if available). Can be set by environment variable GRADIO_SERVER_PORT. If None, will search for an available port starting at 7860.', 19 | dest='server_port', 20 | type=int, 21 | default=None) 22 | return parser.parse_args() 23 | 24 | 25 | def swap_face(input_path, dst_path, src_path, use_enhancer, use_sr, scale, 26 | face_sim_thre): 27 | faker = FaceSwapper(use_enhancer=use_enhancer, 28 | use_sr=use_sr, 29 | scale=scale, 30 | face_sim_thre=face_sim_thre) 31 | output_path = faker.run(input_path, dst_path, src_path) 32 | return output_path 33 | 34 | 35 | def swap_pose(input_path, target_path, use_enhancer, use_sr, scale): 36 | faker = PoseSwapper(use_enhancer=use_enhancer, use_sr=use_sr, scale=scale) 37 | output_path = faker.run(input_path, target_path) 38 | return output_path 39 | 40 | 41 | def main(): 42 | args = parse_args() 43 | 44 | with gr.Blocks(title='DoFaker') as web_ui: 45 | gr.Markdown('DoFaker: Face Swap and pose swap web ui') 46 | with gr.Tab('FaceSwapper'): 47 | gr.Markdown('DoFaker: Face Swap Web UI') 48 | with gr.Tab('Image'): 49 | with gr.Row(): 50 | with gr.Column(): 51 | gr.Markdown('The source image to be swapped') 52 | image_input = gr.Image(type='filepath') 53 | with gr.Row(): 54 | with gr.Column(): 55 | gr.Markdown( 56 | 'target face included in source image') 57 | dst_face_image = gr.Image(type='filepath') 58 | with gr.Column(): 59 | gr.Markdown( 60 | 'source face to replace target face') 61 | src_face_image = gr.Image(type='filepath') 62 | 63 | with gr.Column(): 64 | output_image = gr.Image(type='filepath') 65 | use_enhancer = gr.Checkbox( 66 | label="face enhance", 67 | info="Whether use face enhance model.") 68 | with gr.Row(): 69 | use_sr = gr.Checkbox( 70 | label="super resolution", 71 | info="Whether use image resolution model.") 72 | scale = gr.Number( 73 | value=1, label='image super resolution scale') 74 | with gr.Row(): 75 | face_sim_thre = gr.Number( 76 | value=0.6, 77 | label='face similarity threshold', 78 | minimum=0.0, 79 | maximum=1.0) 80 | convert_button = gr.Button('Swap') 81 | convert_button.click(fn=swap_face, 82 | inputs=[ 83 | image_input, dst_face_image, 84 | src_face_image, use_enhancer, 85 | use_sr, scale, face_sim_thre 86 | ], 87 | outputs=[output_image], 88 | api_name='image swap') 89 | 90 | with gr.Tab('Video'): 91 | with gr.Row(): 92 | with gr.Column(): 93 | gr.Markdown('The source video to be swapped') 94 | video_input = gr.Video() 95 | with gr.Row(): 96 | with gr.Column(): 97 | gr.Markdown( 98 | 'target face included in source image') 99 | dst_face_image = gr.Image(type='filepath') 100 | with gr.Column(): 101 | gr.Markdown( 102 | 'source face to replace target face') 103 | src_face_image = gr.Image(type='filepath') 104 | 105 | with gr.Column(): 106 | output_video = gr.Video() 107 | use_enhancer = gr.Checkbox( 108 | label="face enhance", 109 | info="Whether use face enhance model.") 110 | with gr.Row(): 111 | use_sr = gr.Checkbox( 112 | label="super resolution", 113 | info="Whether use image resolution model.") 114 | scale = gr.Number( 115 | value=1, label='image super resolution scale') 116 | with gr.Row(): 117 | face_sim_thre = gr.Number( 118 | value=0.6, 119 | label='face similarity threshold', 120 | minimum=0.0, 121 | maximum=1.0) 122 | convert_button = gr.Button('Swap') 123 | convert_button.click(fn=swap_face, 124 | inputs=[ 125 | video_input, dst_face_image, 126 | src_face_image, use_enhancer, 127 | use_sr, scale, face_sim_thre 128 | ], 129 | outputs=[output_video], 130 | api_name='video swap') 131 | 132 | with gr.Tab('PoseSwapper'): 133 | gr.Markdown('DoFaker: Pose Swap Web UI') 134 | with gr.Tab('Image'): 135 | with gr.Row(): 136 | with gr.Column(): 137 | gr.Markdown('The source image to be swapped') 138 | image_input = gr.Image(type='filepath') 139 | gr.Markdown('The target image with pose') 140 | target = gr.Image(type='filepath') 141 | 142 | with gr.Column(): 143 | output_image = gr.Image(type='filepath') 144 | use_enhancer = gr.Checkbox( 145 | label="face enhance", 146 | info="Whether use face enhance model.") 147 | with gr.Row(): 148 | use_sr = gr.Checkbox( 149 | label="super resolution", 150 | info="Whether use image resolution model.") 151 | scale = gr.Number( 152 | value=1, label='image super resolution scale') 153 | convert_button = gr.Button('Swap') 154 | convert_button.click(fn=swap_pose, 155 | inputs=[ 156 | image_input, target, 157 | use_enhancer, use_sr, scale 158 | ], 159 | outputs=[output_image], 160 | api_name='image swap') 161 | 162 | # with gr.Tab('Video'): 163 | # with gr.Row(): 164 | # with gr.Column(): 165 | # gr.Markdown('The source video to be swapped') 166 | # video_input = gr.Image(type='filepath') 167 | # gr.Markdown('The target image with pose') 168 | # target = gr.Video() 169 | 170 | # with gr.Column(): 171 | # output_video = gr.Video() 172 | # use_enhancer = gr.Checkbox( 173 | # label="face enhance", 174 | # info="Whether use face enhance model.") 175 | # with gr.Row(): 176 | # use_sr = gr.Checkbox( 177 | # label="super resolution", 178 | # info="Whether use image resolution model.") 179 | # scale = gr.Number(value=1, 180 | # label='image super resolution scale') 181 | # convert_button = gr.Button('Swap') 182 | # convert_button.click(fn=swap_pose, 183 | # inputs=[ 184 | # video_input, target, use_enhancer, 185 | # use_sr, scale 186 | # ], 187 | # outputs=[output_video], 188 | # api_name='video swap') 189 | 190 | web_ui.launch(inbrowser=args.inbrowser, server_port=args.server_port) 191 | 192 | 193 | if __name__ == '__main__': 194 | main() 195 | --------------------------------------------------------------------------------