├── .gitignore ├── LICENSE ├── NOTICE ├── README.md ├── assets ├── exp2.png ├── overview.png ├── prior-token.png ├── test.png └── webtoonai.png ├── config └── MatteFormer_Composition1k.toml ├── dataloader ├── __init__.py ├── data_generator.py ├── image_file.py └── prefetcher.py ├── evaluation.py ├── inference.py ├── main.py ├── networks ├── __init__.py ├── decoders │ ├── __init__.py │ └── resnet_decoder.py ├── encoders │ ├── MatteFormer.py │ └── __init__.py ├── generators.py └── ops.py ├── requirements.txt ├── trainers ├── __init__.py └── trainer.py └── utils ├── __init__.py ├── config.py ├── evaluate.py ├── logger.py └── util.py /.gitignore: -------------------------------------------------------------------------------- 1 | experiments 2 | pretrained 3 | predDIM 4 | 5 | .idea 6 | __pycache__ 7 | 8 | 9 | # Byte-compiled / optimized / DLL files 10 | *pyc 11 | __pycache__/ 12 | *.py[cod] 13 | *$py.class 14 | 15 | # C extensions 16 | *.so 17 | 18 | # Distribution / packaging 19 | .Python 20 | build/ 21 | develop-eggs/ 22 | dist/ 23 | downloads/ 24 | eggs/ 25 | .eggs/ 26 | lib/ 27 | lib64/ 28 | parts/ 29 | sdist/ 30 | var/ 31 | wheels/ 32 | pip-wheel-metadata/ 33 | share/python-wheels/ 34 | *.egg-info/ 35 | .installed.cfg 36 | *.egg 37 | MANIFEST 38 | 39 | # PyInstaller 40 | # Usually these files are written by a python script from a template 41 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 42 | *.manifest 43 | *.spec 44 | 45 | # Installer logs 46 | pip-log.txt 47 | pip-delete-this-directory.txt 48 | 49 | # Unit test / coverage reports 50 | htmlcov/ 51 | .tox/ 52 | .nox/ 53 | .coverage 54 | .coverage.* 55 | .cache 56 | nosetests.xml 57 | coverage.xml 58 | *.cover 59 | *.py,cover 60 | .hypothesis/ 61 | .pytest_cache/ 62 | 63 | # Translations 64 | *.mo 65 | *.pot 66 | 67 | # Django stuff: 68 | *.log 69 | local_settings.py 70 | db.sqlite3 71 | db.sqlite3-journal 72 | 73 | # Flask stuff: 74 | instance/ 75 | .webassets-cache 76 | 77 | # Scrapy stuff: 78 | .scrapy 79 | 80 | # Sphinx documentation 81 | docs/_build/ 82 | 83 | # PyBuilder 84 | target/ 85 | 86 | # Jupyter Notebook 87 | .ipynb_checkpoints 88 | 89 | # IPython 90 | profile_default/ 91 | ipython_config.py 92 | 93 | # pyenv 94 | .python-version 95 | 96 | # pipenv 97 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 98 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 99 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 100 | # install all needed dependencies. 101 | #Pipfile.lock 102 | 103 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 104 | __pypackages__/ 105 | 106 | # Celery stuff 107 | celerybeat-schedule 108 | celerybeat.pid 109 | 110 | # SageMath parsed files 111 | *.sage.py 112 | 113 | # Environments 114 | .env 115 | .venv 116 | env/ 117 | venv/ 118 | ENV/ 119 | env.bak/ 120 | venv.bak/ 121 | 122 | # Spyder project settings 123 | .spyderproject 124 | .spyproject 125 | 126 | # Rope project settings 127 | .ropeproject 128 | 129 | # mkdocs documentation 130 | /site 131 | 132 | # mypy 133 | .mypy_cache/ 134 | .dmypy.json 135 | dmypy.json 136 | 137 | # Pyre type checker 138 | .pyre/ 139 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2022-present NAVER WEBTOON 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /NOTICE: -------------------------------------------------------------------------------- 1 | MatteFormer 2 | 3 | Copyright 2022-present NAVER WEBTOON 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | -------------------------------------------------------------------------------------- 18 | 19 | This project is distributed under Apache-2.0, except utils/logger.py which is adopted from https://github.com/JiahuiYu/generative_inpainting under CC BY-NC 4.0. 20 | 21 | This project contains subcomponents with separate copyright notices and license terms. 22 | Your use of the source code for these subcomponents is subject to the terms and conditions of the following licenses. 23 | 24 | ===== 25 | 26 | pytorch/vision 27 | https://github.com/pytorch/vision 28 | 29 | 30 | BSD 3-Clause License 31 | 32 | Copyright (c) Soumith Chintala 2016, 33 | All rights reserved. 34 | 35 | Redistribution and use in source and binary forms, with or without 36 | modification, are permitted provided that the following conditions are met: 37 | 38 | * Redistributions of source code must retain the above copyright notice, this 39 | list of conditions and the following disclaimer. 40 | 41 | * Redistributions in binary form must reproduce the above copyright notice, 42 | this list of conditions and the following disclaimer in the documentation 43 | and/or other materials provided with the distribution. 44 | 45 | * Neither the name of the copyright holder nor the names of its 46 | contributors may be used to endorse or promote products derived from 47 | this software without specific prior written permission. 48 | 49 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 50 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 51 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 52 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 53 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 54 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 55 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 56 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 57 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 58 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 59 | 60 | ===== 61 | 62 | NVIDIA/apex 63 | https://github.com/NVIDIA/apex 64 | 65 | 66 | All rights reserved. 67 | 68 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 69 | 70 | 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 71 | 72 | 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 73 | 74 | 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. 75 | 76 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 77 | 78 | ===== 79 | 80 | microsoft/Swin-Transformer 81 | https://github.com/microsoft/Swin-Transformer 82 | 83 | 84 | MIT License 85 | 86 | Copyright (c) Microsoft Corporation. 87 | 88 | Permission is hereby granted, free of charge, to any person obtaining a copy 89 | of this software and associated documentation files (the "Software"), to deal 90 | in the Software without restriction, including without limitation the rights 91 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 92 | copies of the Software, and to permit persons to whom the Software is 93 | furnished to do so, subject to the following conditions: 94 | 95 | The above copyright notice and this permission notice shall be included in all 96 | copies or substantial portions of the Software. 97 | 98 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 99 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 100 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 101 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 102 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 103 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 104 | SOFTWARE 105 | 106 | ===== 107 | 108 | christiancosgrove/pytorch-spectral-normalization-gan 109 | https://github.com/christiancosgrove/pytorch-spectral-normalization-gan 110 | 111 | 112 | MIT License 113 | 114 | Copyright (c) 2017 Christian Cosgrove 115 | 116 | Permission is hereby granted, free of charge, to any person obtaining a copy 117 | of this software and associated documentation files (the "Software"), to deal 118 | in the Software without restriction, including without limitation the rights 119 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 120 | copies of the Software, and to permit persons to whom the Software is 121 | furnished to do so, subject to the following conditions: 122 | 123 | The above copyright notice and this permission notice shall be included in all 124 | copies or substantial portions of the Software. 125 | 126 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 127 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 128 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 129 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 130 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 131 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 132 | SOFTWARE. 133 | 134 | ===== 135 | 136 | Yaoyi-Li/GCA-Matting 137 | https://github.com/Yaoyi-Li/GCA-Matting 138 | 139 | 140 | MIT License 141 | 142 | Copyright (c) 2019 Li Yaoyi 143 | 144 | Permission is hereby granted, free of charge, to any person obtaining a copy 145 | of this software and associated documentation files (the "Software"), to deal 146 | in the Software without restriction, including without limitation the rights 147 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 148 | copies of the Software, and to permit persons to whom the Software is 149 | furnished to do so, subject to the following conditions: 150 | 151 | The above copyright notice and this permission notice shall be included in all 152 | copies or substantial portions of the Software. 153 | 154 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 155 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 156 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 157 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 158 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 159 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 160 | SOFTWARE. 161 | 162 | ===== 163 | 164 | JiahuiYu/generative_inpainting 165 | https://github.com/JiahuiYu/generative_inpainting 166 | 167 | 168 | ## creative commons 169 | 170 | # Attribution-NonCommercial 4.0 International 171 | 172 | Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible. 173 | 174 | ### Using Creative Commons Public Licenses 175 | 176 | Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses. 177 | 178 | * __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors). 179 | 180 | * __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees). 181 | 182 | ## Creative Commons Attribution-NonCommercial 4.0 International Public License 183 | 184 | By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions. 185 | 186 | ### Section 1 – Definitions. 187 | 188 | a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image. 189 | 190 | b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License. 191 | 192 | c. __Copyright and Similar Rights__ means copyright and/or similar rights closely related to copyright including, without limitation, performance, broadcast, sound recording, and Sui Generis Database Rights, without regard to how the rights are labeled or categorized. For purposes of this Public License, the rights specified in Section 2(b)(1)-(2) are not Copyright and Similar Rights. 193 | 194 | d. __Effective Technological Measures__ means those measures that, in the absence of proper authority, may not be circumvented under laws fulfilling obligations under Article 11 of the WIPO Copyright Treaty adopted on December 20, 1996, and/or similar international agreements. 195 | 196 | e. __Exceptions and Limitations__ means fair use, fair dealing, and/or any other exception or limitation to Copyright and Similar Rights that applies to Your use of the Licensed Material. 197 | 198 | f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License. 199 | 200 | g. __Licensed Rights__ means the rights granted to You subject to the terms and conditions of this Public License, which are limited to all Copyright and Similar Rights that apply to Your use of the Licensed Material and that the Licensor has authority to license. 201 | 202 | h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License. 203 | 204 | i. __NonCommercial__ means not primarily intended for or directed towards commercial advantage or monetary compensation. For purposes of this Public License, the exchange of the Licensed Material for other material subject to Copyright and Similar Rights by digital file-sharing or similar means is NonCommercial provided there is no payment of monetary compensation in connection with the exchange. 205 | 206 | j. __Share__ means to provide material to the public by any means or process that requires permission under the Licensed Rights, such as reproduction, public display, public performance, distribution, dissemination, communication, or importation, and to make material available to the public including in ways that members of the public may access the material from a place and at a time individually chosen by them. 207 | 208 | k. __Sui Generis Database Rights__ means rights other than copyright resulting from Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, as amended and/or succeeded, as well as other essentially equivalent rights anywhere in the world. 209 | 210 | l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning. 211 | 212 | ### Section 2 – Scope. 213 | 214 | a. ___License grant.___ 215 | 216 | 1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to: 217 | 218 | A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and 219 | 220 | B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only. 221 | 222 | 2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions. 223 | 224 | 3. __Term.__ The term of this Public License is specified in Section 6(a). 225 | 226 | 4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material. 227 | 228 | 5. __Downstream recipients.__ 229 | 230 | A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License. 231 | 232 | B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material. 233 | 234 | 6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i). 235 | 236 | b. ___Other rights.___ 237 | 238 | 1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise. 239 | 240 | 2. Patent and trademark rights are not licensed under this Public License. 241 | 242 | 3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes. 243 | 244 | ### Section 3 – License Conditions. 245 | 246 | Your exercise of the Licensed Rights is expressly made subject to the following conditions. 247 | 248 | a. ___Attribution.___ 249 | 250 | 1. If You Share the Licensed Material (including in modified form), You must: 251 | 252 | A. retain the following if it is supplied by the Licensor with the Licensed Material: 253 | 254 | i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated); 255 | 256 | ii. a copyright notice; 257 | 258 | iii. a notice that refers to this Public License; 259 | 260 | iv. a notice that refers to the disclaimer of warranties; 261 | 262 | v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable; 263 | 264 | B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and 265 | 266 | C. indicate the Licensed Material is licensed under this Public License, and include the text of, or the URI or hyperlink to, this Public License. 267 | 268 | 2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information. 269 | 270 | 3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable. 271 | 272 | 4. If You Share Adapted Material You produce, the Adapter's License You apply must not prevent recipients of the Adapted Material from complying with this Public License. 273 | 274 | ### Section 4 – Sui Generis Database Rights. 275 | 276 | Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material: 277 | 278 | a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only; 279 | 280 | b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and 281 | 282 | c. You must comply with the conditions in Section 3(a) if You Share all or a substantial portion of the contents of the database. 283 | 284 | For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights. 285 | 286 | ### Section 5 – Disclaimer of Warranties and Limitation of Liability. 287 | 288 | a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__ 289 | 290 | b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__ 291 | 292 | c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability. 293 | 294 | ### Section 6 – Term and Termination. 295 | 296 | a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically. 297 | 298 | b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates: 299 | 300 | 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or 301 | 302 | 2. upon express reinstatement by the Licensor. 303 | 304 | For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License. 305 | 306 | c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License. 307 | 308 | d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License. 309 | 310 | ### Section 7 – Other Terms and Conditions. 311 | 312 | a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed. 313 | 314 | b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License. 315 | 316 | ### Section 8 – Interpretation. 317 | 318 | a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License. 319 | 320 | b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions. 321 | 322 | c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor. 323 | 324 | d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority. 325 | 326 | > Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” Except for the limited purpose of indicating that material is shared under a Creative Commons public license or as otherwise permitted by the Creative Commons policies published at [creativecommons.org/policies](http://creativecommons.org/policies), Creative Commons does not authorize the use of the trademark “Creative Commons” or any other trademark or logo of Creative Commons without its prior written consent including, without limitation, in connection with any unauthorized modifications to any of its public licenses or any other arrangements, understandings, or agreements concerning use of licensed material. For the avoidance of doubt, this paragraph does not form part of the public licenses. 327 | > 328 | > Creative Commons may be contacted at creativecommons.org 329 | 330 | ===== 331 | 332 | yucornetto/MGMatting 333 | https://github.com/yucornetto/MGMatting 334 | 335 | 336 | The project can only be redistributed under a Creative Commons Attribution-NonCommercial 2.0 Generic (CC BY-NC 2.0) license; the terms of which are available at https://creativecommons.org/licenses/by-nc/2.0/deed.en_GB. 337 | 338 | This software is for non-commercial purposes only. 339 | 340 | Copyright (c) 2020 Qihang Yu All rights reserved. 341 | 342 | Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 343 | 344 | Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 345 | 346 | Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 347 | 348 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 349 | 350 | ===== 351 | 352 | SwinTransformer/Swin-Transformer-Semantic-Segmentation 353 | https://github.com/SwinTransformer/Swin-Transformer-Semantic-Segmentation 354 | 355 | 356 | Copyright 2020 The MMSegmentation Authors. 357 | 358 | Licensed under the Apache License, Version 2.0 (the "License"); 359 | you may not use this file except in compliance with the License. 360 | You may obtain a copy of the License at 361 | 362 | http://www.apache.org/licenses/LICENSE-2.0 363 | 364 | Unless required by applicable law or agreed to in writing, software 365 | distributed under the License is distributed on an "AS IS" BASIS, 366 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 367 | See the License for the specific language governing permissions and 368 | limitations under the License. 369 | 370 | 371 | ====================================================================================== 372 | Swin-Transformer-Semantic-Segmentation Subcomponents: 373 | 374 | The Swin-Transformer-Semantic-Segmentation project contains subcomponents with separate 375 | copyright notices and license terms. Your use of the source code for the these 376 | subcomponents is subject to the terms and conditions of the following licenses. 377 | 378 | ======================================================================================= 379 | MIT license 380 | ======================================================================================= 381 | 382 | The following components are provided under an MIT license. 383 | 384 | 1. swin_transformer.py - For details, mmseg/models/backbones/swin_transformer.py 385 | Copyright (c) 2021 Microsoft 386 | 387 | ===== 388 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # MatteFormer 2 | 3 | --- 4 | 5 | This repository includes the official project of MatteFormer, presented in our paper: 6 | [MatteFormer: Transformer-Based Image Matting via Prior-Tokens](https://arxiv.org/abs/2203.15662) [CVPR 22] 7 | 8 | ![Exp](assets/exp2.png) 9 | 10 | In this paper, we propose a transformer-based image matting model called MatteFormer, which takes full advantage of trimap information in the transformer block. Our method first introduces a prior-token which is a global representation of each trimap region (e.g. foreground, background and unknown). These prior-tokens are used as global priors and participate in the self-attention mechanism of each block. Each stage of the encoder is composed of PAST (Prior-Attentive Swin Transformer) block, which is based on the Swin Transformer block, but differs in a couple of aspects: 1) It has PA-WSA (Prior-Attentive Window Self-Attention) layer, performing self-attention not only with spatial-tokens but also with prior-tokens. 2) It has prior-memory which saves prior-tokens accumulatively from the previous blocks and transfers them to the next block. We evaluate our MatteFormer on the commonly used image matting datasets: Composition-1k and Distinctions-646. Experiment results show that our proposed method achieves state-of-the-art performance with a large margin. 11 | 12 | --- 13 | 14 | ### Requirements 15 | The codes are tested in the following environment: 16 | - python 3.8 17 | - pytorch 1.10.1 18 | - CUDA 10.2 & CuDNN 8 19 | 20 | ### Performances 21 | | Models | SAD | MSE (x10^(-3) | Grad | Conn | Link | 22 | |:---:|:---:|:---:|:---:|:---:|:---:| 23 | MatteFormer | 23.80 | 4.03 | 8.68 | 18.90 | [model](https://drive.google.com/file/d/1AU7uM1dtYjEhtOa_9OGfoQUE-tmW9mX5/view?usp=sharing) | 24 | 25 | --- 26 | 27 | ### Data Preparation 28 | 1] Get DIM dataset on [Deep Image Matting](https://sites.google.com/view/deepimagematting). 29 | 30 | 2] For DIM dataset preparation, please refer to [GCA-Matting](https://github.com/Yaoyi-Li/GCA-Matting). 31 | - For Training, merge 'Adobe-licensed images' and 'Other' folder to use all 431 foregrounds and alphas 32 | - For Testing, use 'Composition_code.py' and 'copy_testing_alpha.sh' in GCA-Matting. 33 | 34 | 3] For background images, Download dataset on [PASCAL](http://host.robots.ox.ac.uk/pascal/VOC/) and [COCO](https://cocodataset.org/#home). 35 | 36 | ***If you want to download prepared test set directly : [download link](https://drive.google.com/file/d/1fS-uh2Fi0APygd0NPjqfT7jCwUu_a_Xu/view?usp=sharing)** 37 | 38 | ### Testing on Composition-1k dataset 39 | ``` 40 | pip3 install -r requirements.txt 41 | ``` 42 | 43 | 1] Run inference code (the predicted alpha will be save to **./predDIM/pred_alpha** by default) 44 | 45 | ``` 46 | python3 infer.py 47 | ``` 48 | 49 | 2] Evaluate the results by the official evaluation MATLAB code **./DIM_evaluation_code/evaluate.m** (provided by [Deep Image Matting](https://sites.google.com/view/deepimagematting)) 50 | 51 | 3] You can also check out the evaluation result simplicity with the python code (un-official) 52 | ``` 53 | python3 evaluate.py 54 | ``` 55 | 56 | ### Training on Composition-1k dataset 57 | 1] You can get (imagenet pretrained) swin-transformer tiny model (**'swin_tiny_patch4_window7_224.pth'**) on [Swin Transformer](https://github.com/microsoft/Swin-Transformer). 58 | 59 | 2] modify "config/MatteFormer_Composition1k.toml" 60 | 61 | 3] run main.py 62 | ``` 63 | CUDA_VISIBLE_DEVICES=0,1 python3 -m torch.distributed.launch --nproc_per_node=2 main.py 64 | ``` 65 | 66 | --- 67 | 68 | ### Citation 69 | If you find this work or code useful for your research, please use the following BibTex entry: 70 | ``` 71 | @article{park2022matteformer, 72 | title={MatteFormer: Transformer-Based Image Matting via Prior-Tokens}, 73 | author={Park, GyuTae and Son, SungJoon and Yoo, JaeYoung and Kim, SeHo and Kwak, Nojun}, 74 | journal={arXiv preprint arXiv:2203.15662}, 75 | year={2022} 76 | } 77 | ``` 78 | 79 | 80 | ### Acknowledgment 81 | - Our Codes are mainly originated from [MG-Matting](https://github.com/yucornetto/MGMatting) 82 | - Also, we build our codes with reference as [GCA-Matting](https://github.com/Yaoyi-Li/GCA-Matting) and [Swin Transformer for Semantic Segmentation](https://github.com/SwinTransformer/Swin-Transformer-Semantic-Segmentation) 83 | 84 | 85 | ### License 86 | MatteFormer is licensed under Apache-2.0, except utils/logger.py which is adopted from https://github.com/JiahuiYu/generative_inpainting under CC BY-NC 4.0. 87 | See [LICENSE](/LICENSE) for the full license text. 88 | 89 | ``` 90 | MatteFormer 91 | 92 | Copyright 2022-present NAVER WEBTOON 93 | 94 | Licensed under the Apache License, Version 2.0 (the "License"); 95 | you may not use this file except in compliance with the License. 96 | You may obtain a copy of the License at 97 | 98 | http://www.apache.org/licenses/LICENSE-2.0 99 | 100 | Unless required by applicable law or agreed to in writing, software 101 | distributed under the License is distributed on an "AS IS" BASIS, 102 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 103 | See the License for the specific language governing permissions and 104 | limitations under the License. 105 | 106 | ``` 107 | 108 | 109 | ![webtoonai](assets/webtoonai.png) 110 | -------------------------------------------------------------------------------- /assets/exp2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/webtoon/matteformer/f09f090a7e8069f213ea2671c49c52516f755bb5/assets/exp2.png -------------------------------------------------------------------------------- /assets/overview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/webtoon/matteformer/f09f090a7e8069f213ea2671c49c52516f755bb5/assets/overview.png -------------------------------------------------------------------------------- /assets/prior-token.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/webtoon/matteformer/f09f090a7e8069f213ea2671c49c52516f755bb5/assets/prior-token.png -------------------------------------------------------------------------------- /assets/test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/webtoon/matteformer/f09f090a7e8069f213ea2671c49c52516f755bb5/assets/test.png -------------------------------------------------------------------------------- /assets/webtoonai.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/webtoon/matteformer/f09f090a7e8069f213ea2671c49c52516f755bb5/assets/webtoonai.png -------------------------------------------------------------------------------- /config/MatteFormer_Composition1k.toml: -------------------------------------------------------------------------------- 1 | version = "MatteFormer-Composition1k" 2 | dist = true 3 | 4 | [model] 5 | trimap_channel = 3 6 | mask_channel = 1 7 | batch_size = 10 8 | imagenet_pretrain = true 9 | imagenet_pretrain_path = "pretrained/swin_tiny_patch4_window7_224.pth" 10 | self_refine_width1 = 30 11 | self_refine_width2 = 15 12 | 13 | [train] 14 | total_step = 200000 15 | warmup_step = 10000 16 | 17 | val_step = 5000 18 | 19 | clip_grad = true 20 | G_lr = 1e-3 21 | rec_weight = 1.0 22 | comp_weight = 1.0 23 | lap_weight = 1.0 24 | 25 | 26 | [data] 27 | train_fg = "/PATH/Adobe_Deep_Matting_Dataset/Combined_Dataset/Training_set/Adobe-licensed images/fg" 28 | train_alpha = "/PATH/Adobe_Deep_Matting_Dataset/Combined_Dataset/Training_set/Adobe-licensed images/alpha" 29 | train_bg = "/PATH/COCO/train2014" 30 | 31 | test_merged = "/PATH/Adobe_Deep_Matting_Dataset/Combined_Dataset/Test_set/Adobe-licensed images/merged" 32 | test_alpha = "/PATH/Adobe_Deep_Matting_Dataset/Combined_Dataset/Test_set/Adobe-licensed images/alpha_copy" 33 | test_trimap = "/PATH/Adobe_Deep_Matting_Dataset/Combined_Dataset/Test_set/Adobe-licensed images/trimaps" 34 | 35 | workers = 4 36 | 37 | crop_size = 512 38 | 39 | cutmask_prob = 0.25 40 | augmentation = true 41 | random_interp = true 42 | real_world_aug = false 43 | 44 | [log] 45 | experiment_root = "experiments" 46 | 47 | logging_path = "logs/stdout" 48 | logging_step = 10 49 | logging_level = "INFO" 50 | 51 | checkpoint_path = "checkpoints" 52 | checkpoint_step = 5000 -------------------------------------------------------------------------------- /dataloader/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/webtoon/matteformer/f09f090a7e8069f213ea2671c49c52516f755bb5/dataloader/__init__.py -------------------------------------------------------------------------------- /dataloader/data_generator.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | import os 3 | import math 4 | import numbers 5 | import random 6 | import logging 7 | import numpy as np 8 | 9 | import torch 10 | from torch.utils.data import Dataset 11 | from torch.nn import functional as F 12 | from torchvision import transforms 13 | 14 | from utils import CONFIG 15 | 16 | interp_list = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_LANCZOS4] 17 | 18 | 19 | def maybe_random_interp(cv2_interp): 20 | if CONFIG.data.random_interp: 21 | return np.random.choice(interp_list) 22 | else: 23 | return cv2_interp 24 | 25 | 26 | class ToTensor(object): 27 | """ 28 | Convert ndarrays in sample to Tensors with normalization. 29 | """ 30 | def __init__(self, phase="test"): 31 | self.mean = torch.tensor([0.485, 0.456, 0.406]).view(3,1,1) 32 | self.std = torch.tensor([0.229, 0.224, 0.225]).view(3,1,1) 33 | self.phase = phase 34 | 35 | def __call__(self, sample): 36 | # convert GBR images to RGB 37 | image, alpha, trimap, mask = sample['image'][:,:,::-1], sample['alpha'], sample['trimap'], sample['mask'] 38 | 39 | alpha[alpha < 0 ] = 0 40 | alpha[alpha > 1] = 1 41 | 42 | # swap color axis because 43 | # numpy image: H x W x C 44 | # torch image: C X H X W 45 | image = image.transpose((2, 0, 1)).astype(np.float32) 46 | alpha = np.expand_dims(alpha.astype(np.float32), axis=0) 47 | trimap[trimap < 85] = 0 48 | trimap[trimap >= 170] = 2 49 | trimap[trimap >= 85] = 1 50 | 51 | mask = np.expand_dims(mask.astype(np.float32), axis=0) 52 | 53 | # normalize image 54 | image /= 255. 55 | 56 | if self.phase == "train": 57 | # convert GBR images to RGB 58 | fg = sample['fg'][:,:,::-1].transpose((2, 0, 1)).astype(np.float32) / 255. 59 | sample['fg'] = torch.from_numpy(fg).sub_(self.mean).div_(self.std) 60 | bg = sample['bg'][:,:,::-1].transpose((2, 0, 1)).astype(np.float32) / 255. 61 | sample['bg'] = torch.from_numpy(bg).sub_(self.mean).div_(self.std) 62 | # del sample['image_name'] 63 | 64 | sample['image'], sample['alpha'], sample['trimap'] = \ 65 | torch.from_numpy(image), torch.from_numpy(alpha), torch.from_numpy(trimap).to(torch.long) 66 | sample['image'] = sample['image'].sub_(self.mean).div_(self.std) 67 | 68 | if CONFIG.model.trimap_channel == 3: 69 | sample['trimap'] = F.one_hot(sample['trimap'], num_classes=3).permute(2,0,1).float() 70 | elif CONFIG.model.trimap_channel == 1: 71 | sample['trimap'] = sample['trimap'][None,...].float() 72 | else: 73 | raise NotImplementedError("CONFIG.model.trimap_channel can only be 3 or 1") 74 | 75 | sample['mask'] = torch.from_numpy(mask).float() 76 | 77 | return sample 78 | 79 | 80 | class RandomAffine(object): 81 | """ 82 | Random affine translation 83 | """ 84 | def __init__(self, degrees, translate=None, scale=None, shear=None, flip=None, resample=False, fillcolor=0): 85 | if isinstance(degrees, numbers.Number): 86 | if degrees < 0: 87 | raise ValueError("If degrees is a single number, it must be positive.") 88 | self.degrees = (-degrees, degrees) 89 | else: 90 | assert isinstance(degrees, (tuple, list)) and len(degrees) == 2, \ 91 | "degrees should be a list or tuple and it must be of length 2." 92 | self.degrees = degrees 93 | 94 | if translate is not None: 95 | assert isinstance(translate, (tuple, list)) and len(translate) == 2, \ 96 | "translate should be a list or tuple and it must be of length 2." 97 | for t in translate: 98 | if not (0.0 <= t <= 1.0): 99 | raise ValueError("translation values should be between 0 and 1") 100 | self.translate = translate 101 | 102 | if scale is not None: 103 | assert isinstance(scale, (tuple, list)) and len(scale) == 2, \ 104 | "scale should be a list or tuple and it must be of length 2." 105 | for s in scale: 106 | if s <= 0: 107 | raise ValueError("scale values should be positive") 108 | self.scale = scale 109 | 110 | if shear is not None: 111 | if isinstance(shear, numbers.Number): 112 | if shear < 0: 113 | raise ValueError("If shear is a single number, it must be positive.") 114 | self.shear = (-shear, shear) 115 | else: 116 | assert isinstance(shear, (tuple, list)) and len(shear) == 2, \ 117 | "shear should be a list or tuple and it must be of length 2." 118 | self.shear = shear 119 | else: 120 | self.shear = shear 121 | 122 | self.resample = resample 123 | self.fillcolor = fillcolor 124 | self.flip = flip 125 | 126 | @staticmethod 127 | def get_params(degrees, translate, scale_ranges, shears, flip, img_size): 128 | """Get parameters for affine transformation 129 | 130 | Returns: 131 | sequence: params to be passed to the affine transformation 132 | """ 133 | angle = random.uniform(degrees[0], degrees[1]) 134 | if translate is not None: 135 | max_dx = translate[0] * img_size[0] 136 | max_dy = translate[1] * img_size[1] 137 | translations = (np.round(random.uniform(-max_dx, max_dx)), 138 | np.round(random.uniform(-max_dy, max_dy))) 139 | else: 140 | translations = (0, 0) 141 | 142 | if scale_ranges is not None: 143 | scale = (random.uniform(scale_ranges[0], scale_ranges[1]), 144 | random.uniform(scale_ranges[0], scale_ranges[1])) 145 | else: 146 | scale = (1.0, 1.0) 147 | 148 | if shears is not None: 149 | shear = random.uniform(shears[0], shears[1]) 150 | else: 151 | shear = 0.0 152 | 153 | if flip is not None: 154 | flip = (np.random.rand(2) < flip).astype(np.int) * 2 - 1 155 | 156 | return angle, translations, scale, shear, flip 157 | 158 | def __call__(self, sample): 159 | fg, alpha = sample['fg'], sample['alpha'] 160 | rows, cols, ch = fg.shape 161 | if np.maximum(rows, cols) < 1024: 162 | params = self.get_params((0, 0), self.translate, self.scale, self.shear, self.flip, fg.size) 163 | else: 164 | params = self.get_params(self.degrees, self.translate, self.scale, self.shear, self.flip, fg.size) 165 | 166 | center = (cols * 0.5 + 0.5, rows * 0.5 + 0.5) 167 | M = self._get_inverse_affine_matrix(center, *params) 168 | M = np.array(M).reshape((2, 3)) 169 | 170 | fg = cv2.warpAffine(fg, M, (cols, rows), 171 | flags=maybe_random_interp(cv2.INTER_NEAREST) + cv2.WARP_INVERSE_MAP) 172 | alpha = cv2.warpAffine(alpha, M, (cols, rows), 173 | flags=maybe_random_interp(cv2.INTER_NEAREST) + cv2.WARP_INVERSE_MAP) 174 | 175 | sample['fg'], sample['alpha'] = fg, alpha 176 | 177 | return sample 178 | 179 | 180 | @ staticmethod 181 | def _get_inverse_affine_matrix(center, angle, translate, scale, shear, flip): 182 | # Helper method to compute inverse matrix for affine transformation 183 | 184 | # As it is explained in PIL.Image.rotate 185 | # We need compute INVERSE of affine transformation matrix: M = T * C * RSS * C^-1 186 | # where T is translation matrix: [1, 0, tx | 0, 1, ty | 0, 0, 1] 187 | # C is translation matrix to keep center: [1, 0, cx | 0, 1, cy | 0, 0, 1] 188 | # RSS is rotation with scale and shear matrix 189 | # It is different from the original function in torchvision 190 | # The order are changed to flip -> scale -> rotation -> shear 191 | # x and y have different scale factors 192 | # RSS(shear, a, scale, f) = [ cos(a + shear)*scale_x*f -sin(a + shear)*scale_y 0] 193 | # [ sin(a)*scale_x*f cos(a)*scale_y 0] 194 | # [ 0 0 1] 195 | # Thus, the inverse is M^-1 = C * RSS^-1 * C^-1 * T^-1 196 | 197 | angle = math.radians(angle) 198 | shear = math.radians(shear) 199 | scale_x = 1.0 / scale[0] * flip[0] 200 | scale_y = 1.0 / scale[1] * flip[1] 201 | 202 | # Inverted rotation matrix with scale and shear 203 | d = math.cos(angle + shear) * math.cos(angle) + math.sin(angle + shear) * math.sin(angle) 204 | matrix = [ 205 | math.cos(angle) * scale_x, math.sin(angle + shear) * scale_x, 0, 206 | -math.sin(angle) * scale_y, math.cos(angle + shear) * scale_y, 0 207 | ] 208 | matrix = [m / d for m in matrix] 209 | 210 | # Apply inverse of translation and of center translation: RSS^-1 * C^-1 * T^-1 211 | matrix[2] += matrix[0] * (-center[0] - translate[0]) + matrix[1] * (-center[1] - translate[1]) 212 | matrix[5] += matrix[3] * (-center[0] - translate[0]) + matrix[4] * (-center[1] - translate[1]) 213 | 214 | # Apply center translation: C * RSS^-1 * C^-1 * T^-1 215 | matrix[2] += center[0] 216 | matrix[5] += center[1] 217 | 218 | return matrix 219 | 220 | 221 | class RandomJitter(object): 222 | """ 223 | Random change the hue of the image 224 | """ 225 | 226 | def __call__(self, sample): 227 | sample_ori = sample.copy() 228 | fg, alpha = sample['fg'], sample['alpha'] 229 | # if alpha is all 0 skip 230 | if np.all(alpha==0): 231 | return sample_ori 232 | # convert to HSV space, convert to float32 image to keep precision during space conversion. 233 | fg = cv2.cvtColor(fg.astype(np.float32)/255.0, cv2.COLOR_BGR2HSV) 234 | # Hue noise 235 | hue_jitter = np.random.randint(-40, 40) 236 | fg[:, :, 0] = np.remainder(fg[:, :, 0].astype(np.float32) + hue_jitter, 360) 237 | # Saturation noise 238 | sat_bar = fg[:, :, 1][alpha > 0].mean() 239 | if np.isnan(sat_bar): 240 | return sample_ori 241 | sat_jitter = np.random.rand()*(1.1 - sat_bar)/5 - (1.1 - sat_bar) / 10 242 | sat = fg[:, :, 1] 243 | sat = np.abs(sat + sat_jitter) 244 | sat[sat>1] = 2 - sat[sat>1] 245 | fg[:, :, 1] = sat 246 | # Value noise 247 | val_bar = fg[:, :, 2][alpha > 0].mean() 248 | if np.isnan(val_bar): 249 | return sample_ori 250 | val_jitter = np.random.rand()*(1.1 - val_bar)/5-(1.1 - val_bar) / 10 251 | val = fg[:, :, 2] 252 | val = np.abs(val + val_jitter) 253 | val[val>1] = 2 - val[val>1] 254 | fg[:, :, 2] = val 255 | # convert back to BGR space 256 | fg = cv2.cvtColor(fg, cv2.COLOR_HSV2BGR) 257 | sample['fg'] = fg*255 258 | 259 | return sample 260 | 261 | 262 | class RandomHorizontalFlip(object): 263 | """ 264 | Random flip image and label horizontally 265 | """ 266 | def __init__(self, prob=0.5): 267 | self.prob = prob 268 | def __call__(self, sample): 269 | fg, alpha = sample['fg'], sample['alpha'] 270 | if np.random.uniform(0, 1) < self.prob: 271 | fg = cv2.flip(fg, 1) 272 | alpha = cv2.flip(alpha, 1) 273 | sample['fg'], sample['alpha'] = fg, alpha 274 | 275 | return sample 276 | 277 | 278 | class RandomCrop(object): 279 | """ 280 | Crop randomly the image in a sample, retain the center 1/4 images, and resize to 'output_size' 281 | 282 | :param output_size (tuple or int): Desired output size. If int, square crop 283 | is made. 284 | """ 285 | 286 | def __init__(self, output_size=( CONFIG.data.crop_size, CONFIG.data.crop_size)): 287 | assert isinstance(output_size, (int, tuple)) 288 | if isinstance(output_size, int): 289 | self.output_size = (output_size, output_size) 290 | else: 291 | assert len(output_size) == 2 292 | self.output_size = output_size 293 | self.margin = output_size[0] // 2 294 | self.logger = logging.getLogger("Logger") 295 | 296 | def __call__(self, sample): 297 | fg, alpha, trimap, mask, name = sample['fg'], sample['alpha'], sample['trimap'], sample['mask'], sample['image_name'] 298 | bg = sample['bg'] 299 | h, w = trimap.shape 300 | bg = cv2.resize(bg, (w, h), interpolation=maybe_random_interp(cv2.INTER_CUBIC)) 301 | if w < self.output_size[0]+1 or h < self.output_size[1]+1: 302 | ratio = 1.1*self.output_size[0]/h if h < w else 1.1*self.output_size[1]/w 303 | # self.logger.warning("Size of {} is {}.".format(name, (h, w))) 304 | while h < self.output_size[0]+1 or w < self.output_size[1]+1: 305 | fg = cv2.resize(fg, (int(w*ratio), int(h*ratio)), interpolation=maybe_random_interp(cv2.INTER_NEAREST)) 306 | alpha = cv2.resize(alpha, (int(w*ratio), int(h*ratio)), 307 | interpolation=maybe_random_interp(cv2.INTER_NEAREST)) 308 | trimap = cv2.resize(trimap, (int(w*ratio), int(h*ratio)), interpolation=cv2.INTER_NEAREST) 309 | bg = cv2.resize(bg, (int(w*ratio), int(h*ratio)), interpolation=maybe_random_interp(cv2.INTER_CUBIC)) 310 | mask = cv2.resize(mask, (int(w*ratio), int(h*ratio)), interpolation=cv2.INTER_NEAREST) 311 | h, w = trimap.shape 312 | small_trimap = cv2.resize(trimap, (w//4, h//4), interpolation=cv2.INTER_NEAREST) 313 | unknown_list = list(zip(*np.where(small_trimap[self.margin//4:(h-self.margin)//4, 314 | self.margin//4:(w-self.margin)//4] == 128))) 315 | unknown_num = len(unknown_list) 316 | if len(unknown_list) < 10: 317 | left_top = (np.random.randint(0, h-self.output_size[0]+1), np.random.randint(0, w-self.output_size[1]+1)) 318 | else: 319 | idx = np.random.randint(unknown_num) 320 | left_top = (unknown_list[idx][0]*4, unknown_list[idx][1]*4) 321 | 322 | fg_crop = fg[left_top[0]:left_top[0]+self.output_size[0], left_top[1]:left_top[1]+self.output_size[1],:] 323 | alpha_crop = alpha[left_top[0]:left_top[0]+self.output_size[0], left_top[1]:left_top[1]+self.output_size[1]] 324 | bg_crop = bg[left_top[0]:left_top[0]+self.output_size[0], left_top[1]:left_top[1]+self.output_size[1],:] 325 | trimap_crop = trimap[left_top[0]:left_top[0]+self.output_size[0], left_top[1]:left_top[1]+self.output_size[1]] 326 | mask_crop = mask[left_top[0]:left_top[0]+self.output_size[0], left_top[1]:left_top[1]+self.output_size[1]] 327 | 328 | if len(np.where(trimap==128)[0]) == 0: 329 | self.logger.error("{} does not have enough unknown area for crop. Resized to target size." 330 | "left_top: {}".format(name, left_top)) 331 | fg_crop = cv2.resize(fg, self.output_size[::-1], interpolation=maybe_random_interp(cv2.INTER_NEAREST)) 332 | alpha_crop = cv2.resize(alpha, self.output_size[::-1], interpolation=maybe_random_interp(cv2.INTER_NEAREST)) 333 | trimap_crop = cv2.resize(trimap, self.output_size[::-1], interpolation=cv2.INTER_NEAREST) 334 | bg_crop = cv2.resize(bg, self.output_size[::-1], interpolation=maybe_random_interp(cv2.INTER_CUBIC)) 335 | mask_crop = cv2.resize(mask, self.output_size[::-1], interpolation=cv2.INTER_NEAREST) 336 | 337 | sample.update({'fg': fg_crop, 'alpha': alpha_crop, 'trimap': trimap_crop, 'mask': mask_crop, 'bg': bg_crop}) 338 | return sample 339 | 340 | 341 | class OriginScale(object): 342 | def __call__(self, sample): 343 | h, w = sample["alpha_shape"] 344 | 345 | if h % 32 == 0 and w % 32 == 0: 346 | return sample 347 | 348 | target_h = 32 * ((h - 1) // 32 + 1) 349 | target_w = 32 * ((w - 1) // 32 + 1) 350 | pad_h = target_h - h 351 | pad_w = target_w - w 352 | 353 | padded_image = np.pad(sample['image'], ((0,pad_h), (0, pad_w), (0,0)), mode="reflect") 354 | padded_trimap = np.pad(sample['trimap'], ((0,pad_h), (0, pad_w)), mode="reflect") 355 | padded_mask = np.pad(sample['mask'], ((0,pad_h), (0, pad_w)), mode="reflect") 356 | 357 | sample['image'] = padded_image 358 | sample['trimap'] = padded_trimap 359 | sample['mask'] = padded_mask 360 | 361 | return sample 362 | 363 | 364 | class GenMask(object): 365 | def __init__(self): 366 | self.erosion_kernels = [None] + [cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (size, size)) for size in range(1,30)] 367 | 368 | def __call__(self, sample): 369 | alpha_ori = sample['alpha'] 370 | h, w = alpha_ori.shape 371 | 372 | max_kernel_size = 30 373 | alpha = cv2.resize(alpha_ori, (640,640), interpolation=maybe_random_interp(cv2.INTER_NEAREST)) 374 | 375 | ### generate trimap 376 | fg_mask = (alpha + 1e-5).astype(np.int).astype(np.uint8) 377 | bg_mask = (1 - alpha + 1e-5).astype(np.int).astype(np.uint8) 378 | fg_mask = cv2.erode(fg_mask, self.erosion_kernels[np.random.randint(1, max_kernel_size)]) 379 | bg_mask = cv2.erode(bg_mask, self.erosion_kernels[np.random.randint(1, max_kernel_size)]) 380 | 381 | fg_width = np.random.randint(1, 30) 382 | bg_width = np.random.randint(1, 30) 383 | fg_mask = (alpha + 1e-5).astype(np.int).astype(np.uint8) 384 | bg_mask = (1 - alpha + 1e-5).astype(np.int).astype(np.uint8) 385 | fg_mask = cv2.erode(fg_mask, self.erosion_kernels[fg_width]) 386 | bg_mask = cv2.erode(bg_mask, self.erosion_kernels[bg_width]) 387 | 388 | trimap = np.ones_like(alpha) * 128 389 | trimap[fg_mask == 1] = 255 390 | trimap[bg_mask == 1] = 0 391 | 392 | trimap = cv2.resize(trimap, (w,h), interpolation=cv2.INTER_NEAREST) 393 | sample['trimap'] = trimap 394 | 395 | ### generate mask 396 | low = 0.01 397 | high = 1.0 398 | thres = random.random() * (high - low) + low 399 | seg_mask = (alpha >= thres).astype(np.int).astype(np.uint8) 400 | random_num = random.randint(0,3) 401 | if random_num == 0: 402 | seg_mask = cv2.erode(seg_mask, self.erosion_kernels[np.random.randint(1, max_kernel_size)]) 403 | elif random_num == 1: 404 | seg_mask = cv2.dilate(seg_mask, self.erosion_kernels[np.random.randint(1, max_kernel_size)]) 405 | elif random_num == 2: 406 | seg_mask = cv2.erode(seg_mask, self.erosion_kernels[np.random.randint(1, max_kernel_size)]) 407 | seg_mask = cv2.dilate(seg_mask, self.erosion_kernels[np.random.randint(1, max_kernel_size)]) 408 | elif random_num == 3: 409 | seg_mask = cv2.dilate(seg_mask, self.erosion_kernels[np.random.randint(1, max_kernel_size)]) 410 | seg_mask = cv2.erode(seg_mask, self.erosion_kernels[np.random.randint(1, max_kernel_size)]) 411 | 412 | seg_mask = cv2.resize(seg_mask, (w,h), interpolation=cv2.INTER_NEAREST) 413 | sample['mask'] = seg_mask 414 | 415 | return sample 416 | 417 | 418 | class Composite(object): 419 | def __call__(self, sample): 420 | fg, bg, alpha = sample['fg'], sample['bg'], sample['alpha'] 421 | alpha[alpha < 0 ] = 0 422 | alpha[alpha > 1] = 1 423 | fg[fg < 0 ] = 0 424 | fg[fg > 255] = 255 425 | bg[bg < 0 ] = 0 426 | bg[bg > 255] = 255 427 | 428 | image = fg * alpha[:, :, None] + bg * (1 - alpha[:, :, None]) 429 | sample['image'] = image 430 | return sample 431 | 432 | 433 | class CutMask(object): 434 | def __init__(self, perturb_prob = 0): 435 | self.perturb_prob = perturb_prob 436 | 437 | def __call__(self, sample): 438 | if np.random.rand() < self.perturb_prob: 439 | return sample 440 | 441 | mask = sample['mask'] # H x W, trimap 0--255, segmask 0--1, alpha 0--1 442 | h, w = mask.shape 443 | perturb_size_h, perturb_size_w = random.randint(h // 4, h // 2), random.randint(w // 4, w // 2) 444 | x = random.randint(0, h - perturb_size_h) 445 | y = random.randint(0, w - perturb_size_w) 446 | x1 = random.randint(0, h - perturb_size_h) 447 | y1 = random.randint(0, w - perturb_size_w) 448 | 449 | mask[x:x+perturb_size_h, y:y+perturb_size_w] = mask[x1:x1+perturb_size_h, y1:y1+perturb_size_w].copy() 450 | 451 | sample['mask'] = mask 452 | return sample 453 | 454 | 455 | class DataGenerator(Dataset): 456 | def __init__(self, data, phase="train"): 457 | self.phase = phase 458 | self.crop_size = CONFIG.data.crop_size 459 | self.alpha = data.alpha 460 | 461 | if self.phase == "train": 462 | self.fg = data.fg 463 | self.bg = data.bg 464 | self.merged = [] 465 | self.trimap = [] 466 | 467 | else: 468 | self.fg = [] 469 | self.bg = [] 470 | self.merged = data.merged 471 | self.trimap = data.trimap 472 | 473 | train_trans = [ 474 | RandomAffine(degrees=30, scale=[0.8, 1.25], shear=10, flip=0.5), 475 | GenMask(), 476 | CutMask(perturb_prob=CONFIG.data.cutmask_prob), 477 | RandomCrop((self.crop_size, self.crop_size)), 478 | RandomJitter(), 479 | Composite(), 480 | ToTensor(phase="train") ] 481 | 482 | test_trans = [ OriginScale(), ToTensor() ] 483 | 484 | self.transform = { 485 | 'train': 486 | transforms.Compose(train_trans), 487 | 'val': 488 | transforms.Compose([ 489 | OriginScale(), 490 | ToTensor() 491 | ]), 492 | 'test': 493 | transforms.Compose(test_trans) 494 | }[phase] 495 | 496 | self.fg_num = len(self.fg) 497 | 498 | def __getitem__(self, idx): 499 | if self.phase == "train": 500 | fg = cv2.imread(self.fg[idx % self.fg_num]) 501 | alpha = cv2.imread(self.alpha[idx % self.fg_num], 0).astype(np.float32)/255 502 | bg = cv2.imread(self.bg[idx], 1) 503 | 504 | fg, alpha = self._composite_fg(fg, alpha, idx) 505 | 506 | image_name = os.path.split(self.fg[idx % self.fg_num])[-1] 507 | sample = {'fg': fg, 'alpha': alpha, 'bg': bg, 'image_name': image_name} 508 | 509 | else: 510 | image = cv2.imread(self.merged[idx]) 511 | alpha = cv2.imread(self.alpha[idx], 0)/255. 512 | trimap = cv2.imread(self.trimap[idx], 0) 513 | mask = (trimap >= 170).astype(np.float32) 514 | image_name = os.path.split(self.merged[idx])[-1] 515 | 516 | sample = {'image': image, 'alpha': alpha, 'trimap': trimap, 'mask': mask, 'image_name': image_name, 'alpha_shape': alpha.shape} 517 | 518 | sample = self.transform(sample) 519 | 520 | return sample 521 | 522 | def _composite_fg(self, fg, alpha, idx): 523 | 524 | if np.random.rand() < 0.5: 525 | idx2 = np.random.randint(self.fg_num) + idx 526 | fg2 = cv2.imread(self.fg[idx2 % self.fg_num]) 527 | alpha2 = cv2.imread(self.alpha[idx2 % self.fg_num], 0).astype(np.float32)/255. 528 | h, w = alpha.shape 529 | fg2 = cv2.resize(fg2, (w, h), interpolation=maybe_random_interp(cv2.INTER_NEAREST)) 530 | alpha2 = cv2.resize(alpha2, (w, h), interpolation=maybe_random_interp(cv2.INTER_NEAREST)) 531 | 532 | alpha_tmp = 1 - (1 - alpha) * (1 - alpha2) 533 | if np.any(alpha_tmp < 1): 534 | fg = fg.astype(np.float32) * alpha[:,:,None] + fg2.astype(np.float32) * (1 - alpha[:,:,None]) 535 | # The overlap of two 50% transparency should be 25% 536 | alpha = alpha_tmp 537 | fg = fg.astype(np.uint8) 538 | 539 | if np.random.rand() < 0.25: 540 | fg = cv2.resize(fg, (640, 640), interpolation=maybe_random_interp(cv2.INTER_NEAREST)) 541 | alpha = cv2.resize(alpha, (640, 640), interpolation=maybe_random_interp(cv2.INTER_NEAREST)) 542 | 543 | return fg, alpha 544 | 545 | def __len__(self): 546 | if self.phase == "train": 547 | return len(self.bg) 548 | else: 549 | return len(self.alpha) -------------------------------------------------------------------------------- /dataloader/image_file.py: -------------------------------------------------------------------------------- 1 | import os 2 | import glob 3 | import logging 4 | import functools 5 | import numpy as np 6 | 7 | class ImageFile(object): 8 | def __init__(self, phase='train'): 9 | self.logger = logging.getLogger("Logger") 10 | self.phase = phase 11 | self.rng = np.random.RandomState(0) 12 | 13 | def _get_valid_names(self, *dirs, shuffle=True): 14 | # Extract valid names 15 | name_sets = [self._get_name_set(d) for d in dirs] 16 | 17 | # Reduce 18 | def _join_and(a, b): 19 | return a & b 20 | 21 | valid_names = list(functools.reduce(_join_and, name_sets)) 22 | if shuffle: 23 | self.rng.shuffle(valid_names) 24 | 25 | if len(valid_names) == 0: 26 | self.logger.error('No image valid') 27 | else: 28 | self.logger.info('{}: {} foreground/images are valid'.format(self.phase.upper(), len(valid_names))) 29 | 30 | return valid_names 31 | 32 | @staticmethod 33 | def _get_name_set(dir_name): 34 | path_list = glob.glob(os.path.join(dir_name, '*')) 35 | name_set = set() 36 | for path in path_list: 37 | name = os.path.basename(path) 38 | name = os.path.splitext(name)[0] 39 | name_set.add(name) 40 | return name_set 41 | 42 | @staticmethod 43 | def _list_abspath(data_dir, ext, data_list): 44 | return [os.path.join(data_dir, name + ext) 45 | for name in data_list] 46 | 47 | 48 | class ImageFileTrain(ImageFile): 49 | def __init__(self, 50 | alpha_dir="train_alpha", 51 | fg_dir="train_fg", 52 | bg_dir="train_bg", 53 | alpha_ext=".jpg", 54 | fg_ext=".jpg", 55 | bg_ext=".jpg"): 56 | super(ImageFileTrain, self).__init__(phase="train") 57 | 58 | self.alpha_dir = alpha_dir 59 | self.fg_dir = fg_dir 60 | self.bg_dir = bg_dir 61 | self.alpha_ext = alpha_ext 62 | self.fg_ext = fg_ext 63 | self.bg_ext = bg_ext 64 | 65 | self.logger.debug('Load Training Images From Folders') 66 | 67 | self.valid_fg_list = self._get_valid_names(self.fg_dir, self.alpha_dir) 68 | self.valid_bg_list = [os.path.splitext(name)[0] for name in os.listdir(self.bg_dir)] 69 | 70 | self.alpha = self._list_abspath(self.alpha_dir, self.alpha_ext, self.valid_fg_list) 71 | self.fg = self._list_abspath(self.fg_dir, self.fg_ext, self.valid_fg_list) 72 | self.bg = self._list_abspath(self.bg_dir, self.bg_ext, self.valid_bg_list) 73 | 74 | def __len__(self): 75 | return len(self.alpha) 76 | 77 | 78 | class ImageFileTest(ImageFile): 79 | def __init__(self, 80 | alpha_dir="test_alpha", 81 | merged_dir="test_merged", 82 | trimap_dir="test_trimap", 83 | alpha_ext=".png", 84 | merged_ext=".png", 85 | trimap_ext=".png"): 86 | super(ImageFileTest, self).__init__(phase="test") 87 | 88 | self.alpha_dir = alpha_dir 89 | self.merged_dir = merged_dir 90 | self.trimap_dir = trimap_dir 91 | self.alpha_ext = alpha_ext 92 | self.merged_ext = merged_ext 93 | self.trimap_ext = trimap_ext 94 | 95 | self.logger.debug('Load Testing Images From Folders') 96 | 97 | self.valid_image_list = self._get_valid_names(self.alpha_dir, self.merged_dir, self.trimap_dir, shuffle=False) 98 | 99 | self.alpha = self._list_abspath(self.alpha_dir, self.alpha_ext, self.valid_image_list) 100 | self.merged = self._list_abspath(self.merged_dir, self.merged_ext, self.valid_image_list) 101 | self.trimap = self._list_abspath(self.trimap_dir, self.trimap_ext, self.valid_image_list) 102 | 103 | def __len__(self): 104 | return len(self.alpha) 105 | 106 | -------------------------------------------------------------------------------- /dataloader/prefetcher.py: -------------------------------------------------------------------------------- 1 | import torch 2 | 3 | 4 | class Prefetcher(): 5 | """ 6 | Modified from the data_prefetcher in https://github.com/NVIDIA/apex/blob/master/examples/imagenet/main_amp.py 7 | """ 8 | def __init__(self, loader): 9 | self.orig_loader = loader 10 | self.stream = torch.cuda.Stream() 11 | self.next_sample = None 12 | 13 | def preload(self): 14 | try: 15 | self.next_sample = next(self.loader) 16 | except StopIteration: 17 | self.next_sample = None 18 | return 19 | 20 | with torch.cuda.stream(self.stream): 21 | for key, value in self.next_sample.items(): 22 | if isinstance(value, torch.Tensor): 23 | self.next_sample[key] = value.cuda(non_blocking=True) 24 | 25 | def __next__(self): 26 | torch.cuda.current_stream().wait_stream(self.stream) 27 | sample = self.next_sample 28 | if sample is not None: 29 | for key, value in sample.items(): 30 | if isinstance(value, torch.Tensor): 31 | sample[key].record_stream(torch.cuda.current_stream()) 32 | self.preload() 33 | else: 34 | # throw stop exception if there is no more data to perform as a default dataloader 35 | raise StopIteration("No samples in loader. example: `iterator = iter(Prefetcher(loader)); " 36 | "data = next(iterator)`") 37 | return sample 38 | 39 | def __iter__(self): 40 | self.loader = iter(self.orig_loader) 41 | self.preload() 42 | return self 43 | -------------------------------------------------------------------------------- /evaluation.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | import numpy as np 4 | from utils import compute_sad_loss, compute_mse_loss 5 | import argparse 6 | 7 | 8 | def evaluate(args): 9 | img_names = [] 10 | mse_loss_unknown = [] 11 | sad_loss_unknown = [] 12 | 13 | for i, img in enumerate(os.listdir(args.label_dir)): 14 | 15 | if not((os.path.isfile(os.path.join(args.pred_dir, img)) and 16 | os.path.isfile(os.path.join(args.label_dir, img)) and 17 | os.path.isfile(os.path.join(args.trimap_dir, img)))): 18 | print('[{}/{}] "{}" skipping'.format(i, len(os.listdir(args.label_dir)), img)) 19 | continue 20 | 21 | pred = cv2.imread(os.path.join(args.pred_dir, img), 0).astype(np.float32) 22 | label = cv2.imread(os.path.join(args.label_dir, img), 0).astype(np.float32) 23 | trimap = cv2.imread(os.path.join(args.trimap_dir, img), 0).astype(np.float32) 24 | 25 | # calculate loss 26 | mse_loss_unknown_ = compute_mse_loss(pred, label, trimap) 27 | sad_loss_unknown_ = compute_sad_loss(pred, label, trimap)[0] 28 | print('Unknown Region: MSE:', mse_loss_unknown_, ' SAD:', sad_loss_unknown_) 29 | 30 | # save for average 31 | img_names.append(img) 32 | 33 | mse_loss_unknown.append(mse_loss_unknown_) # mean l2 loss per unknown pixel 34 | sad_loss_unknown.append(sad_loss_unknown_) # l1 loss on unknown area 35 | 36 | print('[{}/{}] "{}" processed'.format(i, len(os.listdir(args.label_dir)), img)) 37 | 38 | print('* Unknown Region: MSE:', np.array(mse_loss_unknown).mean(), ' SAD:', np.array(sad_loss_unknown).mean()) 39 | print('* if you want to report scores in your paper, please use the official matlab codes for evaluation.') 40 | 41 | 42 | if __name__ == '__main__': 43 | parser = argparse.ArgumentParser() 44 | parser.add_argument('--pred-dir', type=str, default='predDIM/pred_alpha/', help="output dir") 45 | parser.add_argument('--label-dir', type=str, default='Composition-1k-testset/alpha_copy/', help="GT alpha dir") 46 | parser.add_argument('--trimap-dir', type=str, default='Composition-1k-testset/trimaps/', help="trimap dir") 47 | 48 | args = parser.parse_args() 49 | 50 | evaluate(args) -------------------------------------------------------------------------------- /inference.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | import toml 4 | import argparse 5 | import numpy as np 6 | 7 | import torch 8 | from torch.nn import functional as F 9 | 10 | import utils 11 | from utils import CONFIG 12 | import networks 13 | 14 | 15 | def single_inference(model, image_dict): 16 | 17 | with torch.no_grad(): 18 | image, trimap = image_dict['image'], image_dict['trimap'] 19 | 20 | image = image.cuda() 21 | trimap = trimap.cuda() 22 | 23 | # run model 24 | pred = model(image, trimap) 25 | alpha_pred_os1, alpha_pred_os4, alpha_pred_os8 = pred['alpha_os1'], pred['alpha_os4'], pred['alpha_os8'] 26 | 27 | # refinement 28 | alpha_pred = alpha_pred_os8.clone().detach() 29 | weight_os4 = utils.get_unknown_tensor_from_pred(alpha_pred, rand_width=CONFIG.model.self_refine_width1, train_mode=False) 30 | alpha_pred[weight_os4>0] = alpha_pred_os4[weight_os4>0] 31 | weight_os1 = utils.get_unknown_tensor_from_pred(alpha_pred, rand_width=CONFIG.model.self_refine_width2, train_mode=False) 32 | alpha_pred[weight_os1>0] = alpha_pred_os1[weight_os1>0] 33 | 34 | h, w = image_dict['alpha_shape'] 35 | alpha_pred = alpha_pred[0, 0, ...].data.cpu().numpy() * 255 36 | alpha_pred = alpha_pred.astype(np.uint8) 37 | 38 | alpha_pred[np.argmax(trimap.cpu().numpy()[0], axis=0) == 0] = 0.0 39 | alpha_pred[np.argmax(trimap.cpu().numpy()[0], axis=0) == 2] = 255. 40 | 41 | alpha_pred = alpha_pred[32:h+32, 32:w+32] 42 | 43 | return alpha_pred 44 | 45 | 46 | def generator_tensor_dict(image_path, trimap_path): 47 | # read images 48 | image = cv2.imread(image_path) 49 | trimap = cv2.imread(trimap_path, 0) 50 | 51 | sample = {'image': image, 'trimap':trimap, 'alpha_shape':(image.shape[0], image.shape[1])} 52 | 53 | # reshape 54 | h, w = sample["alpha_shape"] 55 | 56 | if h % 32 == 0 and w % 32 == 0: 57 | padded_image = np.pad(sample['image'], ((32,32), (32, 32), (0,0)), mode="reflect") 58 | padded_trimap = np.pad(sample['trimap'], ((32,32), (32, 32)), mode="reflect") 59 | 60 | sample['image'] = padded_image 61 | sample['trimap'] = padded_trimap 62 | 63 | else: 64 | target_h = 32 * ((h - 1) // 32 + 1) 65 | target_w = 32 * ((w - 1) // 32 + 1) 66 | pad_h = target_h - h 67 | pad_w = target_w - w 68 | padded_image = np.pad(sample['image'], ((32,pad_h+32), (32, pad_w+32), (0,0)), mode="reflect") 69 | padded_trimap = np.pad(sample['trimap'], ((32,pad_h+32), (32, pad_w+32)), mode="reflect") 70 | 71 | sample['image'] = padded_image 72 | sample['trimap'] = padded_trimap 73 | 74 | # ImageNet mean & std 75 | mean = torch.tensor([0.485, 0.456, 0.406]).view(3,1,1) 76 | std = torch.tensor([0.229, 0.224, 0.225]).view(3,1,1) 77 | 78 | # convert GBR images to RGB 79 | image, trimap = sample['image'][:,:,::-1], sample['trimap'] 80 | 81 | # swap color axis 82 | image = image.transpose((2, 0, 1)).astype(np.float32) 83 | 84 | # trimap configuration 85 | padded_trimap[padded_trimap < 85] = 0 86 | padded_trimap[padded_trimap >= 170] = 2 87 | padded_trimap[padded_trimap >= 85] = 1 88 | 89 | # normalize image 90 | image /= 255. 91 | 92 | # to tensor 93 | sample['image'], sample['trimap'] = torch.from_numpy(image), torch.from_numpy(trimap).to(torch.long) 94 | sample['image'] = sample['image'].sub_(mean).div_(std) 95 | 96 | # trimap to one-hot 3 channel 97 | sample['trimap'] = F.one_hot(sample['trimap'], num_classes=3).permute(2, 0, 1).float() 98 | 99 | # add first channel 100 | sample['image'], sample['trimap'] = sample['image'][None, ...], sample['trimap'][None, ...] 101 | 102 | return sample 103 | 104 | 105 | if __name__ == '__main__': 106 | parser = argparse.ArgumentParser() 107 | parser.add_argument('--config', type=str, default='config/MatteFormer_Composition1k.toml') 108 | parser.add_argument('--checkpoint', type=str, default='pretrained/best_model.pth', help="path of checkpoint") 109 | 110 | # local 111 | parser.add_argument('--image-dir', type=str, default='Composition-1k-testset/merged/', help="input image dir") 112 | parser.add_argument('--mask-dir', type=str, default='Composition-1k-testset/alpha_copy/', help="input trimap dir") 113 | parser.add_argument('--trimap-dir', type=str, default='Composition-1k-testset/trimaps/', help="input trimap dir") 114 | 115 | parser.add_argument('--output', type=str, default='predDIM/', help="output dir") 116 | 117 | # Parse configuration 118 | args = parser.parse_args() 119 | with open(args.config) as f: 120 | utils.load_config(toml.load(f)) 121 | 122 | # Check if toml config file is loaded 123 | if CONFIG.is_default: 124 | raise ValueError("No .toml config loaded.") 125 | 126 | utils.make_dir(os.path.join(args.output, 'pred_alpha')) 127 | 128 | # build model 129 | model = networks.get_generator(is_train=False) 130 | model.cuda() 131 | 132 | # load checkpoint 133 | checkpoint = torch.load(args.checkpoint) 134 | model.load_state_dict(utils.remove_prefix_state_dict(checkpoint['state_dict']), strict=True) 135 | 136 | # inference 137 | model = model.eval() 138 | 139 | for i, image_name in enumerate(os.listdir(args.image_dir)): 140 | 141 | # assume image and mask have the same file name 142 | image_path = os.path.join(args.image_dir, image_name) 143 | trimap_path = os.path.join(args.trimap_dir, image_name) 144 | 145 | image_dict = generator_tensor_dict(image_path, trimap_path) 146 | alpha_pred = single_inference(model, image_dict) 147 | 148 | # save images 149 | _im = cv2.imread(image_path) 150 | _tr = cv2.imread(trimap_path) 151 | _al = cv2.cvtColor(alpha_pred, cv2.COLOR_GRAY2RGB) 152 | h, w, c = _al.shape 153 | 154 | canvas = np.zeros((h, w*3, c)) 155 | canvas[:, w*0:w*1, :] = _im 156 | canvas[:, w*1:w*2, :] = _tr 157 | canvas[:, w*2:w*3, :] = _al 158 | 159 | cv2.imwrite(os.path.join(args.output, 'pred_alpha', image_name), _al) 160 | print('[{}/{}] inference done : {}'.format(i, len(os.listdir(args.image_dir)), os.path.join(args.output, 'pred_alpha', image_name))) -------------------------------------------------------------------------------- /main.py: -------------------------------------------------------------------------------- 1 | ''' 2 | OMP_NUM_THREADS=2 python3 -m torch.distributed.launch --nproc_per_node=2 main.py 3 | ''' 4 | 5 | import argparse 6 | import os 7 | import random 8 | import shutil 9 | from datetime import datetime 10 | from pprint import pprint 11 | 12 | import numpy as np 13 | import toml 14 | import torch 15 | from torch.utils.data import DataLoader 16 | 17 | import utils 18 | from dataloader.data_generator import DataGenerator 19 | from dataloader.image_file import ImageFileTrain, ImageFileTest 20 | from dataloader.prefetcher import Prefetcher 21 | from trainers.trainer import Trainer 22 | from utils import CONFIG 23 | 24 | torch.manual_seed(8282) 25 | torch.cuda.manual_seed(8282) 26 | torch.cuda.manual_seed_all(8282) # if use multi-GPU 27 | torch.backends.cudnn.deterministic = True 28 | torch.backends.cudnn.benchmark = False 29 | np.random.seed(8282) 30 | random.seed(8282) 31 | 32 | 33 | def copy_script(root_path=None): 34 | if not os.path.exists(root_path): 35 | os.makedirs(root_path) 36 | os.makedirs(CONFIG.log.logging_path) 37 | os.makedirs(CONFIG.log.checkpoint_path) 38 | 39 | shutil.copytree('./config', os.path.join(root_path, 'config'), ignore=shutil.ignore_patterns('__pycache__')) 40 | shutil.copytree('./dataloader', os.path.join(root_path, 'dataloader'), ignore=shutil.ignore_patterns('__pycache__')) 41 | shutil.copytree('./networks', os.path.join(root_path, 'networks'), ignore=shutil.ignore_patterns('__pycache__')) 42 | shutil.copytree('./trainers', os.path.join(root_path, 'trainers'), ignore=shutil.ignore_patterns('__pycache__')) 43 | shutil.copytree('./utils', os.path.join(root_path, 'utils'), ignore=shutil.ignore_patterns('__pycache__')) 44 | 45 | shutil.copy('./main.py', os.path.join(root_path, 'main.py')) 46 | shutil.copy('./inference.py', os.path.join(root_path, 'inference.py')) 47 | shutil.copy('./evaluation.py', os.path.join(root_path, 'evaluation.py')) 48 | 49 | 50 | def main(): 51 | # Train or Test 52 | if CONFIG.phase.lower() == "train": 53 | # set distributed training 54 | if CONFIG.dist: 55 | CONFIG.gpu = CONFIG.local_rank 56 | torch.cuda.set_device(CONFIG.gpu) 57 | torch.distributed.init_process_group(backend='nccl', init_method='env://') 58 | CONFIG.world_size = torch.distributed.get_world_size() 59 | 60 | # Create directories if not exist. 61 | if CONFIG.local_rank == 0: 62 | utils.make_dir(CONFIG.log.logging_path) 63 | utils.make_dir(CONFIG.log.checkpoint_path) 64 | 65 | """=== Set logger ===""" 66 | logger = utils.get_logger(CONFIG.log.logging_path, logging_level=CONFIG.log.logging_level) 67 | 68 | """=== Set data loader ===""" 69 | # [1] Composition-1k dataset 70 | train_image_file = ImageFileTrain(alpha_dir=CONFIG.data.train_alpha, 71 | fg_dir=CONFIG.data.train_fg, 72 | bg_dir=CONFIG.data.train_bg) 73 | test_image_file = ImageFileTest(alpha_dir=CONFIG.data.test_alpha, 74 | merged_dir=CONFIG.data.test_merged, 75 | trimap_dir=CONFIG.data.test_trimap) 76 | train_dataset = DataGenerator(train_image_file, phase='train') 77 | test_dataset = DataGenerator(test_image_file, phase='val') 78 | 79 | if CONFIG.dist: 80 | train_sampler = torch.utils.data.distributed.DistributedSampler(train_dataset) 81 | test_sampler = torch.utils.data.distributed.DistributedSampler(test_dataset) 82 | else: 83 | train_sampler = None 84 | test_sampler = None 85 | 86 | train_dataloader = DataLoader(train_dataset, 87 | batch_size=CONFIG.model.batch_size, 88 | shuffle=(train_sampler is None), 89 | num_workers=CONFIG.data.workers, 90 | pin_memory=True, 91 | sampler=train_sampler, 92 | drop_last=True) 93 | train_dataloader = Prefetcher(train_dataloader) 94 | test_dataloader = DataLoader(test_dataset, 95 | batch_size=1, 96 | shuffle=False, 97 | num_workers=CONFIG.data.workers, 98 | sampler=test_sampler, 99 | drop_last=False) 100 | 101 | """=== Set Trainer ===""" 102 | trainer = Trainer(train_dataloader=train_dataloader, 103 | test_dataloader=test_dataloader, 104 | logger=logger) 105 | """=== Run Trainer ===""" 106 | trainer.train() 107 | 108 | else: 109 | raise NotImplementedError("Unknown Phase: {}".format(CONFIG.phase)) 110 | 111 | 112 | if __name__ == '__main__': 113 | 114 | parser = argparse.ArgumentParser() 115 | parser.add_argument('--phase', type=str, default='train') 116 | parser.add_argument('--local_rank', type=int, default=0) 117 | 118 | # Composition-1k 119 | parser.add_argument('--config', type=str, default='config/MatteFormer_Composition1k.toml') 120 | 121 | # Parse configuration 122 | args = parser.parse_args() 123 | with open(args.config) as f: 124 | utils.load_config(toml.load(f)) 125 | 126 | # Check if toml config file is loaded 127 | if CONFIG.is_default: 128 | raise ValueError("No .toml config loaded.") 129 | CONFIG.phase = args.phase 130 | 131 | # set_experiment path 132 | CONFIG.log.experiment_root = os.path.join(CONFIG.log.experiment_root, datetime.now().strftime("%y%m%d_%H%M%S")) 133 | CONFIG.log.logging_path = os.path.join(CONFIG.log.experiment_root, CONFIG.log.logging_path) 134 | CONFIG.log.checkpoint_path = os.path.join(CONFIG.log.experiment_root, CONFIG.log.checkpoint_path) 135 | 136 | if args.local_rank == 0: 137 | print('CONFIG: ') 138 | pprint(CONFIG) 139 | copy_script(root_path=CONFIG.log.experiment_root) 140 | 141 | CONFIG.local_rank = args.local_rank 142 | 143 | # Train 144 | main() 145 | 146 | -------------------------------------------------------------------------------- /networks/__init__.py: -------------------------------------------------------------------------------- 1 | from .generators import * 2 | -------------------------------------------------------------------------------- /networks/decoders/__init__.py: -------------------------------------------------------------------------------- 1 | from .resnet_decoder import ResNet_D_Dec, ResShortCut_D_Decoder, BasicBlock 2 | 3 | __all__ = ['res_shortcut_decoder'] 4 | 5 | def res_shortcut_decoder(**kwargs): 6 | return ResShortCut_D_Decoder(BasicBlock, [2, 3, 3, 2], **kwargs) 7 | 8 | -------------------------------------------------------------------------------- /networks/decoders/resnet_decoder.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from typing import List 3 | 4 | import torch 5 | import torch.nn as nn 6 | import torch.nn.functional as F 7 | 8 | from networks.ops import SpectralNorm 9 | 10 | 11 | def conv5x5(in_planes, out_planes, stride=1, groups=1, dilation=1): 12 | """5x5 convolution with padding""" 13 | return nn.Conv2d(in_planes, out_planes, kernel_size=5, stride=stride, 14 | padding=2, groups=groups, bias=False, dilation=dilation) 15 | 16 | 17 | def conv3x3(in_planes, out_planes, stride=1, groups=1, dilation=1): 18 | """3x3 convolution with padding""" 19 | return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride, 20 | padding=dilation, groups=groups, bias=False, dilation=dilation) 21 | 22 | 23 | def conv1x1(in_planes, out_planes, stride=1): 24 | """1x1 convolution""" 25 | return nn.Conv2d(in_planes, out_planes, kernel_size=1, stride=stride, bias=False) 26 | 27 | 28 | class BasicBlock(nn.Module): 29 | expansion = 1 30 | 31 | def __init__(self, inplanes, planes, stride=1, upsample=None, norm_layer=None, large_kernel=False): 32 | super(BasicBlock, self).__init__() 33 | if norm_layer is None: 34 | norm_layer = nn.BatchNorm2d 35 | self.stride = stride 36 | conv = conv5x5 if large_kernel else conv3x3 37 | # Both self.conv1 and self.downsample layers downsample the input when stride != 1 38 | if self.stride > 1: 39 | self.conv1 = SpectralNorm(nn.ConvTranspose2d(inplanes, inplanes, kernel_size=4, stride=2, padding=1, bias=False)) 40 | else: 41 | self.conv1 = SpectralNorm(conv(inplanes, inplanes)) 42 | self.bn1 = norm_layer(inplanes) 43 | self.activation = nn.LeakyReLU(0.2, inplace=True) 44 | self.conv2 = SpectralNorm(conv(inplanes, planes)) 45 | self.bn2 = norm_layer(planes) 46 | self.upsample = upsample 47 | 48 | def forward(self, x): 49 | identity = x 50 | 51 | out = self.conv1(x) 52 | out = self.bn1(out) 53 | out = self.activation(out) 54 | 55 | out = self.conv2(out) 56 | out = self.bn2(out) 57 | 58 | if self.upsample is not None: 59 | identity = self.upsample(x) 60 | 61 | out += identity 62 | out = self.activation(out) 63 | 64 | return out 65 | 66 | 67 | class ResNet_D_Dec(nn.Module): 68 | 69 | def __init__(self, block, layers, norm_layer=None, large_kernel=False, late_downsample=False): 70 | super(ResNet_D_Dec, self).__init__() 71 | self.logger = logging.getLogger("Logger") 72 | if norm_layer is None: 73 | norm_layer = nn.BatchNorm2d 74 | self._norm_layer = norm_layer 75 | self.large_kernel = large_kernel 76 | self.kernel_size = 5 if self.large_kernel else 3 77 | 78 | self.inplanes = 512 if layers[0] > 0 else 256 79 | self.late_downsample = late_downsample 80 | self.midplanes = 64 if late_downsample else 32 81 | 82 | self.conv1 = SpectralNorm(nn.ConvTranspose2d(self.midplanes, 32, kernel_size=4, stride=2, padding=1, bias=False)) 83 | self.bn1 = norm_layer(32) 84 | self.leaky_relu = nn.LeakyReLU(0.2, inplace=True) 85 | 86 | self.upsample = nn.UpsamplingNearest2d(scale_factor=2) 87 | self.tanh = nn.Tanh() 88 | self.layer1 = self._make_layer(block, 256, layers[0], stride=2) 89 | self.layer2 = self._make_layer(block, 128, layers[1], stride=2) 90 | self.layer3 = self._make_layer(block, 64, layers[2], stride=2) 91 | self.layer4 = self._make_layer(block, self.midplanes, layers[3], stride=2) 92 | 93 | self.refine_OS1 = nn.Sequential( 94 | nn.Conv2d(32, 32, kernel_size=self.kernel_size, stride=1, padding=self.kernel_size//2, bias=False), 95 | norm_layer(32), 96 | self.leaky_relu, 97 | nn.Conv2d(32, 1, kernel_size=self.kernel_size, stride=1, padding=self.kernel_size//2),) 98 | 99 | self.refine_OS4 = nn.Sequential( 100 | nn.Conv2d(64, 32, kernel_size=self.kernel_size, stride=1, padding=self.kernel_size//2, bias=False), 101 | norm_layer(32), 102 | self.leaky_relu, 103 | nn.Conv2d(32, 1, kernel_size=self.kernel_size, stride=1, padding=self.kernel_size//2),) 104 | 105 | self.refine_OS8 = nn.Sequential( 106 | nn.Conv2d(128, 32, kernel_size=self.kernel_size, stride=1, padding=self.kernel_size//2, bias=False), 107 | norm_layer(32), 108 | self.leaky_relu, 109 | nn.Conv2d(32, 1, kernel_size=self.kernel_size, stride=1, padding=self.kernel_size//2),) 110 | 111 | for m in self.modules(): 112 | if isinstance(m, nn.Conv2d): 113 | if hasattr(m, "weight_bar"): 114 | nn.init.xavier_uniform_(m.weight_bar) 115 | else: 116 | nn.init.xavier_uniform_(m.weight) 117 | elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): 118 | nn.init.constant_(m.weight, 1) 119 | nn.init.constant_(m.bias, 0) 120 | 121 | # Zero-initialize the last BN in each residual branch, 122 | # so that the residual branch starts with zeros, and each residual block behaves like an identity. 123 | # This improves the model by 0.2~0.3% according to https://arxiv.org/abs/1706.02677 124 | for m in self.modules(): 125 | if isinstance(m, BasicBlock): 126 | nn.init.constant_(m.bn2.weight, 0) 127 | 128 | self.logger.debug(self) 129 | 130 | def _make_layer(self, block, planes, blocks, stride=1): 131 | if blocks == 0: 132 | return nn.Sequential(nn.Identity()) 133 | norm_layer = self._norm_layer 134 | upsample = None 135 | if stride != 1: 136 | upsample = nn.Sequential( 137 | nn.UpsamplingNearest2d(scale_factor=2), 138 | SpectralNorm(conv1x1(self.inplanes, planes * block.expansion)), 139 | norm_layer(planes * block.expansion), 140 | ) 141 | elif self.inplanes != planes * block.expansion: 142 | upsample = nn.Sequential( 143 | SpectralNorm(conv1x1(self.inplanes, planes * block.expansion)), 144 | norm_layer(planes * block.expansion), 145 | ) 146 | 147 | layers = [block(self.inplanes, planes, stride, upsample, norm_layer, self.large_kernel)] 148 | self.inplanes = planes * block.expansion 149 | for _ in range(1, blocks): 150 | layers.append(block(self.inplanes, planes, norm_layer=norm_layer, large_kernel=self.large_kernel)) 151 | 152 | return nn.Sequential(*layers) 153 | 154 | def forward(self, x, mid_fea): 155 | ret = {} 156 | 157 | x = self.layer1(x) # N x 256 x 32 x 32 158 | x = self.layer2(x) # N x 128 x 64 x 64 159 | x_os8 = self.refine_OS8(x) 160 | 161 | x = self.layer3(x) # N x 64 x 128 x 128 162 | x_os4 = self.refine_OS4(x) 163 | 164 | x = self.layer4(x) # N x 32 x 256 x 256 165 | x = self.conv1(x) 166 | x = self.bn1(x) 167 | x = self.leaky_relu(x) 168 | x_os1 = self.refine_OS1(x) 169 | 170 | x_os4 = F.interpolate(x_os4, scale_factor=4.0, mode='bilinear', align_corners=False) 171 | x_os8 = F.interpolate(x_os8, scale_factor=8.0, mode='bilinear', align_corners=False) 172 | 173 | x_os1 = (torch.tanh(x_os1) + 1.0) / 2.0 174 | x_os4 = (torch.tanh(x_os4) + 1.0) / 2.0 175 | x_os8 = (torch.tanh(x_os8) + 1.0) / 2.0 176 | 177 | ret['alpha_os1'] = x_os1 178 | ret['alpha_os4'] = x_os4 179 | ret['alpha_os8'] = x_os8 180 | 181 | return ret 182 | 183 | 184 | class ResShortCut_D_Decoder(ResNet_D_Dec): 185 | 186 | def __init__(self, block, layers, norm_layer=None, large_kernel=False, late_downsample=False): 187 | super(ResShortCut_D_Decoder, self).__init__(block, layers, norm_layer, large_kernel, late_downsample=late_downsample) 188 | 189 | def forward(self, x, mid_fea:List[torch.Tensor]): 190 | ret = {} 191 | fea1, fea2, fea3, fea4, fea5 = mid_fea 192 | x = self.layer1(x) + fea5 193 | x = self.layer2(x) + fea4 194 | x_os8 = self.refine_OS8(x) 195 | 196 | x = self.layer3(x) + fea3 197 | x_os4 = self.refine_OS4(x) 198 | 199 | x = self.layer4(x) + fea2 200 | x = self.conv1(x) 201 | x = self.bn1(x) 202 | x = self.leaky_relu(x) + fea1 203 | x_os1 = self.refine_OS1(x) 204 | 205 | x_os4 = F.interpolate(x_os4, scale_factor=4.0, mode='bilinear', align_corners=False) 206 | x_os8 = F.interpolate(x_os8, scale_factor=8.0, mode='bilinear', align_corners=False) 207 | 208 | x_os1 = (torch.tanh(x_os1) + 1.0) / 2.0 209 | x_os4 = (torch.tanh(x_os4) + 1.0) / 2.0 210 | x_os8 = (torch.tanh(x_os8) + 1.0) / 2.0 211 | 212 | ret['alpha_os1'] = x_os1 213 | ret['alpha_os4'] = x_os4 214 | ret['alpha_os8'] = x_os8 215 | 216 | return ret 217 | 218 | -------------------------------------------------------------------------------- /networks/encoders/MatteFormer.py: -------------------------------------------------------------------------------- 1 | """ MatteFormer 2 | Copyright (c) 2022-present NAVER Webtoon 3 | Apache-2.0 4 | """ 5 | 6 | import cv2 7 | import random 8 | import torch 9 | import torch.nn as nn 10 | import torch.nn.functional as F 11 | import torch.utils.checkpoint as checkpoint 12 | import numpy as np 13 | from timm.models.layers import DropPath, to_2tuple, trunc_normal_ 14 | from networks.ops import SpectralNorm 15 | 16 | 17 | def window_partition(x, window_size, priors=None): 18 | """ 19 | Args: 20 | x: (B, H, W, C) 21 | window_size (int): window size 22 | 23 | Returns: 24 | windows: (num_windows*B, window_size, window_size, C) 25 | """ 26 | 27 | if priors is not None: 28 | B, H, W, C = x.shape 29 | x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) 30 | windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size * window_size, C) 31 | 32 | return_priors = list() 33 | for p, prior in enumerate(priors): 34 | prior['unknown'] = prior['unknown'].unsqueeze(1) 35 | prior['fg'] = prior['fg'].unsqueeze(1) 36 | prior['bg'] = prior['bg'].unsqueeze(1) 37 | return_priors.append(prior) 38 | 39 | return windows, return_priors 40 | 41 | else: 42 | B, H, W, C = x.shape 43 | x = x.view(B, H // window_size, window_size, W // window_size, window_size, C) 44 | windows = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(-1, window_size, window_size, C) 45 | 46 | return windows 47 | 48 | 49 | def window_reverse(windows, window_size, H, W): 50 | """ 51 | Args: 52 | windows: (num_windows*B, window_size, window_size, C) 53 | window_size (int): Window size 54 | H (int): Height of image 55 | W (int): Width of image 56 | 57 | Returns: 58 | x: (B, H, W, C) 59 | """ 60 | B = int(windows.shape[0] / (H * W / window_size / window_size)) 61 | x = windows.view(B, H // window_size, W // window_size, window_size, window_size, -1) 62 | x = x.permute(0, 1, 3, 2, 4, 5).contiguous().view(B, H, W, -1) 63 | return x 64 | 65 | 66 | class Mlp(nn.Module): 67 | """ Multilayer perceptron.""" 68 | 69 | def __init__(self, in_features, hidden_features=None, out_features=None, act_layer=nn.GELU, drop=0.): 70 | super().__init__() 71 | out_features = out_features or in_features 72 | hidden_features = hidden_features or in_features 73 | self.fc1 = nn.Linear(in_features, hidden_features) 74 | self.act = act_layer() 75 | self.fc2 = nn.Linear(hidden_features, out_features) 76 | self.drop = nn.Dropout(drop) 77 | 78 | def forward(self, x): 79 | x = self.fc1(x) 80 | x = self.act(x) 81 | x = self.drop(x) 82 | x = self.fc2(x) 83 | x = self.drop(x) 84 | return x 85 | 86 | 87 | class PatchMerging(nn.Module): 88 | """ Patch Merging Layer 89 | 90 | Args: 91 | dim (int): Number of input channels. 92 | norm_layer (nn.Module, optional): Normalization layer. Default: nn.LayerNorm 93 | """ 94 | def __init__(self, dim, norm_layer=nn.LayerNorm): 95 | super().__init__() 96 | self.dim = dim 97 | self.reduction = nn.Linear(4 * dim, 2 * dim, bias=False) 98 | self.norm = norm_layer(4 * dim) 99 | 100 | def forward(self, x, H, W): 101 | """ Forward function. 102 | 103 | Args: 104 | x: Input feature, tensor size (B, H*W, C). 105 | H, W: Spatial resolution of the input feature. 106 | """ 107 | B, L, C = x.shape 108 | assert L == H * W, "input feature has wrong size" 109 | 110 | x = x.view(B, H, W, C) 111 | 112 | # padding 113 | pad_input = (H % 2 == 1) or (W % 2 == 1) 114 | if pad_input: 115 | x = F.pad(x, (0, 0, 0, W % 2, 0, H % 2)) 116 | 117 | x0 = x[:, 0::2, 0::2, :] # B H/2 W/2 C 118 | x1 = x[:, 1::2, 0::2, :] # B H/2 W/2 C 119 | x2 = x[:, 0::2, 1::2, :] # B H/2 W/2 C 120 | x3 = x[:, 1::2, 1::2, :] # B H/2 W/2 C 121 | x = torch.cat([x0, x1, x2, x3], -1) # B H/2 W/2 4*C 122 | x = x.view(B, -1, 4 * C) # B H/2*W/2 4*C 123 | 124 | x = self.norm(x) 125 | x = self.reduction(x) 126 | 127 | return x 128 | 129 | 130 | class PatchEmbed(nn.Module): 131 | """ Image to Patch Embedding 132 | 133 | Args: 134 | patch_size (int): Patch token size. Default: 4. 135 | in_chans (int): Number of input image channels. Default: 3. 136 | embed_dim (int): Number of linear projection output channels. Default: 96. 137 | norm_layer (nn.Module, optional): Normalization layer. Default: None 138 | """ 139 | 140 | def __init__(self, patch_size=4, in_chans=3, embed_dim=96, norm_layer=None): 141 | super().__init__() 142 | patch_size = to_2tuple(patch_size) 143 | self.patch_size = patch_size 144 | 145 | self.in_chans = in_chans 146 | self.embed_dim = embed_dim 147 | 148 | self.proj = nn.Conv2d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size) 149 | if norm_layer is not None: 150 | self.norm = norm_layer(embed_dim) 151 | else: 152 | self.norm = None 153 | 154 | """Forward function.""" 155 | def forward(self, x): 156 | 157 | _, _, H, W = x.size() 158 | 159 | # padding 160 | if W % self.patch_size[1] != 0: 161 | x = F.pad(x, (0, self.patch_size[1] - W % self.patch_size[1])) 162 | if H % self.patch_size[0] != 0: 163 | x = F.pad(x, (0, 0, 0, self.patch_size[0] - H % self.patch_size[0])) 164 | 165 | x = self.proj(x) # B C Wh Ww 166 | if self.norm is not None: 167 | Wh, Ww = x.size(2), x.size(3) 168 | x = x.flatten(2).transpose(1, 2) 169 | x = self.norm(x) 170 | x = x.transpose(1, 2).view(-1, self.embed_dim, Wh, Ww) 171 | 172 | return x 173 | 174 | 175 | class PAWSA(nn.Module): 176 | def __init__(self, dim, window_size, num_heads, qkv_bias=True, qk_scale=None, 177 | attn_drop=0., proj_drop=0., use_prior=True, num_priorset=1): 178 | 179 | super().__init__() 180 | self.dim = dim 181 | self.window_size = window_size # Wh, Ww 182 | self.num_heads = num_heads 183 | head_dim = dim // num_heads 184 | self.scale = qk_scale or head_dim ** -0.5 185 | 186 | self.use_prior = use_prior 187 | self.num_priorset = num_priorset 188 | 189 | # use 3 prior vector 190 | self.relative_position_bias_table = nn.Parameter( 191 | torch.zeros((2 * window_size[0] - 1) * (2 * window_size[1] - 1) + 3*self.num_priorset, num_heads)) 192 | 193 | # get pair-wise relative position index for each token inside the window 194 | coords_h = torch.arange(self.window_size[0]) 195 | coords_w = torch.arange(self.window_size[1]) 196 | coords = torch.stack(torch.meshgrid([coords_h, coords_w])) 197 | coords_flatten = torch.flatten(coords, 1) 198 | relative_coords = coords_flatten[:, :, None] - coords_flatten[:, None, :] 199 | relative_coords = relative_coords.permute(1, 2, 0).contiguous() 200 | relative_coords[:, :, 0] += self.window_size[0] - 1 201 | relative_coords[:, :, 1] += self.window_size[1] - 1 202 | relative_coords[:, :, 0] *= 2 * self.window_size[1] - 1 203 | relative_position_index = relative_coords.sum(-1) 204 | 205 | # relative position index 206 | num_patch = self.window_size[0] * self.window_size[1] 207 | last_idx = 169 208 | relative_position_index_withPrior = torch.ones((num_patch, num_patch + self.num_priorset*3)).long() * last_idx 209 | relative_position_index_withPrior[:num_patch, :num_patch] = relative_position_index 210 | for i in range(self.num_priorset): 211 | for j in range(3): 212 | relative_position_index_withPrior[:, num_patch + i*3 + j:num_patch + i*3 +j +1] = last_idx + i*3 + j 213 | self.register_buffer("relative_position_index", relative_position_index_withPrior) 214 | 215 | # params 216 | self.qkv = nn.Linear(dim, dim * 3, bias=qkv_bias) 217 | 218 | self.proj = nn.Linear(dim, dim) 219 | self.proj_drop = nn.Dropout(proj_drop) 220 | 221 | trunc_normal_(self.relative_position_bias_table, std=.02) 222 | 223 | self.softmax = nn.Softmax(dim=-1) 224 | 225 | def forward(self, x, mask=None, _inp_shape=None, prior_bins=None): 226 | # get shape 227 | B_, N, C = x.shape 228 | B, H, W, C = _inp_shape 229 | 230 | # for prior-memory 231 | prior_highway = None 232 | for prior in prior_bins: 233 | uk_prior, fg_prior, bg_prior = prior['unknown'], prior['fg'], prior['bg'] 234 | # prior highways (for shortcut) 235 | if prior_highway is None: 236 | prior_highway = torch.cat((uk_prior, fg_prior, bg_prior), dim=1) 237 | else: 238 | prior_highway = torch.cat((prior_highway, uk_prior, fg_prior, bg_prior), dim=1) 239 | # concate prior-tokens to spatial-tokens(x) 240 | uk_prior = uk_prior.expand((-1, (H // self.window_size[0]) * (W // self.window_size[1]), -1)).unsqueeze(2).contiguous().view(-1, 1, C) 241 | fg_prior = fg_prior.expand((-1, (H // self.window_size[0]) * (W // self.window_size[1]), -1)).unsqueeze(2).contiguous().view(-1, 1, C) 242 | bg_prior = bg_prior.expand((-1, (H // self.window_size[0]) * (W // self.window_size[1]), -1)).unsqueeze(2).contiguous().view(-1, 1, C) 243 | x = torch.cat((x, uk_prior, fg_prior, bg_prior), dim=1) 244 | 245 | relative_position_bias = self.relative_position_bias_table[self.relative_position_index.view(-1)] \ 246 | .view(self.window_size[0] * self.window_size[1], self.window_size[0] * self.window_size[1] + self.num_priorset*3, -1) 247 | relative_position_bias = relative_position_bias.permute(2, 0, 1).contiguous() 248 | 249 | # qkv projection for x 250 | qkv = self.qkv(x).reshape(B_, N + self.num_priorset*3, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) 251 | q, k, v = qkv[0], qkv[1], qkv[2] 252 | q = q[:, :, :self.window_size[0] * self.window_size[1], :] * self.scale 253 | 254 | # get self-attention features 255 | attn = (q @ k.transpose(-2, -1)) 256 | attn = attn + relative_position_bias.unsqueeze(0) 257 | if mask is not None: 258 | nW = mask.shape[0] 259 | mask_withPrior = F.pad(mask, (0, self.num_priorset*3, 0, 0)) 260 | attn = attn.view(B_ // nW, nW, self.num_heads, N, N + self.num_priorset*3) + mask_withPrior.contiguous().unsqueeze(1).unsqueeze(0) 261 | attn = attn.view(-1, self.num_heads, N, N + self.num_priorset*3) 262 | attn = self.softmax(attn) 263 | 264 | x = (attn @ v).transpose(1, 2).reshape(B_, N, C) 265 | 266 | # projection 267 | x = self.proj(x) 268 | x = self.proj_drop(x) 269 | 270 | # prior projection for prior-memory 271 | prior_highway = self.qkv(prior_highway).reshape(B, self.num_priorset*3, 3, self.num_heads, C // self.num_heads).permute(2, 0, 3, 1, 4) 272 | _q_hw, _k_hw, _v_hw = prior_highway[0], prior_highway[1], prior_highway[2] 273 | 274 | _v_hw = _v_hw.transpose(1,2).reshape(B, self.num_priorset*3, C) 275 | _v_hw = self.proj(_v_hw) 276 | _v_hw = self.proj_drop(_v_hw) 277 | 278 | return x, _v_hw 279 | 280 | 281 | class PASTBlock(nn.Module): 282 | def __init__(self, layer_idx, block_idx, dim, num_heads, window_size=7, shift_size=0, 283 | mlp_ratio=4., qkv_bias=True, qk_scale=None, drop=0., attn_drop=0., drop_path=0., 284 | act_layer=nn.GELU, norm_layer=nn.LayerNorm, use_prior=True, num_priorset=0): 285 | super().__init__() 286 | self.layer_idx = layer_idx 287 | self.block_idx = block_idx 288 | self.dim = dim 289 | self.num_heads = num_heads 290 | self.window_size = window_size 291 | self.shift_size = shift_size 292 | self.mlp_ratio = mlp_ratio 293 | self.use_prior = use_prior 294 | self.num_priorset = num_priorset 295 | 296 | assert 0 <= self.shift_size < self.window_size, "shift_size must in 0-window_size" 297 | 298 | self.norm1 = norm_layer(dim) 299 | self.attn = PAWSA( 300 | dim, window_size=to_2tuple(self.window_size), num_heads=num_heads, 301 | qkv_bias=qkv_bias, qk_scale=qk_scale, attn_drop=attn_drop, proj_drop=drop, use_prior=self.use_prior, num_priorset=self.num_priorset) 302 | 303 | self.drop_path = DropPath(drop_path) if drop_path > 0. else nn.Identity() 304 | self.norm2 = norm_layer(dim) 305 | mlp_hidden_dim = int(dim * mlp_ratio) 306 | self.mlp = Mlp(in_features=dim, hidden_features=mlp_hidden_dim, act_layer=act_layer, drop=drop) 307 | 308 | self.H = None 309 | self.W = None 310 | 311 | # swin transformer block 312 | def forward(self, x, mask_matrix, prior_memory=None, area_fg=None, area_bg=None, area_uk=None): 313 | B, L, C = x.shape 314 | H, W = self.H, self.W 315 | assert L == H * W, "input feature has wrong size" 316 | 317 | # shortcut features 318 | shortcut = x 319 | 320 | # shortcut prior features (current prior + previous blk prior) 321 | if True: 322 | shortcut_prior = dict() 323 | shortcut_ = shortcut.view(B, H, W, C) # [1, 256, 512, 96] 324 | 325 | epsilon = 1e-9 326 | uk_prior = (area_uk * shortcut_).permute(0,3,1,2) 327 | uk_prior = uk_prior.sum(axis=(-1,-2)) / (area_uk.sum(axis=(1,2)) + epsilon) 328 | fg_prior = (area_fg * shortcut_).permute(0, 3, 1, 2) 329 | fg_prior = fg_prior.sum(axis=(-1,-2)) / (area_fg.sum(axis=(1,2)) + epsilon) 330 | bg_prior = (area_bg * shortcut_).permute(0, 3, 1, 2) 331 | bg_prior = bg_prior.sum(axis=(-1, -2)) / (area_bg.sum(axis=(1,2)) + epsilon) 332 | 333 | shortcut_prior['fg'] = fg_prior 334 | shortcut_prior['bg'] = bg_prior 335 | shortcut_prior['unknown'] = uk_prior 336 | 337 | # current blk prior on last index 338 | prior_memory.append(shortcut_prior) 339 | 340 | # forward 341 | x = self.norm1(x) 342 | x = x.view(B, H, W, C) 343 | 344 | # forward all prior to norm1 345 | if True: 346 | prior_bins = list() 347 | for p, prior in enumerate(prior_memory): 348 | prior_bin = dict() 349 | prior_bin['fg'] = self.norm1(prior['fg']) 350 | prior_bin['bg'] = self.norm1(prior['bg']) 351 | prior_bin['unknown'] = self.norm1(prior['unknown']) 352 | prior_bins.append(prior_bin) 353 | 354 | # pad feature maps to multiples of window size 355 | pad_l = pad_t = 0 356 | pad_r = (self.window_size - W % self.window_size) % self.window_size 357 | pad_b = (self.window_size - H % self.window_size) % self.window_size 358 | x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b)) # [1, 259, 518, 96] 359 | _, Hp, Wp, _ = x.shape 360 | 361 | # cyclic shift 362 | if self.shift_size > 0: 363 | shifted_x = torch.roll(x, shifts=(-self.shift_size, -self.shift_size), dims=(1, 2)) 364 | attn_mask = mask_matrix 365 | else: 366 | shifted_x = x 367 | attn_mask = None 368 | 369 | # partition windows 370 | x_windows, prior_bins = window_partition(shifted_x, self.window_size, prior_bins) 371 | x_windows = x_windows.view(-1, self.window_size * self.window_size, C) 372 | 373 | # foward attention layer 374 | attn_windows, priors_after_attn = self.attn(x_windows, mask=attn_mask, prior_bins=prior_bins, _inp_shape=shifted_x.shape) 375 | 376 | # merge windows 377 | attn_windows = attn_windows.view(-1, self.window_size, self.window_size, C) 378 | shifted_x = window_reverse(attn_windows, self.window_size, Hp, Wp) # B H' W' C 379 | 380 | # reverse cyclic shift 381 | if self.shift_size > 0: 382 | x = torch.roll(shifted_x, shifts=(self.shift_size, self.shift_size), dims=(1, 2)) 383 | else: 384 | x = shifted_x 385 | 386 | if pad_r > 0 or pad_b > 0: 387 | x = x[:, :H, :W, :].contiguous() 388 | 389 | x = x.view(B, H * W, C) 390 | 391 | # FFN : second module 392 | x = shortcut + self.drop_path(x) 393 | x = x + self.drop_path(self.mlp(self.norm2(x))) 394 | 395 | if True: 396 | priors_after_attn = priors_after_attn.chunk(chunks=self.num_priorset*3, axis=1) 397 | prior_bins_outs = list() 398 | for idx in range(self.num_priorset): 399 | prior_bin_out = dict() 400 | prior_bin_out['unknown'] = priors_after_attn[idx*3+0] 401 | prior_bin_out['fg'] = priors_after_attn[idx*3+1] 402 | prior_bin_out['bg'] = priors_after_attn[idx*3+2] 403 | prior_bins_outs.append(prior_bin_out) 404 | 405 | # FFN : prior second module 406 | prior_memory_out = list() 407 | for p, (prior_shortcut, prior_out) in enumerate(zip(prior_memory, prior_bins_outs)): 408 | prior_out_uk = prior_shortcut['unknown'] + self.drop_path(prior_out['unknown'].squeeze()) 409 | prior_out_uk = prior_out_uk + self.drop_path(self.mlp(self.norm2(prior_out_uk))) 410 | 411 | prior_out_fg = prior_shortcut['fg'] + self.drop_path(prior_out['fg'].squeeze()) 412 | prior_out_fg = prior_out_fg + self.drop_path(self.mlp(self.norm2(prior_out_fg))) 413 | 414 | prior_out_bg = prior_shortcut['bg'] + self.drop_path(prior_out['bg'].squeeze()) 415 | prior_out_bg = prior_out_bg + self.drop_path(self.mlp(self.norm2(prior_out_bg))) 416 | 417 | prior_out = {'fg':prior_out_fg, 'bg':prior_out_bg, 'unknown':prior_out_uk} 418 | prior_memory_out.append(prior_out) 419 | 420 | return x, prior_memory_out 421 | 422 | 423 | class BasicLayer(nn.Module): 424 | 425 | def __init__(self, layer_idx, 426 | dim, depth, num_heads, window_size=7, mlp_ratio=4., qkv_bias=True, 427 | qk_scale=None, drop=0., attn_drop=0., drop_path=0., norm_layer=nn.LayerNorm, downsample=None, 428 | use_checkpoint=False, use_prior=True): 429 | super().__init__() 430 | self.layer_idx=layer_idx 431 | self.window_size = window_size 432 | self.shift_size = window_size // 2 433 | self.depth = depth 434 | self.use_checkpoint = use_checkpoint 435 | 436 | # build blocks 437 | self.blocks = nn.ModuleList([ 438 | PASTBlock( 439 | layer_idx=layer_idx, 440 | block_idx=i, 441 | dim=dim, 442 | num_heads=num_heads, 443 | window_size=window_size, 444 | shift_size=0 if (i % 2 == 0) else window_size // 2, 445 | mlp_ratio=mlp_ratio, 446 | qkv_bias=qkv_bias, 447 | qk_scale=qk_scale, 448 | drop=drop, 449 | attn_drop=attn_drop, 450 | drop_path=drop_path[i] if isinstance(drop_path, list) else drop_path, 451 | norm_layer=norm_layer, 452 | use_prior=use_prior, 453 | num_priorset=i+1) 454 | for i in range(depth)]) 455 | 456 | # patch merging layer 457 | if downsample is not None: 458 | self.downsample = downsample(dim=dim, norm_layer=norm_layer) 459 | else: 460 | self.downsample = None 461 | 462 | def _make_shortcut(self, inplane, planes, norm_layer=nn.BatchNorm2d): 463 | return nn.Sequential( 464 | nn.Linear(inplane, planes, bias=False), 465 | nn.ReLU(inplace=True), 466 | ) 467 | 468 | # basic layer 469 | def forward(self, x, H, W, area_fg, area_bg, area_uk): 470 | 471 | # calculate attention mask for SW-MSA 472 | Hp = int(np.ceil(H / self.window_size)) * self.window_size 473 | Wp = int(np.ceil(W / self.window_size)) * self.window_size 474 | img_mask = torch.zeros((1, Hp, Wp, 1), device=x.device) # 1 Hp Wp 1 475 | h_slices = (slice(0, -self.window_size), 476 | slice(-self.window_size, -self.shift_size), 477 | slice(-self.shift_size, None)) 478 | w_slices = (slice(0, -self.window_size), 479 | slice(-self.window_size, -self.shift_size), 480 | slice(-self.shift_size, None)) 481 | 482 | # img_mask -> index map (0~8) # [1, 259, 518, 1] 483 | cnt = 0 484 | for h in h_slices: 485 | for w in w_slices: 486 | img_mask[:, h, w, :] = cnt 487 | cnt += 1 488 | 489 | # get attn_mask 490 | mask_windows = window_partition(img_mask, self.window_size) 491 | mask_windows = mask_windows.view(-1, self.window_size * self.window_size) 492 | 493 | attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2) 494 | attn_mask = attn_mask.masked_fill(attn_mask != 0, float(-100.0)).masked_fill(attn_mask == 0, float(0.0)) 495 | 496 | # forward blocks 497 | prior_memory = [] 498 | for b, blk in enumerate(self.blocks): 499 | blk.H, blk.W = H, W 500 | 501 | if self.use_checkpoint: 502 | x = checkpoint.checkpoint(blk, x, attn_mask) 503 | else: 504 | x, prior_memory = blk(x, attn_mask, prior_memory=prior_memory, 505 | area_fg=area_fg, area_bg=area_bg, area_uk=area_uk) 506 | 507 | if self.downsample is not None: 508 | x_down = self.downsample(x, H, W) 509 | Wh, Ww = (H + 1) // 2, (W + 1) // 2 510 | return x, H, W, x_down, Wh, Ww 511 | else: 512 | return x, H, W, x, H, W 513 | 514 | 515 | class MatteFormer(nn.Module): 516 | 517 | def __init__(self, 518 | patch_size=4, in_chans=3, embed_dim=96, depths=[2, 2, 6, 2], 519 | num_heads=[3, 6, 12, 24], window_size=7, mlp_ratio=4., qkv_bias=True, qk_scale=None, 520 | drop_rate=0., attn_drop_rate=0., drop_path_rate=0.2, norm_layer=nn.LayerNorm, 521 | patch_norm=True, out_indices=(0, 1, 2, 3), use_checkpoint=False): 522 | super().__init__() 523 | 524 | self.num_layers = len(depths) 525 | self.embed_dim = embed_dim 526 | self.patch_norm = patch_norm 527 | self.out_indices = out_indices 528 | 529 | # split image into non-overlapping patches (with trimap) 530 | self.patch_embed = PatchEmbed( 531 | patch_size=patch_size, in_chans=in_chans+3, embed_dim=embed_dim, 532 | norm_layer=norm_layer if self.patch_norm else None) 533 | 534 | self.pos_drop = nn.Dropout(p=drop_rate) 535 | 536 | # stochastic depth 537 | dpr = [x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))] # stochastic depth decay rule 538 | 539 | # build layers 540 | self.layers = nn.ModuleList() 541 | for i_layer in range(self.num_layers): 542 | layer = BasicLayer( 543 | layer_idx = i_layer, 544 | dim=int(embed_dim * 2 ** i_layer), 545 | depth=depths[i_layer], 546 | num_heads=num_heads[i_layer], 547 | window_size=window_size, 548 | mlp_ratio=mlp_ratio, 549 | qkv_bias=qkv_bias, 550 | qk_scale=qk_scale, 551 | drop=drop_rate, 552 | attn_drop=attn_drop_rate, 553 | drop_path=dpr[sum(depths[:i_layer]):sum(depths[:i_layer + 1])], 554 | norm_layer=norm_layer, 555 | downsample=PatchMerging if (i_layer < self.num_layers - 1) else None, 556 | use_checkpoint=use_checkpoint, 557 | use_prior=True, 558 | ) 559 | self.layers.append(layer) 560 | 561 | num_features = [int(embed_dim * 2 ** i) for i in range(self.num_layers)] 562 | self.num_features = num_features 563 | 564 | # add a norm layer for each output [from Swin-Transformer-Semantic-Segmentation] 565 | for i_layer in out_indices: 566 | layer = norm_layer(num_features[i_layer]) 567 | layer_name = f'norm{i_layer}' 568 | self.add_module(layer_name, layer) 569 | 570 | # add shortcut layer [from MG-Matting] 571 | self.shortcut = nn.ModuleList() 572 | shortcut_inplanes = [[6, 32], [96, 32], [96, 64], [192, 128], [384, 256], [768, 512]] 573 | for shortcut in shortcut_inplanes: 574 | inplane, planes = shortcut 575 | self.shortcut.append(self._make_shortcut(inplane=inplane, planes=planes, norm_layer=nn.BatchNorm2d)) 576 | 577 | def _make_shortcut(self, inplane, planes, norm_layer=nn.BatchNorm2d): 578 | ''' 579 | came from MGMatting 580 | ''' 581 | return nn.Sequential( 582 | SpectralNorm(nn.Conv2d(inplane, planes, kernel_size=3, padding=1, bias=False)), 583 | nn.ReLU(inplace=True), 584 | norm_layer(planes), 585 | SpectralNorm(nn.Conv2d(planes, planes, kernel_size=3, padding=1, bias=False)), 586 | nn.ReLU(inplace=True), 587 | norm_layer(planes) 588 | ) 589 | 590 | def forward(self, x, trimapmask, sampleidx=None): 591 | # set outputs 592 | outs = [] 593 | 594 | # get outs[0] 595 | outs.append(self.shortcut[0](x)) 596 | 597 | # forward patch-embedding layer 598 | x = self.patch_embed(x) 599 | _, _, Wh, Ww = x.shape 600 | trimapmask = F.interpolate(trimapmask, scale_factor=1/4, mode='nearest') 601 | 602 | # get outs[1] 603 | outs.append(self.shortcut[1](F.upsample_bilinear(x, scale_factor=2.0))) 604 | 605 | # dropout 606 | x = x.flatten(2).transpose(1, 2) 607 | x = self.pos_drop(x) 608 | 609 | # get outs[2~5] 610 | for i in range(self.num_layers): 611 | layer = self.layers[i] 612 | 613 | trimapmask_ = F.interpolate(trimapmask, scale_factor=1/(pow(2, i)), mode='nearest') 614 | area_fg = trimapmask_[:, 0, :, :].unsqueeze(-1) # background area 615 | area_bg = trimapmask_[:, 2, :, :].unsqueeze(-1) # foreground area 616 | area_uk = trimapmask_[:, 1, :, :].unsqueeze(-1) # unknown area 617 | 618 | x_out, H, W, x, Wh, Ww = layer(x, Wh, Ww, area_fg=area_fg, area_bg=area_bg, area_uk=area_uk) 619 | 620 | if i in self.out_indices: 621 | norm_layer = getattr(self, f'norm{i}') 622 | x_out = norm_layer(x_out) 623 | out = x_out.view(-1, H, W, self.num_features[i]).permute(0, 3, 1, 2).contiguous() 624 | out = self.shortcut[i+2](out) 625 | outs.append(out) 626 | 627 | return tuple(outs) 628 | 629 | def train(self, mode=True): 630 | super(MatteFormer, self).train(mode) 631 | 632 | 633 | if __name__ == '__main__': 634 | model = MatteFormer().cuda() 635 | print(model) 636 | 637 | out = model(torch.ones(2, 6, 512, 512).cuda(), torch.ones(2,3,512,512).cuda()) 638 | print(len(out)) 639 | 640 | print('MODEL DEBUG') -------------------------------------------------------------------------------- /networks/encoders/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/webtoon/matteformer/f09f090a7e8069f213ea2671c49c52516f755bb5/networks/encoders/__init__.py -------------------------------------------------------------------------------- /networks/generators.py: -------------------------------------------------------------------------------- 1 | import os 2 | import torch 3 | import torch.nn as nn 4 | from utils import CONFIG 5 | 6 | from networks import decoders 7 | from networks.encoders.MatteFormer import MatteFormer 8 | 9 | 10 | def get_generator(is_train=True): 11 | generator = Generator_MatteFormer(is_train=is_train) 12 | return generator 13 | 14 | 15 | class Generator_MatteFormer(nn.Module): 16 | 17 | def __init__(self, is_train=True): 18 | 19 | super(Generator_MatteFormer, self).__init__() 20 | self.encoder = MatteFormer(embed_dim=96, 21 | depths=[2,2,6,2], # tiny-model 22 | num_heads=[3,6,12,24], 23 | window_size=7, 24 | mlp_ratio=4.0, 25 | qkv_bias=True, 26 | qk_scale=None, 27 | drop_rate=0.0, 28 | attn_drop_rate=0.0, 29 | drop_path_rate=0.3, 30 | patch_norm=True, 31 | use_checkpoint=False 32 | ) 33 | # original 34 | self.decoder = decoders.__dict__['res_shortcut_decoder']() 35 | 36 | if is_train: 37 | self.init_pretrained_weight(pretrained_path=CONFIG.model.imagenet_pretrain_path) # MatteFormer 38 | 39 | def init_pretrained_weight(self, pretrained_path=None): 40 | if not os.path.isfile(pretrained_path): 41 | print('Please Check your Pretrained weight path.. file not exist : {}'.format(pretrained_path)) 42 | exit() 43 | 44 | weight = torch.load(pretrained_path)['model'] 45 | 46 | # [1] get backbone weights 47 | weight_ = {} 48 | for i, (k, v) in enumerate(weight.items()): 49 | head = k.split('.')[0] 50 | if head in ['patch_embed', 'layers']: 51 | if 'attn_mask' in k: 52 | print('[{}/{}] {} will be ignored'.format(i, len(weight.items()), k)) 53 | continue 54 | weight_.update({k: v}) 55 | else: 56 | print('[{}/{}] {} will be ignored'.format(i, len(weight.items()), k)) 57 | 58 | patch_embed_weight = weight_['patch_embed.proj.weight'] 59 | patch_embed_weight_new = torch.nn.init.xavier_normal_(torch.randn(96, (3 + 3), 4, 4).cuda()) 60 | patch_embed_weight_new[:, :3, :, :].copy_(patch_embed_weight) 61 | weight_['patch_embed.proj.weight'] = patch_embed_weight_new 62 | 63 | attn_layers = [k for k, v in weight_.items() if 'attn.relative_position_bias_table' in k] 64 | for layer_name in attn_layers: 65 | pos_bias = weight_[layer_name] 66 | n_bias, n_head = pos_bias.shape 67 | 68 | layer_idx, block_idx = int(layer_name.split('.')[1]), int(layer_name.split('.')[3]) 69 | n_prior = block_idx + 1 70 | pos_bias_new = torch.nn.init.xavier_normal_(torch.randn(n_bias + n_prior*3, n_head)) 71 | 72 | pos_bias_new[:n_bias, :] = pos_bias 73 | weight_[layer_name] = pos_bias_new 74 | 75 | attn_layers = [k for k, v in weight_.items() if 'attn.relative_position_index' in k] 76 | for layer_name in attn_layers: 77 | pos_index = weight_[layer_name] 78 | 79 | layer_idx, block_idx = int(layer_name.split('.')[1]), int(layer_name.split('.')[3]) 80 | n_prior = block_idx + 1 81 | 82 | num_patch = 49 83 | last_idx = 169 84 | pos_index_new = torch.ones((num_patch, num_patch + n_prior*3)).long() * last_idx 85 | pos_index_new[:num_patch, :num_patch] = pos_index 86 | for i in range(n_prior): 87 | for j in range(3): 88 | pos_index_new[:, num_patch + i*3 + j:num_patch + i*3 +j +1] = last_idx + i*3 + j 89 | weight_[layer_name] = pos_index_new 90 | 91 | self.encoder.load_state_dict(weight_, strict=False) 92 | print('load pretrained model done') 93 | 94 | def forward(self, image, trimap): 95 | inp = torch.cat((image, trimap), axis=1) 96 | x = self.encoder(inp, trimap) 97 | embedding = x[-1] 98 | outs = self.decoder(embedding, x[:-1]) 99 | return outs 100 | 101 | 102 | if __name__ == '__main__': 103 | 104 | img = torch.ones([2, 3, 512, 512]).cuda() 105 | tri = torch.ones([2, 3, 512, 512]).cuda() 106 | 107 | generator = Generator_MatteFormer().cuda() 108 | 109 | inp1 = torch.Tensor(2, 3, 512, 512).cuda() 110 | inp2 = torch.ones(2, 3, 512, 512).cuda() 111 | out = generator(inp1, inp2) 112 | 113 | print('Done') 114 | -------------------------------------------------------------------------------- /networks/ops.py: -------------------------------------------------------------------------------- 1 | import torch 2 | from torch import nn 3 | from torch.nn import Parameter 4 | 5 | 6 | def l2normalize(v, eps=1e-12): 7 | return v / (v.norm() + eps) 8 | 9 | 10 | class SpectralNorm(nn.Module): 11 | """ 12 | Based on https://github.com/heykeetae/Self-Attention-GAN/blob/master/spectral.py 13 | and add _noupdate_u_v() for evaluation 14 | """ 15 | def __init__(self, module, name='weight', power_iterations=1): 16 | super(SpectralNorm, self).__init__() 17 | self.module = module 18 | self.name = name 19 | self.power_iterations = power_iterations 20 | if not self._made_params(): 21 | self._make_params() 22 | 23 | def _update_u_v(self): 24 | u = getattr(self.module, self.name + "_u") 25 | v = getattr(self.module, self.name + "_v") 26 | w = getattr(self.module, self.name + "_bar") 27 | 28 | height = w.data.shape[0] 29 | for _ in range(self.power_iterations): 30 | v.data = l2normalize(torch.mv(torch.t(w.view(height,-1).data), u.data)) 31 | u.data = l2normalize(torch.mv(w.view(height,-1).data, v.data)) 32 | 33 | sigma = u.dot(w.view(height, -1).mv(v)) 34 | setattr(self.module, self.name, w / sigma.expand_as(w)) 35 | 36 | def _noupdate_u_v(self): 37 | u = getattr(self.module, self.name + "_u") 38 | v = getattr(self.module, self.name + "_v") 39 | w = getattr(self.module, self.name + "_bar") 40 | 41 | height = w.data.shape[0] 42 | sigma = u.dot(w.view(height, -1).mv(v)) 43 | setattr(self.module, self.name, w / sigma.expand_as(w)) 44 | 45 | def _made_params(self): 46 | try: 47 | u = getattr(self.module, self.name + "_u") 48 | v = getattr(self.module, self.name + "_v") 49 | w = getattr(self.module, self.name + "_bar") 50 | return True 51 | except AttributeError: 52 | return False 53 | 54 | def _make_params(self): 55 | w = getattr(self.module, self.name) 56 | 57 | height = w.data.shape[0] 58 | width = w.view(height, -1).data.shape[1] 59 | 60 | u = Parameter(w.data.new(height).normal_(0, 1), requires_grad=False) 61 | v = Parameter(w.data.new(width).normal_(0, 1), requires_grad=False) 62 | u.data = l2normalize(u.data) 63 | v.data = l2normalize(v.data) 64 | w_bar = Parameter(w.data) 65 | 66 | del self.module._parameters[self.name] 67 | 68 | self.module.register_parameter(self.name + "_u", u) 69 | self.module.register_parameter(self.name + "_v", v) 70 | self.module.register_parameter(self.name + "_bar", w_bar) 71 | 72 | def forward(self, *args): 73 | # if torch.is_grad_enabled() and self.module.training: 74 | if self.module.training: 75 | self._update_u_v() 76 | else: 77 | self._noupdate_u_v() 78 | return self.module.forward(*args) 79 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | torch 2 | torchvision 3 | timm 4 | numpy 5 | opencv-python 6 | toml 7 | easydict 8 | pprint 9 | -------------------------------------------------------------------------------- /trainers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/webtoon/matteformer/f09f090a7e8069f213ea2671c49c52516f755bb5/trainers/__init__.py -------------------------------------------------------------------------------- /trainers/trainer.py: -------------------------------------------------------------------------------- 1 | import os 2 | import numpy as np 3 | import random 4 | 5 | import torch 6 | import torch.nn as nn 7 | import torch.nn.functional as F 8 | import torch.nn.utils as nn_utils 9 | import torch.backends.cudnn as cudnn 10 | from torch.nn import SyncBatchNorm 11 | import torch.optim.lr_scheduler as lr_scheduler 12 | from torch.nn.parallel import DistributedDataParallel 13 | 14 | import utils 15 | from utils import CONFIG 16 | import networks 17 | 18 | 19 | class Trainer(object): 20 | 21 | def __init__(self, 22 | train_dataloader, 23 | test_dataloader, 24 | logger): 25 | 26 | cudnn.benchmark = True 27 | 28 | self.train_dataloader = train_dataloader 29 | self.test_dataloader = test_dataloader 30 | self.logger = logger 31 | 32 | self.model_config = CONFIG.model 33 | self.train_config = CONFIG.train 34 | self.log_config = CONFIG.log 35 | self.loss_dict = {'rec': None, 36 | 'comp': None, 37 | 'lap': None, } 38 | self.test_loss_dict = {'rec': None, 39 | 'mse': None, 40 | 'sad': None} 41 | 42 | self.gauss_filter = torch.tensor([[1., 4., 6., 4., 1.], 43 | [4., 16., 24., 16., 4.], 44 | [6., 24., 36., 24., 6.], 45 | [4., 16., 24., 16., 4.], 46 | [1., 4., 6., 4., 1.]]).cuda() 47 | self.gauss_filter /= 256. 48 | self.gauss_filter = self.gauss_filter.repeat(1, 1, 1, 1) 49 | 50 | self.build_model() 51 | self.resume_step = None 52 | self.best_loss = {'mse':1e+8, 'sad':1e+8} 53 | 54 | utils.print_network(self.G, CONFIG.version) 55 | 56 | def build_model(self): 57 | self.G = networks.get_generator() 58 | self.G.cuda() 59 | 60 | if CONFIG.dist: 61 | self.logger.info("Using pytorch synced BN") 62 | self.G = SyncBatchNorm.convert_sync_batchnorm(self.G) 63 | 64 | self.G_optimizer = torch.optim.Adam(self.G.parameters(), 65 | lr=self.train_config.G_lr, 66 | betas=[self.train_config.beta1, self.train_config.beta2]) 67 | 68 | if CONFIG.dist: 69 | # SyncBatchNorm only supports DistributedDataParallel with single GPU per process 70 | self.G = DistributedDataParallel(self.G, device_ids=[CONFIG.local_rank], output_device=CONFIG.local_rank) 71 | else: 72 | self.G = nn.DataParallel(self.G) 73 | 74 | self.build_lr_scheduler() 75 | 76 | def build_lr_scheduler(self): 77 | """Build cosine learning rate scheduler.""" 78 | self.G_scheduler = lr_scheduler.CosineAnnealingLR(self.G_optimizer, 79 | T_max=self.train_config.total_step 80 | - self.train_config.warmup_step) 81 | 82 | def reset_grad(self): 83 | """Reset the gradient buffers.""" 84 | self.G_optimizer.zero_grad() 85 | 86 | def train(self): 87 | data_iter = iter(self.train_dataloader) 88 | 89 | if self.train_config.resume_checkpoint: 90 | start = self.resume_step + 1 91 | else: 92 | start = 0 93 | 94 | moving_max_grad = 0 95 | moving_grad_moment = 0.999 96 | 97 | for step in range(start, self.train_config.total_step + 1): 98 | try: 99 | image_dict = next(data_iter) 100 | except: 101 | data_iter = iter(self.train_dataloader) 102 | image_dict = next(data_iter) 103 | 104 | image, alpha, trimap = image_dict['image'], image_dict['alpha'], image_dict['trimap'] 105 | image = image.cuda() 106 | alpha = alpha.cuda() 107 | trimap = trimap.cuda() 108 | fg_norm, bg_norm = image_dict['fg'].cuda(), image_dict['bg'].cuda() 109 | 110 | self.G.train() 111 | loss = 0 112 | 113 | """===== Update Learning Rate =====""" 114 | if step < self.train_config.warmup_step and self.train_config.resume_checkpoint is None: 115 | cur_G_lr = utils.warmup_lr(self.train_config.G_lr, step + 1, self.train_config.warmup_step) 116 | utils.update_lr(cur_G_lr, self.G_optimizer) 117 | 118 | else: 119 | self.G_scheduler.step() 120 | cur_G_lr = self.G_scheduler.get_lr()[0] 121 | 122 | """===== Forward G =====""" 123 | pred = self.G(image, trimap) 124 | alpha_pred_os1, alpha_pred_os4, alpha_pred_os8 = pred['alpha_os1'], pred['alpha_os4'], pred['alpha_os8'] 125 | 126 | weight_os8 = utils.get_unknown_tensor(trimap) 127 | weight_os8[...] = 1 128 | 129 | if step < self.train_config.warmup_step: 130 | weight_os4 = utils.get_unknown_tensor(trimap) 131 | weight_os1 = utils.get_unknown_tensor(trimap) 132 | 133 | elif step < self.train_config.warmup_step * 3: 134 | if random.randint(0, 1) == 0: 135 | weight_os4 = utils.get_unknown_tensor(trimap) 136 | weight_os1 = utils.get_unknown_tensor(trimap) 137 | else: 138 | weight_os4 = utils.get_unknown_tensor_from_pred(alpha_pred_os8, rand_width=CONFIG.model.self_refine_width1, train_mode=True) 139 | alpha_pred_os4[weight_os4 == 0] = alpha_pred_os8[weight_os4 == 0] 140 | weight_os1 = utils.get_unknown_tensor_from_pred(alpha_pred_os4, rand_width=CONFIG.model.self_refine_width2, train_mode=True) 141 | alpha_pred_os1[weight_os1 == 0] = alpha_pred_os4[weight_os1 == 0] 142 | else: 143 | weight_os4 = utils.get_unknown_tensor_from_pred(alpha_pred_os8, rand_width=CONFIG.model.self_refine_width1, train_mode=True) 144 | alpha_pred_os4[weight_os4 == 0] = alpha_pred_os8[weight_os4 == 0] 145 | weight_os1 = utils.get_unknown_tensor_from_pred(alpha_pred_os4, rand_width=CONFIG.model.self_refine_width2, train_mode=True) 146 | alpha_pred_os1[weight_os1 == 0] = alpha_pred_os4[weight_os1 == 0] 147 | 148 | """===== Calculate Loss =====""" 149 | if self.train_config.rec_weight > 0: 150 | self.loss_dict['rec'] = (self.regression_loss(alpha_pred_os1, alpha, loss_type='l1', weight=weight_os1) * 2 + \ 151 | self.regression_loss(alpha_pred_os4, alpha, loss_type='l1', weight=weight_os4) * 1 + \ 152 | self.regression_loss(alpha_pred_os8, alpha, loss_type='l1', weight=weight_os8) * 1) / 5.0 * self.train_config.rec_weight 153 | 154 | if self.train_config.comp_weight > 0: 155 | self.loss_dict['comp'] = (self.composition_loss(alpha_pred_os1, fg_norm, bg_norm, image, weight=weight_os1) * 2 + \ 156 | self.composition_loss(alpha_pred_os4, fg_norm, bg_norm, image, weight=weight_os4) * 1 + \ 157 | self.composition_loss(alpha_pred_os8, fg_norm, bg_norm, image, weight=weight_os8) * 1) / 5.0 * self.train_config.comp_weight 158 | 159 | if self.train_config.lap_weight > 0: 160 | self.loss_dict['lap'] = (self.lap_loss(logit=alpha_pred_os1, target=alpha, gauss_filter=self.gauss_filter, loss_type='l1', weight=weight_os1) * 2 + \ 161 | self.lap_loss(logit=alpha_pred_os4, target=alpha, gauss_filter=self.gauss_filter, loss_type='l1', weight=weight_os4) * 1 + \ 162 | self.lap_loss(logit=alpha_pred_os8, target=alpha, gauss_filter=self.gauss_filter, loss_type='l1', weight=weight_os8) * 1) / 5.0 * self.train_config.lap_weight 163 | 164 | for loss_key in self.loss_dict.keys(): 165 | if self.loss_dict[loss_key] is not None and loss_key in ['rec', 'comp', 'lap']: 166 | loss += self.loss_dict[loss_key] 167 | 168 | """===== Back Propagate =====""" 169 | self.reset_grad() 170 | loss.backward() 171 | 172 | """===== Clip Large Gradient =====""" 173 | if self.train_config.clip_grad: 174 | if moving_max_grad == 0: 175 | moving_max_grad = nn_utils.clip_grad_norm_(self.G.parameters(), 1e+6) 176 | max_grad = moving_max_grad 177 | else: 178 | max_grad = nn_utils.clip_grad_norm_(self.G.parameters(), 2 * moving_max_grad) 179 | moving_max_grad = moving_max_grad * moving_grad_moment + max_grad * (1 - moving_grad_moment) 180 | 181 | """===== Update Parameters =====""" 182 | self.G_optimizer.step() 183 | 184 | """===== Write Log =====""" 185 | # stdout log 186 | if step % self.log_config.logging_step == 0: 187 | self.write_log(loss, step, image, trimap, cur_G_lr) 188 | 189 | """===== TEST =====""" 190 | if ((step % self.train_config.val_step) == 0 or step == self.train_config.total_step) and step > start: 191 | self.test(step, start) 192 | 193 | def test(self, step, start): 194 | self.G.eval() 195 | test_loss = 0 196 | log_info = "" 197 | 198 | self.test_loss_dict['mse'] = 0 199 | self.test_loss_dict['sad'] = 0 200 | for loss_key in self.loss_dict.keys(): 201 | if loss_key in self.test_loss_dict and self.loss_dict[loss_key] is not None: 202 | self.test_loss_dict[loss_key] = 0 203 | 204 | with torch.no_grad(): 205 | for idx, image_dict in enumerate(self.test_dataloader): 206 | image, alpha, trimap = image_dict['image'], image_dict['alpha'], image_dict['trimap'] 207 | alpha_shape = image_dict['alpha_shape'] 208 | image = image.cuda() 209 | alpha = alpha.cuda() 210 | trimap = trimap.cuda() 211 | 212 | pred = self.G(image, trimap) 213 | 214 | alpha_pred_os1, alpha_pred_os4, alpha_pred_os8 = pred['alpha_os1'], pred['alpha_os4'], pred['alpha_os8'] 215 | alpha_pred = alpha_pred_os8.clone().detach() 216 | weight_os4 = utils.get_unknown_tensor_from_pred(alpha_pred, rand_width=CONFIG.model.self_refine_width1, train_mode=False) 217 | alpha_pred[weight_os4 > 0] = alpha_pred_os4[weight_os4 > 0] 218 | weight_os1 = utils.get_unknown_tensor_from_pred(alpha_pred, rand_width=CONFIG.model.self_refine_width2, train_mode=False) 219 | alpha_pred[weight_os1 > 0] = alpha_pred_os1[weight_os1 > 0] 220 | 221 | h, w = alpha_shape 222 | alpha_pred = alpha_pred[..., :h, :w] 223 | 224 | trimap = trimap[..., :h, :w] 225 | 226 | weight = utils.get_unknown_tensor(trimap) # get unknown region (trimap) 227 | # weight[...] = 1 # get whole region 228 | 229 | # value of MSE/SAD here is different from test.py and matlab version 230 | self.test_loss_dict['mse'] += self.mse(((alpha_pred * 255.).int()).float() / 255., alpha, weight) 231 | # self.test_loss_dict['mse'] += self.mse(alpha_pred, alpha, weight) 232 | self.test_loss_dict['sad'] += self.sad(alpha_pred, alpha, weight) 233 | 234 | if self.train_config.rec_weight > 0: 235 | self.test_loss_dict['rec'] += \ 236 | self.regression_loss(alpha_pred, alpha, weight=weight) * self.train_config.rec_weight 237 | 238 | # reduce losses from GPUs 239 | if CONFIG.dist: 240 | self.test_loss_dict = utils.reduce_tensor_dict(self.test_loss_dict, mode='mean') 241 | 242 | """===== Write Log =====""" 243 | # stdout log 244 | for loss_key in self.test_loss_dict.keys(): 245 | if self.test_loss_dict[loss_key] is not None: 246 | self.test_loss_dict[loss_key] /= len(self.test_dataloader) 247 | # logging 248 | log_info += loss_key.upper() + ": {:.4f} ".format(self.test_loss_dict[loss_key]) 249 | 250 | if loss_key in ['rec']: 251 | test_loss += self.test_loss_dict[loss_key] 252 | 253 | self.logger.info("TEST: LOSS: {:.4f} ".format(test_loss) + log_info) 254 | 255 | """===== Save Model =====""" 256 | if (step % self.log_config.checkpoint_step == 0 or step == self.train_config.total_step) \ 257 | and CONFIG.local_rank == 0 and (step > start): 258 | self.logger.info('Saving the trained models from step {}...'.format(iter)) 259 | self.save_model("latest_model", step, self.best_loss) 260 | 261 | if self.test_loss_dict['mse'] < self.best_loss['mse']: 262 | self.best_loss['mse'] = self.test_loss_dict['mse'] 263 | self.best_loss['sad'] = self.test_loss_dict['sad'] 264 | self.save_model("best_model_mse", step, self.best_loss) 265 | 266 | torch.cuda.empty_cache() 267 | 268 | def write_log(self, loss, step, image, trimap, cur_G_lr): 269 | log_info= '' 270 | 271 | # reduce losses from GPUs 272 | if CONFIG.dist: 273 | self.loss_dict = utils.reduce_tensor_dict(self.loss_dict, mode='mean') 274 | loss = utils.reduce_tensor(loss) 275 | 276 | # create logging information 277 | for loss_key in self.loss_dict.keys(): 278 | if self.loss_dict[loss_key] is not None: 279 | log_info += loss_key.upper() + ": {:.4f}, ".format(self.loss_dict[loss_key]) 280 | 281 | self.logger.debug("Image tensor shape: {}. Trimap tensor shape: {}".format(image.shape, trimap.shape)) 282 | log_info = "[{}/{}], ".format(step, self.train_config.total_step) + log_info 283 | log_info += "lr: {:6f}".format(cur_G_lr) 284 | self.logger.info(log_info) 285 | 286 | def save_model(self, checkpoint_name, iter, loss): 287 | """Restore the trained generator and discriminator.""" 288 | torch.save({ 289 | 'iter': iter, 290 | 'loss': loss, 291 | 'state_dict': self.G.state_dict(), 292 | 'opt_state_dict': self.G_optimizer.state_dict(), 293 | 'lr_state_dict': self.G_scheduler.state_dict() 294 | }, os.path.join(self.log_config.checkpoint_path, '{}.pth'.format(checkpoint_name))) 295 | self.logger.info('Saving models in step {} iter... : {}'.format(iter, '{}.pth'.format(checkpoint_name))) 296 | 297 | @staticmethod 298 | def mse(logit, target, weight): 299 | # return F.mse_loss(logit * weight, target * weight, reduction='sum') / (torch.sum(weight) + 1e-8) 300 | return Trainer.regression_loss(logit, target, loss_type='l2', weight=weight) 301 | 302 | @staticmethod 303 | def sad(logit, target, weight): 304 | return F.l1_loss(logit * weight, target * weight, reduction='sum') / 1000 305 | 306 | @staticmethod 307 | def regression_loss(logit, target, loss_type='l1', weight=None): 308 | """ 309 | Alpha reconstruction loss 310 | :param logit: 311 | :param target: 312 | :param loss_type: "l1" or "l2" 313 | :param weight: tensor with shape [N,1,H,W] weights for each pixel 314 | :return: 315 | """ 316 | if weight is None: 317 | if loss_type == 'l1': 318 | return F.l1_loss(logit, target) 319 | elif loss_type == 'l2': 320 | return F.mse_loss(logit, target) 321 | else: 322 | raise NotImplementedError("NotImplemented loss type {}".format(loss_type)) 323 | else: 324 | if loss_type == 'l1': 325 | return F.l1_loss(logit * weight, target * weight, reduction='sum') / (torch.sum(weight) + 1e-8) 326 | elif loss_type == 'l2': 327 | return F.mse_loss(logit * weight, target * weight, reduction='sum') / (torch.sum(weight) + 1e-8) 328 | else: 329 | raise NotImplementedError("NotImplemented loss type {}".format(loss_type)) 330 | 331 | @staticmethod 332 | def composition_loss(alpha, fg, bg, image, weight, loss_type='l1'): 333 | """ 334 | Alpha composition loss 335 | """ 336 | merged = fg * alpha + bg * (1 - alpha) 337 | return Trainer.regression_loss(merged, image, loss_type=loss_type, weight=weight) 338 | 339 | @staticmethod 340 | def lap_loss(logit, target, gauss_filter, loss_type='l1', weight=None): 341 | ''' 342 | Based on FBA Matting implementation: 343 | https://gist.github.com/MarcoForte/a07c40a2b721739bb5c5987671aa5270 344 | ''' 345 | 346 | def conv_gauss(x, kernel): 347 | x = F.pad(x, (2, 2, 2, 2), mode='reflect') 348 | x = F.conv2d(x, kernel, groups=x.shape[1]) 349 | return x 350 | 351 | def downsample(x): 352 | return x[:, :, ::2, ::2] 353 | 354 | def upsample(x, kernel): 355 | N, C, H, W = x.shape 356 | cc = torch.cat([x, torch.zeros(N, C, H, W).cuda()], dim=3) 357 | cc = cc.view(N, C, H * 2, W) 358 | cc = cc.permute(0, 1, 3, 2) 359 | cc = torch.cat([cc, torch.zeros(N, C, W, H * 2).cuda()], dim=3) 360 | cc = cc.view(N, C, W * 2, H * 2) 361 | x_up = cc.permute(0, 1, 3, 2) 362 | return conv_gauss(x_up, kernel=4 * gauss_filter) 363 | 364 | def lap_pyramid(x, kernel, max_levels=3): 365 | current = x 366 | pyr = [] 367 | for level in range(max_levels): 368 | filtered = conv_gauss(current, kernel) 369 | down = downsample(filtered) 370 | up = upsample(down, kernel) 371 | diff = current - up 372 | pyr.append(diff) 373 | current = down 374 | return pyr 375 | 376 | def weight_pyramid(x, max_levels=3): 377 | current = x 378 | pyr = [] 379 | for level in range(max_levels): 380 | down = downsample(current) 381 | pyr.append(current) 382 | current = down 383 | return pyr 384 | 385 | pyr_logit = lap_pyramid(x=logit, kernel=gauss_filter, max_levels=5) 386 | pyr_target = lap_pyramid(x=target, kernel=gauss_filter, max_levels=5) 387 | if weight is not None: 388 | pyr_weight = weight_pyramid(x=weight, max_levels=5) 389 | return sum(Trainer.regression_loss(A[0], A[1], loss_type=loss_type, weight=A[2]) * (2 ** i) for i, A in 390 | enumerate(zip(pyr_logit, pyr_target, pyr_weight))) 391 | else: 392 | return sum(Trainer.regression_loss(A[0], A[1], loss_type=loss_type, weight=None) * (2 ** i) for i, A in 393 | enumerate(zip(pyr_logit, pyr_target))) -------------------------------------------------------------------------------- /utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .logger import * 2 | from .config import * 3 | from .util import * 4 | from .evaluate import * -------------------------------------------------------------------------------- /utils/config.py: -------------------------------------------------------------------------------- 1 | from easydict import EasyDict 2 | 3 | # Base default config 4 | CONFIG = EasyDict({}) 5 | # to indicate this is a default setting, should not be changed by user 6 | CONFIG.is_default = True 7 | CONFIG.version = "baseline" 8 | CONFIG.phase = "train" 9 | # distributed training 10 | CONFIG.dist = False 11 | # global variables which will be assigned in the runtime 12 | CONFIG.local_rank = 0 13 | CONFIG.gpu = 0 14 | CONFIG.world_size = 1 15 | 16 | # Model config 17 | CONFIG.model = EasyDict({}) 18 | # use pretrained checkpoint as encoder 19 | CONFIG.model.imagenet_pretrain = True 20 | CONFIG.model.imagenet_pretrain_path = "" 21 | CONFIG.model.batch_size = 16 22 | # one-hot or class, choice: [3, 1] 23 | CONFIG.model.mask_channel = 1 24 | CONFIG.model.trimap_channel = 3 25 | 26 | # hyper-parameter for refinement 27 | CONFIG.model.self_refine_width1 = 30 28 | CONFIG.model.self_refine_width2 = 15 29 | 30 | # Model -> Architecture config 31 | CONFIG.model.arch = EasyDict({}) 32 | # definition in networks/encoders/__init__.py and networks/encoders/__init__.py 33 | CONFIG.model.arch.name = "MatteFormer" 34 | # predefined for GAN structure 35 | CONFIG.model.arch.discriminator = None 36 | 37 | 38 | # Dataloader config 39 | CONFIG.data = EasyDict({}) 40 | CONFIG.data.cutmask_prob = 0 41 | CONFIG.data.workers = 0 42 | # data path for training and validation in training phase 43 | CONFIG.data.train_fg = None 44 | CONFIG.data.train_alpha = None 45 | CONFIG.data.train_bg = None 46 | CONFIG.data.test_merged = None 47 | CONFIG.data.test_alpha = None 48 | CONFIG.data.test_trimap = None 49 | # feed forward image size (untested) 50 | CONFIG.data.crop_size = 512 51 | # composition of two foregrounds, affine transform, crop and HSV jitter 52 | CONFIG.data.real_world_aug = False 53 | CONFIG.data.augmentation = True 54 | CONFIG.data.random_interp = True 55 | 56 | 57 | # Training config 58 | CONFIG.train = EasyDict({}) 59 | CONFIG.train.total_step = 100000 60 | CONFIG.train.warmup_step = 5000 61 | CONFIG.train.val_step = 1000 62 | # basic learning rate of optimizer 63 | CONFIG.train.G_lr = 1e-3 64 | # beta1 and beta2 for Adam 65 | CONFIG.train.beta1 = 0.5 66 | CONFIG.train.beta2 = 0.999 67 | # weight of different losses 68 | CONFIG.train.rec_weight = 1 69 | CONFIG.train.comp_weight = 1 70 | CONFIG.train.lap_weight = 1 71 | # clip large gradient 72 | CONFIG.train.clip_grad = True 73 | # resume the training (checkpoint file name) 74 | CONFIG.train.resume_checkpoint = None 75 | # reset the learning rate (this option will reset the optimizer and learning rate scheduler and ignore warmup) 76 | CONFIG.train.reset_lr = False 77 | 78 | 79 | # Logging config 80 | CONFIG.log = EasyDict({}) 81 | CONFIG.log.experiment_root = "." 82 | CONFIG.log.logging_path = "./logs/stdout" 83 | CONFIG.log.logging_step = 10 84 | CONFIG.log.logging_level = "DEBUG" 85 | CONFIG.log.checkpoint_path = "./checkpoints" 86 | CONFIG.log.checkpoint_step = 10000 87 | 88 | 89 | def load_config(custom_config, default_config=CONFIG, prefix="CONFIG"): 90 | """ 91 | This function will recursively overwrite the default config by a custom config 92 | :param default_config: 93 | :param custom_config: parsed from config/config.toml 94 | :param prefix: prefix for config key 95 | :return: None 96 | """ 97 | if "is_default" in default_config: 98 | default_config.is_default = False 99 | 100 | for key in custom_config.keys(): 101 | full_key = ".".join([prefix, key]) 102 | if key not in default_config: 103 | raise NotImplementedError("Unknown config key: {}".format(full_key)) 104 | elif isinstance(custom_config[key], dict): 105 | if isinstance(default_config[key], dict): 106 | load_config(default_config=default_config[key], 107 | custom_config=custom_config[key], 108 | prefix=full_key) 109 | else: 110 | raise ValueError("{}: Expected {}, got dict instead.".format(full_key, type(custom_config[key]))) 111 | else: 112 | if isinstance(default_config[key], dict): 113 | raise ValueError("{}: Expected dict, got {} instead.".format(full_key, type(custom_config[key]))) 114 | else: 115 | default_config[key] = custom_config[key] 116 | 117 | 118 | -------------------------------------------------------------------------------- /utils/evaluate.py: -------------------------------------------------------------------------------- 1 | 2 | import numpy as np 3 | 4 | 5 | def compute_mse_loss(pred, target, trimap): 6 | error_map = (pred - target) / 255.0 7 | loss = np.sum((error_map ** 2) * (trimap == 128)) / (np.sum(trimap == 128) + 1e-8) 8 | 9 | return loss 10 | 11 | 12 | def compute_sad_loss(pred, target, trimap): 13 | error_map = np.abs((pred - target) / 255.0) 14 | loss = np.sum(error_map * (trimap == 128)) 15 | 16 | return loss / 1000, np.sum(trimap == 128) / 1000 17 | 18 | -------------------------------------------------------------------------------- /utils/logger.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | import torch 4 | import logging 5 | import datetime 6 | import numpy as np 7 | from pprint import pprint 8 | from utils.config import CONFIG 9 | 10 | LEVELS = { 11 | "DEBUG": logging.DEBUG, 12 | "INFO": logging.INFO, 13 | "WARNING": logging.WARNING, 14 | "ERROR": logging.ERROR, 15 | "CRITICAL": logging.CRITICAL, 16 | } 17 | 18 | def make_color_wheel(): 19 | # from https://github.com/JiahuiYu/generative_inpainting/blob/master/inpaint_ops.py 20 | RY, YG, GC, CB, BM, MR = (15, 6, 4, 11, 13, 6) 21 | ncols = RY + YG + GC + CB + BM + MR 22 | colorwheel = np.zeros([ncols, 3]) 23 | col = 0 24 | # RY 25 | colorwheel[0:RY, 0] = 255 26 | colorwheel[0:RY, 1] = np.transpose(np.floor(255*np.arange(0, RY) / RY)) 27 | col += RY 28 | # YG 29 | colorwheel[col:col+YG, 0] = 255 - np.transpose(np.floor(255*np.arange(0, YG) / YG)) 30 | colorwheel[col:col+YG, 1] = 255 31 | col += YG 32 | # GC 33 | colorwheel[col:col+GC, 1] = 255 34 | colorwheel[col:col+GC, 2] = np.transpose(np.floor(255*np.arange(0, GC) / GC)) 35 | col += GC 36 | # CB 37 | colorwheel[col:col+CB, 1] = 255 - np.transpose(np.floor(255*np.arange(0, CB) / CB)) 38 | colorwheel[col:col+CB, 2] = 255 39 | col += CB 40 | # BM 41 | colorwheel[col:col+BM, 2] = 255 42 | colorwheel[col:col+BM, 0] = np.transpose(np.floor(255*np.arange(0, BM) / BM)) 43 | col += + BM 44 | # MR 45 | colorwheel[col:col+MR, 2] = 255 - np.transpose(np.floor(255 * np.arange(0, MR) / MR)) 46 | colorwheel[col:col+MR, 0] = 255 47 | return colorwheel 48 | 49 | 50 | COLORWHEEL = make_color_wheel() 51 | 52 | 53 | class MyLogger(logging.Logger): 54 | """ 55 | Only write log in the first subprocess 56 | """ 57 | def __init__(self, *args, **kwargs): 58 | super(MyLogger, self).__init__(*args, **kwargs) 59 | 60 | def _log(self, level, msg, args, exc_info=None, extra=None, stack_info=False): 61 | if CONFIG.local_rank == 0: 62 | super()._log(level, msg, args, exc_info, extra, stack_info) 63 | 64 | 65 | def get_logger(log_dir=None, logging_level="DEBUG"): 66 | """ 67 | Return a default build-in logger if log_file=None and 68 | Return a build-in logger which dump stdout to log_file if log_file is assigned 69 | :param log_file: logging file dumped from stdout 70 | :param logging_level: 71 | :return: Logger 72 | """ 73 | level = LEVELS[logging_level.upper()] 74 | exp_string = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S") 75 | 76 | logging.setLoggerClass(MyLogger) 77 | logger = logging.getLogger('Logger') 78 | logger.setLevel(level) 79 | # create formatter 80 | formatter = logging.Formatter('[%(asctime)s] %(levelname)s: %(message)s', datefmt='%m-%d %H:%M:%S') 81 | 82 | # create console handler 83 | ch = logging.StreamHandler() 84 | ch.setLevel(level) 85 | ch.setFormatter(formatter) 86 | # add the handlers to logger 87 | logger.addHandler(ch) 88 | 89 | # create file handler 90 | if log_dir is not None and CONFIG.local_rank == 0: 91 | log_file = os.path.join(log_dir, exp_string) 92 | fh = logging.FileHandler(log_file+'.log', mode='w') 93 | fh.setLevel(level) 94 | fh.setFormatter(formatter) 95 | logger.addHandler(fh) 96 | pprint(CONFIG, stream=fh.stream) 97 | 98 | return logger 99 | 100 | -------------------------------------------------------------------------------- /utils/util.py: -------------------------------------------------------------------------------- 1 | import os 2 | import cv2 3 | import torch 4 | import logging 5 | import numpy as np 6 | from utils.config import CONFIG 7 | import torch.distributed as dist 8 | import torch.nn.functional as F 9 | 10 | 11 | def make_dir(target_dir): 12 | """ 13 | Create dir if not exists 14 | """ 15 | if not os.path.exists(target_dir): 16 | os.makedirs(target_dir) 17 | 18 | 19 | def print_network(model, name): 20 | """ 21 | Print out the network information 22 | """ 23 | logger = logging.getLogger("Logger") 24 | num_params = 0 25 | for p in model.parameters(): 26 | num_params += p.numel() 27 | 28 | logger.info(model) 29 | logger.info(name) 30 | logger.info("Number of parameters: {}".format(num_params)) 31 | 32 | 33 | def update_lr(lr, optimizer): 34 | """ 35 | update learning rates 36 | """ 37 | for param_group in optimizer.param_groups: 38 | param_group['lr'] = lr 39 | 40 | 41 | def warmup_lr(init_lr, step, iter_num): 42 | """ 43 | Warm up learning rate 44 | """ 45 | return step/iter_num*init_lr 46 | 47 | 48 | def remove_prefix_state_dict(state_dict, prefix="module"): 49 | """ 50 | remove prefix from the key of pretrained state dict for Data-Parallel 51 | """ 52 | new_state_dict = {} 53 | first_state_name = list(state_dict.keys())[0] 54 | if not first_state_name.startswith(prefix): 55 | for key, value in state_dict.items(): 56 | new_state_dict[key] = state_dict[key].float() 57 | else: 58 | for key, value in state_dict.items(): 59 | new_state_dict[key[len(prefix)+1:]] = state_dict[key].float() 60 | return new_state_dict 61 | 62 | 63 | def get_unknown_tensor(trimap): 64 | """ 65 | get 1-channel unknown area tensor from the 3-channel/1-channel trimap tensor 66 | """ 67 | if CONFIG.model.trimap_channel == 3: 68 | weight = trimap[:, 1:2, :, :].float() 69 | else: 70 | weight = trimap.eq(1).float() 71 | return weight 72 | 73 | 74 | def reduce_tensor_dict(tensor_dict, mode='mean'): 75 | """ 76 | average tensor dict over different GPUs 77 | """ 78 | for key, tensor in tensor_dict.items(): 79 | if tensor is not None: 80 | tensor_dict[key] = reduce_tensor(tensor, mode) 81 | return tensor_dict 82 | 83 | 84 | def reduce_tensor(tensor, mode='mean'): 85 | """ 86 | average tensor over different GPUs 87 | """ 88 | rt = tensor.clone() 89 | dist.all_reduce(rt, op=dist.ReduceOp.SUM) 90 | if mode == 'mean': 91 | rt /= CONFIG.world_size 92 | elif mode == 'sum': 93 | pass 94 | else: 95 | raise NotImplementedError("reduce mode can only be 'mean' or 'sum'") 96 | return rt 97 | 98 | 99 | Kernels = [None] + [cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (size, size)) for size in range(1,30)] 100 | 101 | 102 | def get_unknown_tensor_from_pred(pred, rand_width=30, train_mode=True): 103 | ### pred: N, 1 ,H, W 104 | N, C, H, W = pred.shape 105 | pred = F.interpolate(pred, size=(640,640), mode='nearest') 106 | pred = pred.data.cpu().numpy() 107 | uncertain_area = np.ones_like(pred, dtype=np.uint8) 108 | uncertain_area[pred < 1.0/255.0] = 0 109 | uncertain_area[pred > 1-1.0/255.0] = 0 110 | 111 | for n in range(N): 112 | uncertain_area_ = uncertain_area[n,0,:,:] # H, W 113 | if train_mode: 114 | width = np.random.randint(1, rand_width) 115 | else: 116 | width = rand_width // 2 117 | uncertain_area_ = cv2.dilate(uncertain_area_, Kernels[width]) 118 | uncertain_area[n,0,:,:] = uncertain_area_ 119 | 120 | weight = np.zeros_like(uncertain_area) 121 | weight[uncertain_area == 1] = 1 122 | 123 | weight = np.array(weight, dtype=np.float) 124 | weight = torch.from_numpy(weight).cuda() 125 | 126 | weight = F.interpolate(weight, size=(H,W), mode='nearest') 127 | 128 | return weight --------------------------------------------------------------------------------