Added technique epic
This commit is contained in:
+1
-1
@@ -4,4 +4,4 @@ visual_results/*
|
||||
__pycache__/*
|
||||
project/__pycache__/*
|
||||
project/obfuscation/__pycache__/*
|
||||
models/*
|
||||
*.pyc
|
||||
Binary file not shown.
+2
-1
@@ -2,6 +2,7 @@ from obfuscation.block_black import Blackening
|
||||
from obfuscation.block_random import Randoming
|
||||
from obfuscation.block_white import Whitening
|
||||
from obfuscation.blurring import Blurring
|
||||
from obfuscation.epic import Epic
|
||||
#from obfuscation.fams import FAMS
|
||||
from obfuscation.pixelation import Pixelation
|
||||
|
||||
@@ -34,7 +35,7 @@ class Config:
|
||||
debug_show_preprocessing=False
|
||||
|
||||
obfuscation_techniques=[
|
||||
#FAMS(),
|
||||
Epic(),
|
||||
Blackening(),
|
||||
Randoming(),
|
||||
Blurring(),
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
yolo11m-pose.pt
|
||||
yolo11m-seg.pt
|
||||
@@ -0,0 +1,2 @@
|
||||
*.tar
|
||||
stuff/*
|
||||
Generated
+3
@@ -0,0 +1,3 @@
|
||||
# Default ignored files
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
@@ -0,0 +1,41 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<profile version="1.0">
|
||||
<option name="myName" value="Project Default" />
|
||||
<inspection_tool class="PyPackageRequirementsInspection" enabled="true" level="WARNING" enabled_by_default="true">
|
||||
<option name="ignoredPackages">
|
||||
<value>
|
||||
<list size="13">
|
||||
<item index="0" class="java.lang.String" itemvalue="scikit-image" />
|
||||
<item index="1" class="java.lang.String" itemvalue="opencv-contrib-python" />
|
||||
<item index="2" class="java.lang.String" itemvalue="pysimplegui" />
|
||||
<item index="3" class="java.lang.String" itemvalue="torch" />
|
||||
<item index="4" class="java.lang.String" itemvalue="numpy" />
|
||||
<item index="5" class="java.lang.String" itemvalue="torchvision" />
|
||||
<item index="6" class="java.lang.String" itemvalue="imgaug" />
|
||||
<item index="7" class="java.lang.String" itemvalue="imageio" />
|
||||
<item index="8" class="java.lang.String" itemvalue="tk" />
|
||||
<item index="9" class="java.lang.String" itemvalue="matplotlib" />
|
||||
<item index="10" class="java.lang.String" itemvalue="imutils" />
|
||||
<item index="11" class="java.lang.String" itemvalue="torchaudio" />
|
||||
<item index="12" class="java.lang.String" itemvalue="Pillow" />
|
||||
</list>
|
||||
</value>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="PyPep8Inspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||
<option name="ignoredErrors">
|
||||
<list>
|
||||
<option value="E501" />
|
||||
</list>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
<inspection_tool class="PyPep8NamingInspection" enabled="true" level="WEAK WARNING" enabled_by_default="true">
|
||||
<option name="ignoredErrors">
|
||||
<list>
|
||||
<option value="N802" />
|
||||
<option value="N806" />
|
||||
</list>
|
||||
</option>
|
||||
</inspection_tool>
|
||||
</profile>
|
||||
</component>
|
||||
@@ -0,0 +1,6 @@
|
||||
<component name="InspectionProjectProfileManager">
|
||||
<settings>
|
||||
<option name="USE_PROJECT_PROFILE" value="false" />
|
||||
<version value="1.0" />
|
||||
</settings>
|
||||
</component>
|
||||
Generated
+7
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectRootManager" version="2" project-jdk-name="Python 3.6 (motion-cosegmentation-master)" project-jdk-type="Python SDK" />
|
||||
<component name="PyCharmProfessionalAdvertiser">
|
||||
<option name="shown" value="true" />
|
||||
</component>
|
||||
</project>
|
||||
Generated
+8
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/motion-cosegmentation-master.iml" filepath="$PROJECT_DIR$/.idea/motion-cosegmentation-master.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="PYTHON_MODULE" version="4">
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<excludeFolder url="file://$MODULE_DIR$/venv" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
<component name="PyDocumentationSettings">
|
||||
<option name="format" value="PLAIN" />
|
||||
<option name="myDocStringFormat" value="Plain" />
|
||||
</component>
|
||||
</module>
|
||||
@@ -0,0 +1,185 @@
|
||||
## creative commons
|
||||
|
||||
# Attribution-NonCommercial 4.0 International
|
||||
|
||||
Creative Commons Corporation (“Creative Commons”) is not a law firm and does not provide legal services or legal advice. Distribution of Creative Commons public licenses does not create a lawyer-client or other relationship. Creative Commons makes its licenses and related information available on an “as-is” basis. Creative Commons gives no warranties regarding its licenses, any material licensed under their terms and conditions, or any related information. Creative Commons disclaims all liability for damages resulting from their use to the fullest extent possible.
|
||||
|
||||
### Using Creative Commons Public Licenses
|
||||
|
||||
Creative Commons public licenses provide a standard set of terms and conditions that creators and other rights holders may use to share original works of authorship and other material subject to copyright and certain other rights specified in the public license below. The following considerations are for informational purposes only, are not exhaustive, and do not form part of our licenses.
|
||||
|
||||
* __Considerations for licensors:__ Our public licenses are intended for use by those authorized to give the public permission to use material in ways otherwise restricted by copyright and certain other rights. Our licenses are irrevocable. Licensors should read and understand the terms and conditions of the license they choose before applying it. Licensors should also secure all rights necessary before applying our licenses so that the public can reuse the material as expected. Licensors should clearly mark any material not subject to the license. This includes other CC-licensed material, or material used under an exception or limitation to copyright. [More considerations for licensors](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensors).
|
||||
|
||||
* __Considerations for the public:__ By using one of our public licenses, a licensor grants the public permission to use the licensed material under specified terms and conditions. If the licensor’s permission is not necessary for any reason–for example, because of any applicable exception or limitation to copyright–then that use is not regulated by the license. Our licenses grant only permissions under copyright and certain other rights that a licensor has authority to grant. Use of the licensed material may still be restricted for other reasons, including because others have copyright or other rights in the material. A licensor may make special requests, such as asking that all changes be marked or described. Although not required by our licenses, you are encouraged to respect those requests where reasonable. [More considerations for the public](http://wiki.creativecommons.org/Considerations_for_licensors_and_licensees#Considerations_for_licensees).
|
||||
|
||||
## Creative Commons Attribution-NonCommercial 4.0 International Public License
|
||||
|
||||
By exercising the Licensed Rights (defined below), You accept and agree to be bound by the terms and conditions of this Creative Commons Attribution-NonCommercial 4.0 International Public License ("Public License"). To the extent this Public License may be interpreted as a contract, You are granted the Licensed Rights in consideration of Your acceptance of these terms and conditions, and the Licensor grants You such rights in consideration of benefits the Licensor receives from making the Licensed Material available under these terms and conditions.
|
||||
|
||||
### Section 1 – Definitions.
|
||||
|
||||
a. __Adapted Material__ means material subject to Copyright and Similar Rights that is derived from or based upon the Licensed Material and in which the Licensed Material is translated, altered, arranged, transformed, or otherwise modified in a manner requiring permission under the Copyright and Similar Rights held by the Licensor. For purposes of this Public License, where the Licensed Material is a musical work, performance, or sound recording, Adapted Material is always produced where the Licensed Material is synched in timed relation with a moving image.
|
||||
|
||||
b. __Adapter's License__ means the license You apply to Your Copyright and Similar Rights in Your contributions to Adapted Material in accordance with the terms and conditions of this Public License.
|
||||
|
||||
c. __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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
|
||||
|
||||
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.
|
||||
|
||||
h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
|
||||
|
||||
### Section 2 – Scope.
|
||||
|
||||
a. ___License grant.___
|
||||
|
||||
1. Subject to the terms and conditions of this Public License, the Licensor hereby grants You a worldwide, royalty-free, non-sublicensable, non-exclusive, irrevocable license to exercise the Licensed Rights in the Licensed Material to:
|
||||
|
||||
A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
|
||||
|
||||
B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
|
||||
|
||||
2. __Exceptions and Limitations.__ For the avoidance of doubt, where Exceptions and Limitations apply to Your use, this Public License does not apply, and You do not need to comply with its terms and conditions.
|
||||
|
||||
3. __Term.__ The term of this Public License is specified in Section 6(a).
|
||||
|
||||
4. __Media and formats; technical modifications allowed.__ The Licensor authorizes You to exercise the Licensed Rights in all media and formats whether now known or hereafter created, and to make technical modifications necessary to do so. The Licensor waives and/or agrees not to assert any right or authority to forbid You from making technical modifications necessary to exercise the Licensed Rights, including technical modifications necessary to circumvent Effective Technological Measures. For purposes of this Public License, simply making modifications authorized by this Section 2(a)(4) never produces Adapted Material.
|
||||
|
||||
5. __Downstream recipients.__
|
||||
|
||||
A. __Offer from the Licensor – Licensed Material.__ Every recipient of the Licensed Material automatically receives an offer from the Licensor to exercise the Licensed Rights under the terms and conditions of this Public License.
|
||||
|
||||
B. __No downstream restrictions.__ You may not offer or impose any additional or different terms or conditions on, or apply any Effective Technological Measures to, the Licensed Material if doing so restricts exercise of the Licensed Rights by any recipient of the Licensed Material.
|
||||
|
||||
6. __No endorsement.__ Nothing in this Public License constitutes or may be construed as permission to assert or imply that You are, or that Your use of the Licensed Material is, connected with, or sponsored, endorsed, or granted official status by, the Licensor or others designated to receive attribution as provided in Section 3(a)(1)(A)(i).
|
||||
|
||||
b. ___Other rights.___
|
||||
|
||||
1. Moral rights, such as the right of integrity, are not licensed under this Public License, nor are publicity, privacy, and/or other similar personality rights; however, to the extent possible, the Licensor waives and/or agrees not to assert any such rights held by the Licensor to the limited extent necessary to allow You to exercise the Licensed Rights, but not otherwise.
|
||||
|
||||
2. Patent and trademark rights are not licensed under this Public License.
|
||||
|
||||
3. To the extent possible, the Licensor waives any right to collect royalties from You for the exercise of the Licensed Rights, whether directly or through a collecting society under any voluntary or waivable statutory or compulsory licensing scheme. In all other cases the Licensor expressly reserves any right to collect such royalties, including when the Licensed Material is used other than for NonCommercial purposes.
|
||||
|
||||
### Section 3 – License Conditions.
|
||||
|
||||
Your exercise of the Licensed Rights is expressly made subject to the following conditions.
|
||||
|
||||
a. ___Attribution.___
|
||||
|
||||
1. If You Share the Licensed Material (including in modified form), You must:
|
||||
|
||||
A. retain the following if it is supplied by the Licensor with the Licensed Material:
|
||||
|
||||
i. identification of the creator(s) of the Licensed Material and any others designated to receive attribution, in any reasonable manner requested by the Licensor (including by pseudonym if designated);
|
||||
|
||||
ii. a copyright notice;
|
||||
|
||||
iii. a notice that refers to this Public License;
|
||||
|
||||
iv. a notice that refers to the disclaimer of warranties;
|
||||
|
||||
v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
|
||||
|
||||
B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
|
||||
|
||||
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.
|
||||
|
||||
2. You may satisfy the conditions in Section 3(a)(1) in any reasonable manner based on the medium, means, and context in which You Share the Licensed Material. For example, it may be reasonable to satisfy the conditions by providing a URI or hyperlink to a resource that includes the required information.
|
||||
|
||||
3. If requested by the Licensor, You must remove any of the information required by Section 3(a)(1)(A) to the extent reasonably practicable.
|
||||
|
||||
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.
|
||||
|
||||
### Section 4 – Sui Generis Database Rights.
|
||||
|
||||
Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
|
||||
|
||||
a. for the avoidance of doubt, Section 2(a)(1) grants You the right to extract, reuse, reproduce, and Share all or a substantial portion of the contents of the database for NonCommercial purposes only;
|
||||
|
||||
b. if You include all or a substantial portion of the database contents in a database in which You have Sui Generis Database Rights, then the database in which You have Sui Generis Database Rights (but not its individual contents) is Adapted Material; and
|
||||
|
||||
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.
|
||||
|
||||
For the avoidance of doubt, this Section 4 supplements and does not replace Your obligations under this Public License where the Licensed Rights include other Copyright and Similar Rights.
|
||||
|
||||
### Section 5 – Disclaimer of Warranties and Limitation of Liability.
|
||||
|
||||
a. __Unless otherwise separately undertaken by the Licensor, to the extent possible, the Licensor offers the Licensed Material as-is and as-available, and makes no representations or warranties of any kind concerning the Licensed Material, whether express, implied, statutory, or other. This includes, without limitation, warranties of title, merchantability, fitness for a particular purpose, non-infringement, absence of latent or other defects, accuracy, or the presence or absence of errors, whether or not known or discoverable. Where disclaimers of warranties are not allowed in full or in part, this disclaimer may not apply to You.__
|
||||
|
||||
b. __To the extent possible, in no event will the Licensor be liable to You on any legal theory (including, without limitation, negligence) or otherwise for any direct, special, indirect, incidental, consequential, punitive, exemplary, or other losses, costs, expenses, or damages arising out of this Public License or use of the Licensed Material, even if the Licensor has been advised of the possibility of such losses, costs, expenses, or damages. Where a limitation of liability is not allowed in full or in part, this limitation may not apply to You.__
|
||||
|
||||
c. The disclaimer of warranties and limitation of liability provided above shall be interpreted in a manner that, to the extent possible, most closely approximates an absolute disclaimer and waiver of all liability.
|
||||
|
||||
### Section 6 – Term and Termination.
|
||||
|
||||
a. This Public License applies for the term of the Copyright and Similar Rights licensed here. However, if You fail to comply with this Public License, then Your rights under this Public License terminate automatically.
|
||||
|
||||
b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
|
||||
|
||||
1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
|
||||
|
||||
2. upon express reinstatement by the Licensor.
|
||||
|
||||
For the avoidance of doubt, this Section 6(b) does not affect any right the Licensor may have to seek remedies for Your violations of this Public License.
|
||||
|
||||
c. For the avoidance of doubt, the Licensor may also offer the Licensed Material under separate terms or conditions or stop distributing the Licensed Material at any time; however, doing so will not terminate this Public License.
|
||||
|
||||
d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
|
||||
|
||||
### Section 7 – Other Terms and Conditions.
|
||||
|
||||
a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
|
||||
|
||||
b. Any arrangements, understandings, or agreements regarding the Licensed Material not stated herein are separate from and independent of the terms and conditions of this Public License.
|
||||
|
||||
### Section 8 – Interpretation.
|
||||
|
||||
a. For the avoidance of doubt, this Public License does not, and shall not be interpreted to, reduce, limit, restrict, or impose conditions on any use of the Licensed Material that could lawfully be made without permission under this Public License.
|
||||
|
||||
b. To the extent possible, if any provision of this Public License is deemed unenforceable, it shall be automatically reformed to the minimum extent necessary to make it enforceable. If the provision cannot be reformed, it shall be severed from this Public License without affecting the enforceability of the remaining terms and conditions.
|
||||
|
||||
c. No term or condition of this Public License will be waived and no failure to comply consented to unless expressly agreed to by the Licensor.
|
||||
|
||||
d. Nothing in this Public License constitutes or may be interpreted as a limitation upon, or waiver of, any privileges and immunities that apply to the Licensor or You, including from the legal processes of any jurisdiction or authority.
|
||||
|
||||
> Creative Commons is not a party to its public licenses. Notwithstanding, Creative Commons may elect to apply one of its public licenses to material it publishes and in those instances will be considered the “Licensor.” 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.
|
||||
>
|
||||
> Creative Commons may be contacted at creativecommons.org
|
||||
|
||||
--------------------------- LICENSE FOR Synchronized-BatchNorm-PyTorch --------------------------------
|
||||
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Jiayuan MAO
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,161 @@
|
||||
# Motion Supervised co-part Segmentation
|
||||
## [Arxiv](http://arxiv.org/abs/2004.03234) | [YouTube video](https://www.youtube.com/watch?v=RJ4Nj1wV5iA)
|
||||
|
||||
This repository contains the source code for the paper [Motion Supervised co-part Segmentation](http://arxiv.org/abs/2004.03234) by Aliaksandr Siarohin<sup>\*</sup>, [Subhankar Roy<sup>\*</sup>](https://scholar.google.com/citations?user=YfzgrDYAAAAJ&hl=en), [Stéphane Lathuilière](https://stelat.eu/), [Sergey Tulyakov](http://stulyakov.com), [Elisa Ricci](http://elisaricci.eu/) and [Nicu Sebe](http://disi.unitn.it/~sebe/).
|
||||
|
||||
<sup>\*</sup> - denotes equal contribution
|
||||
|
||||
Our method is a self-supervised deep learning method for co-part segmentation. Differently from previous works, our approach develops the idea that motion information inferred from videos can be leveraged to discover meaningful object parts. Our method can also perform video editing (aka part-swaps).
|
||||
|
||||
## Example segmentations
|
||||
|
||||
Unsupervised segmentations obtained with our method on <b>VoxCeleb</b>:
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td><image src="sup-mat/vox-seg-0.gif" width="256" /></td>
|
||||
<td><image src="sup-mat/vox-seg-1.gif" width="256"/></td>
|
||||
<td><image src="sup-mat/vox-seg-2.gif" width="256"/></td>
|
||||
<td><image src="sup-mat/vox-seg-3.gif" width="256"/></td>
|
||||
<td><image src="sup-mat/vox-seg-4.gif" width="256"/></td>
|
||||
<td><image src="sup-mat/vox-seg-5.gif" width="256"/></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
and <b>TaiChi</b> dataset:
|
||||
<table>
|
||||
<tr>
|
||||
<td><image src="sup-mat/taichi-seg-0.gif" width="256"/></td>
|
||||
<td><image src="sup-mat/taichi-seg-1.gif" width="256"/></td>
|
||||
<td><image src="sup-mat/taichi-seg-2.gif" width="256"/></td>
|
||||
<td><image src="sup-mat/taichi-seg-3.gif" width="256"/></td>
|
||||
<td><image src="sup-mat/taichi-seg-4.gif" width="256"/></td>
|
||||
<td><image src="sup-mat/taichi-seg-5.gif" width="256"/></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
## Example part-swaps
|
||||
|
||||
Part swaping with our method for VoxCeleb dataset. Each triplet shows source image, target video (with swap mask in the corner) and result:
|
||||
|
||||
<table style="width:100%;;padding-top:35%">
|
||||
<tr>
|
||||
<th colspan="3"> Hair Swap </th>
|
||||
<th colspan="3"> Beard Swap </th>
|
||||
<tr/>
|
||||
|
||||
|
||||
<tr>
|
||||
<td colspan="3"><image src="sup-mat/hair-line.gif" width="768"/></td>
|
||||
<td colspan="3"><image src="sup-mat/beard-line.gif" width="768"/></td>
|
||||
</tr>
|
||||
|
||||
<tr>
|
||||
<th colspan="3"> Eyes Swap </th>
|
||||
<th colspan="3"> Lips Swap </th>
|
||||
<tr/>
|
||||
|
||||
<tr>
|
||||
<td colspan="3"><image src="sup-mat/eye-line.gif" width="768"/></td>
|
||||
<td colspan="3"><image src="sup-mat/lips-line.gif" width="768"/></td>
|
||||
</tr>
|
||||
|
||||
|
||||
</table>
|
||||
|
||||
### Installation
|
||||
|
||||
We support ```python3```. To install the dependencies run:
|
||||
```
|
||||
pip install -r requirements.txt
|
||||
```
|
||||
|
||||
### YAML configs
|
||||
|
||||
There are several configuration (```config/dataset_name.yaml```) files one for each `dataset`. See ```config/taichi-sem-256.yaml``` to get description of each parameter.
|
||||
|
||||
### Pre-trained checkpoints
|
||||
Checkpoints can be found under following links: [yandex-disk](https://yadi.sk/d/2hTyhEcqo_5ruA) and [google-drive](https://drive.google.com/open?id=1SsBifjoM_qO0iFzb8wLlsz_4qW2j8dZe).
|
||||
|
||||
### Part-swap demo
|
||||
|
||||
To run a demo, download checkpoint and run the following command:
|
||||
```
|
||||
python part_swap.py --config config/dataset_name.yaml --target_video path/to/target --source_image path/to/source --checkpoint path/to/checkpoint --swap_index 0,1
|
||||
```
|
||||
The result will be stored in ```result.mp4```.
|
||||
|
||||
* For swaping either soft or hard labels can be used (specify ```--hard``` for hard segmentation).
|
||||
|
||||
* For swaping either target or source segmentation mask can be used (specify ```--use_source_segmentation``` for using source segmentation mask).
|
||||
|
||||
* For the reference we also provide fully-supervised segmentation. For fully-supervised add ```--supervised``` option. And run
|
||||
```git clone https://github.com/AliaksandrSiarohin/face-makeup.PyTorch face_parsing```
|
||||
which is a fork of @zllrunning.
|
||||
|
||||
* Also for the reference we provide [First Order Motion Model](https://github.com/AliaksandrSiarohin/first-order-model) based alignment, use ```--first_order_motion_model``` and the correspoinding checkpoint. This allignment can only be used along with ```--supervised``` option.
|
||||
|
||||
|
||||
### Colab Demo
|
||||
|
||||
We prepare a special demo for the google-colab, see: ```part_swap.ipynb```.
|
||||
|
||||
### Training
|
||||
|
||||
Model training consist in finetuning the First Order Model checkpoint (they can be downloaded from [google-drive](https://drive.google.com/open?id=1PyQJmkdCsAkOYwUyaj_l-l0as-iLDgeH) or [yandex-disk](https://yadi.sk/d/lEw8uRm140L_eQ)). Use the following command for training:
|
||||
```
|
||||
CUDA_VISIBLE_DEVICES=0 python train.py --config config/dataset_name.yaml --device_ids 0 --checkpoint dataset-name.cpk.pth.tar
|
||||
```
|
||||
The code will create a folder in the log directory (each run will create a time-stamped new directory).
|
||||
Checkpoints will be saved to this folder. To check the loss values during training in see ```log.txt```.
|
||||
You can also check training data reconstructions in the ```train-vis``` subfolder.
|
||||
By default the batch size is tunned to run on 1 Tesla-p100 gpu, you can change it in the train_params in the corresponding ```.yaml``` file.
|
||||
|
||||
### Evaluation
|
||||
We use two metrics to evaluate our model: 1) landmark regression MAE; and 2) Foreground segmentation IoU.
|
||||
|
||||
1) For computing the MAE download eval_images.tar.gz from [google-drive-eval](https://drive.google.com/drive/folders/18l3W4tkYWnpPcwMMhy07Tc6R7Ky_ouoJ?usp=sharing) and use the following command:
|
||||
|
||||
```
|
||||
CUDA_VISIBLE_DEVICES=0 python evaluate.py --config config/dataset_name.yaml --device_ids 0 --root_dir path-to-root-folder-of-dataset --checkpoint_path dataset-name.cpk.pth.tar
|
||||
```
|
||||
|
||||
2) Coming soon...
|
||||
|
||||
### Datasets
|
||||
|
||||
1) **Taichi**. Please follow the instruction from https://github.com/AliaksandrSiarohin/video-preprocessing.
|
||||
|
||||
2) **VoxCeleb**. Please follow the instruction from https://github.com/AliaksandrSiarohin/video-preprocessing.
|
||||
|
||||
|
||||
### Training on your own dataset
|
||||
1) Follow instructions from [First Order Motion Model](https://github.com/AliaksandrSiarohin/first-order-model) for preparing your dataset and train [First Order Motion Model](https://github.com/AliaksandrSiarohin/first-order-model) on your dataset.
|
||||
|
||||
2) This repository use the same dataset format as [First Order Motion Model](https://github.com/AliaksandrSiarohin/first-order-model) so you can use the same data as in 1).
|
||||
|
||||
#### Additional notes
|
||||
|
||||
Citation:
|
||||
|
||||
Motion Supervised co-part Segmentation:
|
||||
```
|
||||
@article{Siarohin_2020_motion,
|
||||
title={Motion Supervised co-part Segmentation},
|
||||
author={Siarohin, Aliaksandr and Roy, Subhankar and Lathuilière, Stéphane and Tulyakov, Sergey and Ricci, Elisa and Sebe, Nicu},
|
||||
journal={arXiv preprint},
|
||||
year={2020}
|
||||
}
|
||||
|
||||
```
|
||||
First Order Motion Model:
|
||||
```
|
||||
@InProceedings{Siarohin_2019_NeurIPS,
|
||||
author={Siarohin, Aliaksandr and Lathuilière, Stéphane and Tulyakov, Sergey and Ricci, Elisa and Sebe, Nicu},
|
||||
title={First Order Motion Model for Image Animation},
|
||||
booktitle = {Conference on Neural Information Processing Systems (NeurIPS)},
|
||||
month = {December},
|
||||
year = {2019}
|
||||
}
|
||||
|
||||
```
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,345 @@
|
||||
"""
|
||||
Code from https://github.com/hassony2/torch_videovision
|
||||
"""
|
||||
|
||||
import numbers
|
||||
|
||||
import random
|
||||
import numpy as np
|
||||
import PIL
|
||||
|
||||
from skimage.transform import resize, rotate
|
||||
from skimage.util import pad
|
||||
import torchvision
|
||||
|
||||
import warnings
|
||||
|
||||
from skimage import img_as_ubyte, img_as_float
|
||||
|
||||
|
||||
def crop_clip(clip, min_h, min_w, h, w):
|
||||
if isinstance(clip[0], np.ndarray):
|
||||
cropped = [img[min_h:min_h + h, min_w:min_w + w, :] for img in clip]
|
||||
|
||||
elif isinstance(clip[0], PIL.Image.Image):
|
||||
cropped = [
|
||||
img.crop((min_w, min_h, min_w + w, min_h + h)) for img in clip
|
||||
]
|
||||
else:
|
||||
raise TypeError('Expected numpy.ndarray or PIL.Image' +
|
||||
'but got list of {0}'.format(type(clip[0])))
|
||||
return cropped
|
||||
|
||||
|
||||
def pad_clip(clip, h, w):
|
||||
im_h, im_w = clip[0].shape[:2]
|
||||
pad_h = (0, 0) if h < im_h else ((h - im_h) // 2, (h - im_h + 1) // 2)
|
||||
pad_w = (0, 0) if w < im_w else ((w - im_w) // 2, (w - im_w + 1) // 2)
|
||||
|
||||
return pad(clip, ((0, 0), pad_h, pad_w, (0, 0)), mode='edge')
|
||||
|
||||
|
||||
def resize_clip(clip, size, interpolation='bilinear'):
|
||||
if isinstance(clip[0], np.ndarray):
|
||||
if isinstance(size, numbers.Number):
|
||||
im_h, im_w, im_c = clip[0].shape
|
||||
# Min spatial dim already matches minimal size
|
||||
if (im_w <= im_h and im_w == size) or (im_h <= im_w
|
||||
and im_h == size):
|
||||
return clip
|
||||
new_h, new_w = get_resize_sizes(im_h, im_w, size)
|
||||
size = (new_w, new_h)
|
||||
else:
|
||||
size = size[1], size[0]
|
||||
|
||||
scaled = [
|
||||
resize(img, size, order=1 if interpolation == 'bilinear' else 0, preserve_range=True,
|
||||
mode='constant', anti_aliasing=True) for img in clip
|
||||
]
|
||||
elif isinstance(clip[0], PIL.Image.Image):
|
||||
if isinstance(size, numbers.Number):
|
||||
im_w, im_h = clip[0].size
|
||||
# Min spatial dim already matches minimal size
|
||||
if (im_w <= im_h and im_w == size) or (im_h <= im_w
|
||||
and im_h == size):
|
||||
return clip
|
||||
new_h, new_w = get_resize_sizes(im_h, im_w, size)
|
||||
size = (new_w, new_h)
|
||||
else:
|
||||
size = size[1], size[0]
|
||||
if interpolation == 'bilinear':
|
||||
pil_inter = PIL.Image.NEAREST
|
||||
else:
|
||||
pil_inter = PIL.Image.BILINEAR
|
||||
scaled = [img.resize(size, pil_inter) for img in clip]
|
||||
else:
|
||||
raise TypeError('Expected numpy.ndarray or PIL.Image' +
|
||||
'but got list of {0}'.format(type(clip[0])))
|
||||
return scaled
|
||||
|
||||
|
||||
def get_resize_sizes(im_h, im_w, size):
|
||||
if im_w < im_h:
|
||||
ow = size
|
||||
oh = int(size * im_h / im_w)
|
||||
else:
|
||||
oh = size
|
||||
ow = int(size * im_w / im_h)
|
||||
return oh, ow
|
||||
|
||||
|
||||
class RandomFlip(object):
|
||||
def __init__(self, time_flip=False, horizontal_flip=False):
|
||||
self.time_flip = time_flip
|
||||
self.horizontal_flip = horizontal_flip
|
||||
|
||||
def __call__(self, clip):
|
||||
if random.random() < 0.5 and self.time_flip:
|
||||
return clip[::-1]
|
||||
if random.random() < 0.5 and self.horizontal_flip:
|
||||
return [np.fliplr(img) for img in clip]
|
||||
|
||||
return clip
|
||||
|
||||
|
||||
class RandomResize(object):
|
||||
"""Resizes a list of (H x W x C) numpy.ndarray to the final size
|
||||
The larger the original image is, the more times it takes to
|
||||
interpolate
|
||||
Args:
|
||||
interpolation (str): Can be one of 'nearest', 'bilinear'
|
||||
defaults to nearest
|
||||
size (tuple): (widht, height)
|
||||
"""
|
||||
|
||||
def __init__(self, ratio=(3. / 4., 4. / 3.), interpolation='nearest'):
|
||||
self.ratio = ratio
|
||||
self.interpolation = interpolation
|
||||
|
||||
def __call__(self, clip):
|
||||
scaling_factor = random.uniform(self.ratio[0], self.ratio[1])
|
||||
|
||||
if isinstance(clip[0], np.ndarray):
|
||||
im_h, im_w, im_c = clip[0].shape
|
||||
elif isinstance(clip[0], PIL.Image.Image):
|
||||
im_w, im_h = clip[0].size
|
||||
|
||||
new_w = int(im_w * scaling_factor)
|
||||
new_h = int(im_h * scaling_factor)
|
||||
new_size = (new_w, new_h)
|
||||
resized = resize_clip(
|
||||
clip, new_size, interpolation=self.interpolation)
|
||||
|
||||
return resized
|
||||
|
||||
|
||||
class RandomCrop(object):
|
||||
"""Extract random crop at the same location for a list of images
|
||||
Args:
|
||||
size (sequence or int): Desired output size for the
|
||||
crop in format (h, w)
|
||||
"""
|
||||
|
||||
def __init__(self, size):
|
||||
if isinstance(size, numbers.Number):
|
||||
size = (size, size)
|
||||
|
||||
self.size = size
|
||||
|
||||
def __call__(self, clip):
|
||||
"""
|
||||
Args:
|
||||
img (PIL.Image or numpy.ndarray): List of images to be cropped
|
||||
in format (h, w, c) in numpy.ndarray
|
||||
Returns:
|
||||
PIL.Image or numpy.ndarray: Cropped list of images
|
||||
"""
|
||||
h, w = self.size
|
||||
if isinstance(clip[0], np.ndarray):
|
||||
im_h, im_w, im_c = clip[0].shape
|
||||
elif isinstance(clip[0], PIL.Image.Image):
|
||||
im_w, im_h = clip[0].size
|
||||
else:
|
||||
raise TypeError('Expected numpy.ndarray or PIL.Image' +
|
||||
'but got list of {0}'.format(type(clip[0])))
|
||||
|
||||
clip = pad_clip(clip, h, w)
|
||||
im_h, im_w = clip.shape[1:3]
|
||||
x1 = 0 if h == im_h else random.randint(0, im_w - w)
|
||||
y1 = 0 if w == im_w else random.randint(0, im_h - h)
|
||||
cropped = crop_clip(clip, y1, x1, h, w)
|
||||
|
||||
return cropped
|
||||
|
||||
|
||||
class RandomRotation(object):
|
||||
"""Rotate entire clip randomly by a random angle within
|
||||
given bounds
|
||||
Args:
|
||||
degrees (sequence or int): Range of degrees to select from
|
||||
If degrees is a number instead of sequence like (min, max),
|
||||
the range of degrees, will be (-degrees, +degrees).
|
||||
"""
|
||||
|
||||
def __init__(self, degrees):
|
||||
if isinstance(degrees, numbers.Number):
|
||||
if degrees < 0:
|
||||
raise ValueError('If degrees is a single number,'
|
||||
'must be positive')
|
||||
degrees = (-degrees, degrees)
|
||||
else:
|
||||
if len(degrees) != 2:
|
||||
raise ValueError('If degrees is a sequence,'
|
||||
'it must be of len 2.')
|
||||
|
||||
self.degrees = degrees
|
||||
|
||||
def __call__(self, clip):
|
||||
"""
|
||||
Args:
|
||||
img (PIL.Image or numpy.ndarray): List of images to be cropped
|
||||
in format (h, w, c) in numpy.ndarray
|
||||
Returns:
|
||||
PIL.Image or numpy.ndarray: Cropped list of images
|
||||
"""
|
||||
angle = random.uniform(self.degrees[0], self.degrees[1])
|
||||
if isinstance(clip[0], np.ndarray):
|
||||
rotated = [rotate(image=img, angle=angle, preserve_range=True) for img in clip]
|
||||
elif isinstance(clip[0], PIL.Image.Image):
|
||||
rotated = [img.rotate(angle) for img in clip]
|
||||
else:
|
||||
raise TypeError('Expected numpy.ndarray or PIL.Image' +
|
||||
'but got list of {0}'.format(type(clip[0])))
|
||||
|
||||
return rotated
|
||||
|
||||
|
||||
class ColorJitter(object):
|
||||
"""Randomly change the brightness, contrast and saturation and hue of the clip
|
||||
Args:
|
||||
brightness (float): How much to jitter brightness. brightness_factor
|
||||
is chosen uniformly from [max(0, 1 - brightness), 1 + brightness].
|
||||
contrast (float): How much to jitter contrast. contrast_factor
|
||||
is chosen uniformly from [max(0, 1 - contrast), 1 + contrast].
|
||||
saturation (float): How much to jitter saturation. saturation_factor
|
||||
is chosen uniformly from [max(0, 1 - saturation), 1 + saturation].
|
||||
hue(float): How much to jitter hue. hue_factor is chosen uniformly from
|
||||
[-hue, hue]. Should be >=0 and <= 0.5.
|
||||
"""
|
||||
|
||||
def __init__(self, brightness=0, contrast=0, saturation=0, hue=0):
|
||||
self.brightness = brightness
|
||||
self.contrast = contrast
|
||||
self.saturation = saturation
|
||||
self.hue = hue
|
||||
|
||||
def get_params(self, brightness, contrast, saturation, hue):
|
||||
if brightness > 0:
|
||||
brightness_factor = random.uniform(
|
||||
max(0, 1 - brightness), 1 + brightness)
|
||||
else:
|
||||
brightness_factor = None
|
||||
|
||||
if contrast > 0:
|
||||
contrast_factor = random.uniform(
|
||||
max(0, 1 - contrast), 1 + contrast)
|
||||
else:
|
||||
contrast_factor = None
|
||||
|
||||
if saturation > 0:
|
||||
saturation_factor = random.uniform(
|
||||
max(0, 1 - saturation), 1 + saturation)
|
||||
else:
|
||||
saturation_factor = None
|
||||
|
||||
if hue > 0:
|
||||
hue_factor = random.uniform(-hue, hue)
|
||||
else:
|
||||
hue_factor = None
|
||||
return brightness_factor, contrast_factor, saturation_factor, hue_factor
|
||||
|
||||
def __call__(self, clip):
|
||||
"""
|
||||
Args:
|
||||
clip (list): list of PIL.Image
|
||||
Returns:
|
||||
list PIL.Image : list of transformed PIL.Image
|
||||
"""
|
||||
if isinstance(clip[0], np.ndarray):
|
||||
brightness, contrast, saturation, hue = self.get_params(
|
||||
self.brightness, self.contrast, self.saturation, self.hue)
|
||||
|
||||
# Create img transform function sequence
|
||||
img_transforms = []
|
||||
if brightness is not None:
|
||||
img_transforms.append(lambda img: torchvision.transforms.functional.adjust_brightness(img, brightness))
|
||||
if saturation is not None:
|
||||
img_transforms.append(lambda img: torchvision.transforms.functional.adjust_saturation(img, saturation))
|
||||
if hue is not None:
|
||||
img_transforms.append(lambda img: torchvision.transforms.functional.adjust_hue(img, hue))
|
||||
if contrast is not None:
|
||||
img_transforms.append(lambda img: torchvision.transforms.functional.adjust_contrast(img, contrast))
|
||||
random.shuffle(img_transforms)
|
||||
img_transforms = [img_as_ubyte, torchvision.transforms.ToPILImage()] + img_transforms + [np.array,
|
||||
img_as_float]
|
||||
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
jittered_clip = []
|
||||
for img in clip:
|
||||
jittered_img = img
|
||||
for func in img_transforms:
|
||||
jittered_img = func(jittered_img)
|
||||
jittered_clip.append(jittered_img.astype('float32'))
|
||||
elif isinstance(clip[0], PIL.Image.Image):
|
||||
brightness, contrast, saturation, hue = self.get_params(
|
||||
self.brightness, self.contrast, self.saturation, self.hue)
|
||||
|
||||
# Create img transform function sequence
|
||||
img_transforms = []
|
||||
if brightness is not None:
|
||||
img_transforms.append(lambda img: torchvision.transforms.functional.adjust_brightness(img, brightness))
|
||||
if saturation is not None:
|
||||
img_transforms.append(lambda img: torchvision.transforms.functional.adjust_saturation(img, saturation))
|
||||
if hue is not None:
|
||||
img_transforms.append(lambda img: torchvision.transforms.functional.adjust_hue(img, hue))
|
||||
if contrast is not None:
|
||||
img_transforms.append(lambda img: torchvision.transforms.functional.adjust_contrast(img, contrast))
|
||||
random.shuffle(img_transforms)
|
||||
|
||||
# Apply to all images
|
||||
jittered_clip = []
|
||||
for img in clip:
|
||||
for func in img_transforms:
|
||||
jittered_img = func(img)
|
||||
jittered_clip.append(jittered_img)
|
||||
|
||||
else:
|
||||
raise TypeError('Expected numpy.ndarray or PIL.Image' +
|
||||
'but got list of {0}'.format(type(clip[0])))
|
||||
return jittered_clip
|
||||
|
||||
|
||||
class AllAugmentationTransform:
|
||||
def __init__(self, resize_param=None, rotation_param=None, flip_param=None, crop_param=None, jitter_param=None):
|
||||
self.transforms = []
|
||||
|
||||
if flip_param is not None:
|
||||
self.transforms.append(RandomFlip(**flip_param))
|
||||
|
||||
if rotation_param is not None:
|
||||
self.transforms.append(RandomRotation(**rotation_param))
|
||||
|
||||
if resize_param is not None:
|
||||
self.transforms.append(RandomResize(**resize_param))
|
||||
|
||||
if crop_param is not None:
|
||||
self.transforms.append(RandomCrop(**crop_param))
|
||||
|
||||
if jitter_param is not None:
|
||||
self.transforms.append(ColorJitter(**jitter_param))
|
||||
|
||||
def __call__(self, clip):
|
||||
for t in self.transforms:
|
||||
clip = t(clip)
|
||||
return clip
|
||||
@@ -0,0 +1,92 @@
|
||||
# Dataset parameters
|
||||
dataset_params:
|
||||
# Path to data, data can be stored in several formats: .mp4 or .gif videos, stacked .png images or folders with frames.
|
||||
root_dir: data/taichi-png
|
||||
# Image shape, needed for staked .png format.
|
||||
image_shape: [256, 256, 3]
|
||||
# In case of VoxCeleb or TaiChi single video can be splitted in many chunks, or the maybe several videos for single person.
|
||||
# In this case epoch can be a pass over different videos (if id_sampling=True) or over different chunks (if id_sampling=False)
|
||||
# If the name of the video '12335#adsbf.mp4' the id is assumed to be 12335
|
||||
id_sampling: True
|
||||
# Augmentation parameters see augmentation.py for all posible augmentations
|
||||
augmentation_params:
|
||||
flip_param:
|
||||
horizontal_flip: True
|
||||
time_flip: True
|
||||
jitter_param:
|
||||
brightness: 0.1
|
||||
contrast: 0.1
|
||||
saturation: 0.1
|
||||
hue: 0.1
|
||||
|
||||
# Defines model architecture
|
||||
model_params:
|
||||
common_params:
|
||||
# Number of segments
|
||||
num_segments: 10
|
||||
# Number of channels per image
|
||||
num_channels: 3
|
||||
# Use only shift and no-affine part
|
||||
estimate_affine_part: True
|
||||
segmentation_module_params:
|
||||
# Softmax temperature for shift heatmaps
|
||||
temperature: 0.1
|
||||
# Number of features mutliplier
|
||||
block_expansion: 32
|
||||
# Maximum allowed number of features
|
||||
max_features: 1024
|
||||
# Number of block in Unet. Can be increased or decreased depending or resolution.
|
||||
num_blocks: 5
|
||||
# Segmentations is predicted on smaller images for better performance,
|
||||
# scale_factor=0.25 means that 256x256 image will be resized to 64x64
|
||||
scale_factor: 0.25
|
||||
reconstruction_module_params:
|
||||
# Number of features mutliplier
|
||||
block_expansion: 64
|
||||
# Maximum allowed number of features
|
||||
max_features: 512
|
||||
# Number of downsampling blocks in Jonson architecture.
|
||||
# Can be increased or decreased depending or resolution.
|
||||
num_down_blocks: 2
|
||||
# Number of ResBlocks in Jonson architecture.
|
||||
num_bottleneck_blocks: 6
|
||||
# Use visibility map or not
|
||||
estimate_visibility: True
|
||||
|
||||
# Parameters of training
|
||||
train_params:
|
||||
# Number of training epochs
|
||||
num_epochs: 10
|
||||
# For better i/o performance when number of videos is small number of epochs can be multiplied by this number.
|
||||
# Thus effectively with num_repeats=100 each epoch is 100 times larger.
|
||||
num_repeats: 50
|
||||
# Learning rates
|
||||
lr_segmentation: 2.0e-4
|
||||
lr_reconstruction: 2.0e-4
|
||||
batch_size: 20
|
||||
# Scales for perceptual pyramide loss. If scales = [1, 0.5, 0.25, 0.125] and image resolution is 256x256,
|
||||
# than the loss will be computer on resolutions 256x256, 128x128, 64x64, 32x32.
|
||||
scales: [1, 0.5, 0.25, 0.125]
|
||||
# Save checkpoint this frequently. If checkpoint_freq=50, checkpoint will be saved every 50 epochs.
|
||||
checkpoint_freq: 50
|
||||
# Parameters of transform for equivariance loss
|
||||
transform_params:
|
||||
# Sigma for affine part
|
||||
sigma_affine: 0.05
|
||||
# Sigma for deformation part
|
||||
sigma_tps: 0.005
|
||||
# Number of point in the deformation grid
|
||||
points_tps: 5
|
||||
loss_weights:
|
||||
equivariance: 10
|
||||
perceptual: [10, 10, 10, 10, 10]
|
||||
|
||||
|
||||
# Visualization parameters
|
||||
visualizer_params:
|
||||
# Draw keypoints (shifts in affine transformations) of this size, increase or decrease depending on resolution
|
||||
kp_size: 5
|
||||
# Draw white border around images
|
||||
draw_border: True
|
||||
# Color map for keypoints
|
||||
colormap: 'gist_rainbow'
|
||||
@@ -0,0 +1,92 @@
|
||||
# Dataset parameters
|
||||
dataset_params:
|
||||
# Path to data, data can be stored in several formats: .mp4 or .gif videos, stacked .png images or folders with frames.
|
||||
root_dir: data/vox-png
|
||||
# Image shape, needed for staked .png format.
|
||||
image_shape: [256, 256, 3]
|
||||
# In case of VoxCeleb or TaiChi single video can be splitted in many chunks, or the maybe several videos for single person.
|
||||
# In this case epoch can be a pass over different videos (if id_sampling=True) or over different chunks (if id_sampling=False)
|
||||
# If the name of the video '12335#adsbf.mp4' the id is assumed to be 12335
|
||||
id_sampling: True
|
||||
# Augmentation parameters see augmentation.py for all posible augmentations
|
||||
augmentation_params:
|
||||
flip_param:
|
||||
horizontal_flip: True
|
||||
time_flip: True
|
||||
jitter_param:
|
||||
brightness: 0.1
|
||||
contrast: 0.1
|
||||
saturation: 0.1
|
||||
hue: 0.1
|
||||
|
||||
# Defines model architecture
|
||||
model_params:
|
||||
common_params:
|
||||
# Number of segments
|
||||
num_segments: 10
|
||||
# Number of channels per image
|
||||
num_channels: 3
|
||||
# Use only shift and no-affine part
|
||||
estimate_affine_part: True
|
||||
segmentation_module_params:
|
||||
# Softmax temperature for shift heatmaps
|
||||
temperature: 0.1
|
||||
# Number of features mutliplier
|
||||
block_expansion: 32
|
||||
# Maximum allowed number of features
|
||||
max_features: 1024
|
||||
# Number of block in Unet. Can be increased or decreased depending or resolution.
|
||||
num_blocks: 5
|
||||
# Segmentations is predicted on smaller images for better performance,
|
||||
# scale_factor=0.25 means that 256x256 image will be resized to 64x64
|
||||
scale_factor: 0.25
|
||||
reconstruction_module_params:
|
||||
# Number of features mutliplier
|
||||
block_expansion: 64
|
||||
# Maximum allowed number of features
|
||||
max_features: 512
|
||||
# Number of downsampling blocks in Jonson architecture.
|
||||
# Can be increased or decreased depending or resolution.
|
||||
num_down_blocks: 2
|
||||
# Number of ResBlocks in Jonson architecture.
|
||||
num_bottleneck_blocks: 6
|
||||
# Use visibility map or not
|
||||
estimate_visibility: True
|
||||
|
||||
# Parameters of training
|
||||
train_params:
|
||||
# Number of training epochs
|
||||
num_epochs: 5
|
||||
# For better i/o performance when number of videos is small number of epochs can be multiplied by this number.
|
||||
# Thus effectively with num_repeats=100 each epoch is 100 times larger.
|
||||
num_repeats: 50
|
||||
# Learning rates
|
||||
lr_segmentation: 2.0e-4
|
||||
lr_reconstruction: 2.0e-4
|
||||
batch_size: 20
|
||||
# Scales for perceptual pyramide loss. If scales = [1, 0.5, 0.25, 0.125] and image resolution is 256x256,
|
||||
# than the loss will be computer on resolutions 256x256, 128x128, 64x64, 32x32.
|
||||
scales: [1, 0.5, 0.25, 0.125]
|
||||
# Save checkpoint this frequently. If checkpoint_freq=50, checkpoint will be saved every 50 epochs.
|
||||
checkpoint_freq: 50
|
||||
# Parameters of transform for equivariance loss
|
||||
transform_params:
|
||||
# Sigma for affine part
|
||||
sigma_affine: 0.05
|
||||
# Sigma for deformation part
|
||||
sigma_tps: 0.005
|
||||
# Number of point in the deformation grid
|
||||
points_tps: 5
|
||||
loss_weights:
|
||||
equivariance: 10
|
||||
perceptual: [10, 10, 10, 10, 10]
|
||||
|
||||
|
||||
# Visualization parameters
|
||||
visualizer_params:
|
||||
# Draw keypoints (shifts in affine transformations) of this size, increase or decrease depending on resolution
|
||||
kp_size: 5
|
||||
# Draw white border around images
|
||||
draw_border: True
|
||||
# Color map for keypoints
|
||||
colormap: 'gist_rainbow'
|
||||
@@ -0,0 +1,92 @@
|
||||
# Dataset parameters
|
||||
dataset_params:
|
||||
# Path to data, data can be stored in several formats: .mp4 or .gif videos, stacked .png images or folders with frames.
|
||||
root_dir: data/vox-png
|
||||
# Image shape, needed for staked .png format.
|
||||
image_shape: [256, 256, 3]
|
||||
# In case of VoxCeleb or TaiChi single video can be splitted in many chunks, or the maybe several videos for single person.
|
||||
# In this case epoch can be a pass over different videos (if id_sampling=True) or over different chunks (if id_sampling=False)
|
||||
# If the name of the video '12335#adsbf.mp4' the id is assumed to be 12335
|
||||
id_sampling: True
|
||||
# Augmentation parameters see augmentation.py for all posible augmentations
|
||||
augmentation_params:
|
||||
flip_param:
|
||||
horizontal_flip: True
|
||||
time_flip: True
|
||||
jitter_param:
|
||||
brightness: 0.1
|
||||
contrast: 0.1
|
||||
saturation: 0.1
|
||||
hue: 0.1
|
||||
|
||||
# Defines model architecture
|
||||
model_params:
|
||||
common_params:
|
||||
# Number of segments
|
||||
num_segments: 15
|
||||
# Number of channels per image
|
||||
num_channels: 3
|
||||
# Use only shift and no-affine part
|
||||
estimate_affine_part: True
|
||||
segmentation_module_params:
|
||||
# Softmax temperature for shift heatmaps
|
||||
temperature: 0.1
|
||||
# Number of features mutliplier
|
||||
block_expansion: 32
|
||||
# Maximum allowed number of features
|
||||
max_features: 1024
|
||||
# Number of block in Unet. Can be increased or decreased depending or resolution.
|
||||
num_blocks: 5
|
||||
# Segmentations is predicted on smaller images for better performance,
|
||||
# scale_factor=0.25 means that 256x256 image will be resized to 64x64
|
||||
scale_factor: 0.25
|
||||
reconstruction_module_params:
|
||||
# Number of features mutliplier
|
||||
block_expansion: 64
|
||||
# Maximum allowed number of features
|
||||
max_features: 512
|
||||
# Number of downsampling blocks in Jonson architecture.
|
||||
# Can be increased or decreased depending or resolution.
|
||||
num_down_blocks: 2
|
||||
# Number of ResBlocks in Jonson architecture.
|
||||
num_bottleneck_blocks: 6
|
||||
# Use visibility map or not
|
||||
estimate_visibility: True
|
||||
|
||||
# Parameters of training
|
||||
train_params:
|
||||
# Number of training epochs
|
||||
num_epochs: 5
|
||||
# For better i/o performance when number of videos is small number of epochs can be multiplied by this number.
|
||||
# Thus effectively with num_repeats=100 each epoch is 100 times larger.
|
||||
num_repeats: 50
|
||||
# Learning rates
|
||||
lr_segmentation: 2.0e-4
|
||||
lr_reconstruction: 2.0e-4
|
||||
batch_size: 20
|
||||
# Scales for perceptual pyramide loss. If scales = [1, 0.5, 0.25, 0.125] and image resolution is 256x256,
|
||||
# than the loss will be computer on resolutions 256x256, 128x128, 64x64, 32x32.
|
||||
scales: [1, 0.5, 0.25, 0.125]
|
||||
# Save checkpoint this frequently. If checkpoint_freq=50, checkpoint will be saved every 50 epochs.
|
||||
checkpoint_freq: 50
|
||||
# Parameters of transform for equivariance loss
|
||||
transform_params:
|
||||
# Sigma for affine part
|
||||
sigma_affine: 0.05
|
||||
# Sigma for deformation part
|
||||
sigma_tps: 0.005
|
||||
# Number of point in the deformation grid
|
||||
points_tps: 5
|
||||
loss_weights:
|
||||
equivariance: 10
|
||||
perceptual: [10, 10, 10, 10, 10]
|
||||
|
||||
|
||||
# Visualization parameters
|
||||
visualizer_params:
|
||||
# Draw keypoints (shifts in affine transformations) of this size, increase or decrease depending on resolution
|
||||
kp_size: 5
|
||||
# Draw white border around images
|
||||
draw_border: True
|
||||
# Color map for keypoints
|
||||
colormap: 'gist_rainbow'
|
||||
@@ -0,0 +1,92 @@
|
||||
# Dataset parameters
|
||||
dataset_params:
|
||||
# Path to data, data can be stored in several formats: .mp4 or .gif videos, stacked .png images or folders with frames.
|
||||
root_dir: data/vox-png
|
||||
# Image shape, needed for staked .png format.
|
||||
image_shape: [256, 256, 3]
|
||||
# In case of VoxCeleb or TaiChi single video can be splitted in many chunks, or the maybe several videos for single person.
|
||||
# In this case epoch can be a pass over different videos (if id_sampling=True) or over different chunks (if id_sampling=False)
|
||||
# If the name of the video '12335#adsbf.mp4' the id is assumed to be 12335
|
||||
id_sampling: True
|
||||
# Augmentation parameters see augmentation.py for all posible augmentations
|
||||
augmentation_params:
|
||||
flip_param:
|
||||
horizontal_flip: True
|
||||
time_flip: True
|
||||
jitter_param:
|
||||
brightness: 0.1
|
||||
contrast: 0.1
|
||||
saturation: 0.1
|
||||
hue: 0.1
|
||||
|
||||
# Defines model architecture
|
||||
model_params:
|
||||
common_params:
|
||||
# Number of segments
|
||||
num_segments: 5
|
||||
# Number of channels per image
|
||||
num_channels: 3
|
||||
# Use only shift and no-affine part
|
||||
estimate_affine_part: True
|
||||
segmentation_module_params:
|
||||
# Softmax temperature for shift heatmaps
|
||||
temperature: 0.1
|
||||
# Number of features mutliplier
|
||||
block_expansion: 32
|
||||
# Maximum allowed number of features
|
||||
max_features: 1024
|
||||
# Number of block in Unet. Can be increased or decreased depending or resolution.
|
||||
num_blocks: 5
|
||||
# Segmentations is predicted on smaller images for better performance,
|
||||
# scale_factor=0.25 means that 256x256 image will be resized to 64x64
|
||||
scale_factor: 0.25
|
||||
reconstruction_module_params:
|
||||
# Number of features mutliplier
|
||||
block_expansion: 64
|
||||
# Maximum allowed number of features
|
||||
max_features: 512
|
||||
# Number of downsampling blocks in Jonson architecture.
|
||||
# Can be increased or decreased depending or resolution.
|
||||
num_down_blocks: 2
|
||||
# Number of ResBlocks in Jonson architecture.
|
||||
num_bottleneck_blocks: 6
|
||||
# Use visibility map or not
|
||||
estimate_visibility: True
|
||||
|
||||
# Parameters of training
|
||||
train_params:
|
||||
# Number of training epochs
|
||||
num_epochs: 5
|
||||
# For better i/o performance when number of videos is small number of epochs can be multiplied by this number.
|
||||
# Thus effectively with num_repeats=100 each epoch is 100 times larger.
|
||||
num_repeats: 50
|
||||
# Learning rates
|
||||
lr_segmentation: 2.0e-4
|
||||
lr_reconstruction: 2.0e-4
|
||||
batch_size: 20
|
||||
# Scales for perceptual pyramide loss. If scales = [1, 0.5, 0.25, 0.125] and image resolution is 256x256,
|
||||
# than the loss will be computer on resolutions 256x256, 128x128, 64x64, 32x32.
|
||||
scales: [1, 0.5, 0.25, 0.125]
|
||||
# Save checkpoint this frequently. If checkpoint_freq=50, checkpoint will be saved every 50 epochs.
|
||||
checkpoint_freq: 50
|
||||
# Parameters of transform for equivariance loss
|
||||
transform_params:
|
||||
# Sigma for affine part
|
||||
sigma_affine: 0.05
|
||||
# Sigma for deformation part
|
||||
sigma_tps: 0.005
|
||||
# Number of point in the deformation grid
|
||||
points_tps: 5
|
||||
loss_weights:
|
||||
equivariance: 10
|
||||
perceptual: [10, 10, 10, 10, 10]
|
||||
|
||||
|
||||
# Visualization parameters
|
||||
visualizer_params:
|
||||
# Draw keypoints (shifts in affine transformations) of this size, increase or decrease depending on resolution
|
||||
kp_size: 5
|
||||
# Draw white border around images
|
||||
draw_border: True
|
||||
# Color map for keypoints
|
||||
colormap: 'gist_rainbow'
|
||||
@@ -0,0 +1,248 @@
|
||||
import os
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
from tqdm import trange
|
||||
from sklearn import linear_model
|
||||
from argparse import ArgumentParser
|
||||
import matplotlib
|
||||
matplotlib.use('Agg')
|
||||
import matplotlib.pyplot as plt
|
||||
import yaml
|
||||
from time import gmtime, strftime
|
||||
import numpy as np
|
||||
import cv2
|
||||
import imageio
|
||||
from skimage import io, img_as_float32
|
||||
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
from torch.utils import data
|
||||
import torch.nn.functional as F
|
||||
|
||||
from modules.segmentation_module import SegmentationModule
|
||||
from logger import load_segmentation_module
|
||||
|
||||
class FramesDataset(data.Dataset):
|
||||
def __init__(self, root_dir, is_train=True, root_dir_masks=None):
|
||||
super(FramesDataset, self).__init__()
|
||||
self.is_train = is_train
|
||||
self.root_dir_masks = root_dir_masks
|
||||
|
||||
train_images, test_images = os.listdir(os.path.join(root_dir, 'train')), os.listdir(os.path.join(root_dir, 'test'))
|
||||
|
||||
if self.is_train:
|
||||
self.images = train_images
|
||||
self.root_dir = os.path.join(root_dir, 'train')
|
||||
else:
|
||||
self.images = test_images
|
||||
self.root_dir = os.path.join(root_dir, 'test')
|
||||
|
||||
def __len__(self):
|
||||
return len(self.images)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
name = self.images[idx]
|
||||
path = os.path.join(self.root_dir, name)
|
||||
|
||||
video = img_as_float32(io.imread(path))
|
||||
|
||||
out = {}
|
||||
image = np.array(video, dtype='float32')
|
||||
|
||||
out['img'] = image.transpose((2, 0, 1)).astype('float32')
|
||||
out['name'] = name
|
||||
|
||||
if self.root_dir_masks is not None:
|
||||
path_mask = os.path.join(self.root_dir_masks, name)
|
||||
mask = img_as_float32(io.imread(path_mask))
|
||||
out['mask'] = np.expand_dims(mask, axis=0)
|
||||
|
||||
return out
|
||||
|
||||
def get_coordinate_tensors(x_max, y_max):
|
||||
x_map = np.tile(np.arange(x_max), (y_max,1)) / x_max * 2 - 1.0
|
||||
y_map = np.tile(np.arange(y_max), (x_max,1)).T / y_max * 2 - 1.0
|
||||
|
||||
x_map = torch.from_numpy(x_map.astype(np.float32))
|
||||
y_map = torch.from_numpy(y_map.astype(np.float32))
|
||||
|
||||
return x_map, y_map
|
||||
|
||||
def get_center(part_map):
|
||||
h,w = part_map.shape
|
||||
x_map, y_map = get_coordinate_tensors(h, w)
|
||||
|
||||
x_center = (part_map * x_map).sum()
|
||||
y_center = (part_map * y_map).sum()
|
||||
|
||||
return x_center, y_center
|
||||
|
||||
|
||||
def sort_column(df):
|
||||
df = df.sort_values('file_name')
|
||||
return df
|
||||
|
||||
|
||||
def regress_keypoints(df_kp):
|
||||
# train dataframes
|
||||
train_gnd = sort_column(df_kp['train_gnd'])
|
||||
train_pred = sort_column(df_kp['train_pred'])
|
||||
|
||||
# test dataframes
|
||||
test_gnd = sort_column(df_kp['test_gnd'])
|
||||
test_pred = sort_column(df_kp['test_pred'])
|
||||
|
||||
# convert dataframe to numpy
|
||||
train_gnd = np.stack(train_gnd['value'].values)
|
||||
train_pred = np.stack(train_pred['value'].values)
|
||||
|
||||
test_gnd = np.stack(test_gnd['value'].values)
|
||||
test_pred = np.stack(test_pred['value'].values)
|
||||
|
||||
scores = []
|
||||
num_gnd_kp = train_gnd.shape[1]
|
||||
for i in range(num_gnd_kp):
|
||||
for j in range(2):
|
||||
print('Fitting linear model for...{},{}'.format(i, j))
|
||||
index = train_gnd[:, i, j] != -1
|
||||
features = train_pred[index]
|
||||
features = features.reshape(features.shape[0], -1)
|
||||
label = train_gnd[index, i, j]
|
||||
reg = linear_model.LinearRegression()
|
||||
reg.fit(features, label)
|
||||
|
||||
index_test = test_gnd[:, i, j] != -1
|
||||
features = test_pred[index_test]
|
||||
features = features.reshape(features.shape[0], -1)
|
||||
label = test_gnd[index_test, i, j]
|
||||
#score = reg.score(features, label) # using sklearn's score
|
||||
score = np.mean(np.abs(reg.predict(features) - label))
|
||||
scores.append(score)
|
||||
print(np.sum(scores))
|
||||
|
||||
def evaluate(config, segmentation_module, dataset, opt):
|
||||
trainloader = data.DataLoader(dataset['train'], batch_size=1, shuffle=False, drop_last=False)
|
||||
testloader = data.DataLoader(dataset['test'], batch_size=1, shuffle=False, drop_last=False)
|
||||
|
||||
# put in eval mode
|
||||
segmentation_module.eval()
|
||||
|
||||
size = config['dataset_params']['image_shape'][:2]
|
||||
|
||||
# iterate over train images to obtain predicted keypoints for train set
|
||||
print('Computing keypoints on train set. Please wait...')
|
||||
# obtain keypoint for train images
|
||||
out_df = {'file_name': [], 'value': []}
|
||||
lms_pred = []
|
||||
|
||||
train_iter = iter(trainloader)
|
||||
with torch.no_grad():
|
||||
for _ in trange(len(trainloader.dataset)):
|
||||
|
||||
batch = train_iter.next()
|
||||
|
||||
image = batch['img']
|
||||
name = batch['name'][0]
|
||||
|
||||
# get the model output
|
||||
output = segmentation_module(image.to(opt.device_ids[0]))['segmentation']
|
||||
output = F.interpolate(output.cpu(), size=size, mode='bilinear')
|
||||
|
||||
centers = []
|
||||
for j in range(1, output.shape[1]): # ignore the background
|
||||
part_map = output[0, j, ...] + 1e-6
|
||||
k = part_map.sum()
|
||||
part_map_pdf = part_map / k
|
||||
x_c, y_c = get_center(part_map_pdf)
|
||||
x_c = (x_c + 1.) / 2 * size[0]
|
||||
y_c = (y_c + 1.) / 2 * size[0]
|
||||
center = torch.stack((x_c, y_c), dim=0).unsqueeze(0) # compute center of the part map
|
||||
centers.append(center)
|
||||
centers = torch.cat(centers, dim=0)
|
||||
lms_pred.append(centers.unsqueeze(0))
|
||||
|
||||
out_df['value'].append(centers.numpy())
|
||||
out_df['file_name'].append(name)
|
||||
|
||||
# save the landmarks in a pandas dataframe
|
||||
kp_train_df = pd.DataFrame(out_df)
|
||||
dataset_name_pkl = os.path.basename(opt.config).split('.')[0].split('-')[0]
|
||||
kp_train_df.to_pickle('landmarks/' + dataset_name_pkl + '_train_pred.pkl')
|
||||
|
||||
# iterate over the test images to obtain predicted keypoints for test set
|
||||
print('Computing keypoints on test set. Please wait...')
|
||||
# obtain keypoint for test images
|
||||
out_df = {'file_name': [], 'value': []}
|
||||
lms_pred = []
|
||||
test_iter = iter(testloader)
|
||||
with torch.no_grad():
|
||||
for _ in trange(len(testloader.dataset)):
|
||||
batch = test_iter.next()
|
||||
|
||||
image = batch['img']
|
||||
name = batch['name'][0]
|
||||
|
||||
# get the model output
|
||||
output = segmentation_module(image.to(opt.device_ids[0]))['segmentation']
|
||||
output = F.interpolate(output.cpu(), size=size, mode='bilinear')
|
||||
|
||||
centers = []
|
||||
for j in range(1, output.shape[1]): # ignore the background
|
||||
part_map = output[0, j, ...] + 1e-6
|
||||
k = part_map.sum()
|
||||
part_map_pdf = part_map / k
|
||||
x_c, y_c = get_center(part_map_pdf)
|
||||
x_c = (x_c + 1.) / 2 * size[0]
|
||||
y_c = (y_c + 1.) / 2 * size[0]
|
||||
center = torch.stack((x_c, y_c), dim=0).unsqueeze(0) # compute center of the part map
|
||||
centers.append(center)
|
||||
centers = torch.cat(centers, dim=0)
|
||||
lms_pred.append(centers.unsqueeze(0))
|
||||
|
||||
out_df['value'].append(centers.numpy())
|
||||
out_df['file_name'].append(name)
|
||||
|
||||
# save the landmarks in a pandas dataframe
|
||||
kp_train_df = pd.DataFrame(out_df)
|
||||
kp_train_df.to_pickle('landmarks/' + dataset_name_pkl + '_test_pred.pkl')
|
||||
|
||||
# regress from predicted keypoints to ground truth landmarks
|
||||
df_kp = {}
|
||||
df_kp['train_gnd'] = pd.read_pickle('landmarks/' + dataset_name_pkl + '_train_gt.pkl')
|
||||
df_kp['train_pred'] = pd.read_pickle('landmarks/' + dataset_name_pkl + '_train_pred.pkl')
|
||||
df_kp['test_gnd'] = pd.read_pickle('landmarks/' + dataset_name_pkl + '_test_gt.pkl')
|
||||
df_kp['test_pred'] = pd.read_pickle('landmarks/' + dataset_name_pkl + '_test_pred.pkl')
|
||||
regress_keypoints(df_kp)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = ArgumentParser(description="Evaluation script")
|
||||
parser.add_argument("--config", required=True, help="path to the config file")
|
||||
parser.add_argument('--mode', default='evaluate')
|
||||
parser.add_argument("--root_dir", required=True, help="path to root folder of the train and test images")
|
||||
parser.add_argument("--checkpoint_path", default=None, help="path to checkpoint to restore")
|
||||
parser.add_argument("--device_ids", default="0", type=lambda x: list(map(int, x.split(','))),
|
||||
help="Names of the devices comma separated.")
|
||||
|
||||
opt = parser.parse_args()
|
||||
with open(opt.config) as f:
|
||||
config = yaml.load(f)
|
||||
|
||||
segmentation_module = SegmentationModule(**config['model_params']['segmentation_module_params'],
|
||||
**config['model_params']['common_params'])
|
||||
|
||||
if torch.cuda.is_available():
|
||||
segmentation_module.to(opt.device_ids[0])
|
||||
|
||||
if opt.checkpoint_path is not None:
|
||||
checkpoint = torch.load(opt.checkpoint_path)
|
||||
load_segmentation_module(segmentation_module, checkpoint)
|
||||
|
||||
dataset = {}
|
||||
dataset['train'] = FramesDataset(root_dir=opt.root_dir, is_train=True)
|
||||
dataset['test'] = FramesDataset(root_dir=opt.root_dir, is_train=False)
|
||||
|
||||
evaluate(config, segmentation_module, dataset, opt)
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
import os
|
||||
import random
|
||||
|
||||
import matplotlib
|
||||
|
||||
|
||||
matplotlib.use('Agg')
|
||||
import cv2
|
||||
import yaml
|
||||
from argparse import ArgumentParser
|
||||
# from tqdm import tqdm
|
||||
import sys
|
||||
import time
|
||||
import imageio
|
||||
import numpy as np
|
||||
from skimage.transform import resize
|
||||
from skimage import img_as_ubyte
|
||||
from skimage.exposure import match_histograms
|
||||
import json
|
||||
import torch
|
||||
from sync_batchnorm import DataParallelWithCallback
|
||||
import torch.nn.functional as F
|
||||
|
||||
#from modules.segmentation_module import SegmentationModule
|
||||
from models.epic.modules.segmentation_module import SegmentationModule
|
||||
from models.epic.modules.reconstruction_module import ReconstructionModule
|
||||
|
||||
from models.epic.logger import load_reconstruction_module, load_segmentation_module
|
||||
|
||||
from models.epic.modules.util import AntiAliasInterpolation2d
|
||||
from models.epic.modules.dense_motion import DenseMotionNetwork
|
||||
|
||||
class PartSwapGenerator(ReconstructionModule):
|
||||
def __init__(self, blend_scale=1, first_order_motion_model=False, **kwargs):
|
||||
super(PartSwapGenerator, self).__init__(**kwargs)
|
||||
if blend_scale == 1:
|
||||
self.blend_downsample = lambda x: x
|
||||
else:
|
||||
self.blend_downsample = AntiAliasInterpolation2d(1, blend_scale)
|
||||
|
||||
if first_order_motion_model:
|
||||
self.dense_motion_network = DenseMotionNetwork()
|
||||
else:
|
||||
self.dense_motion_network = None
|
||||
|
||||
def forward(self, source_image, target_image, seg_target, seg_source, blend_mask, use_source_segmentation=False):
|
||||
# Encoding of source image
|
||||
enc_source = self.first(source_image)
|
||||
for i in range(len(self.down_blocks)):
|
||||
enc_source = self.down_blocks[i](enc_source)
|
||||
|
||||
# Encoding of target image
|
||||
enc_target = self.first(target_image)
|
||||
for i in range(len(self.down_blocks)):
|
||||
enc_target = self.down_blocks[i](enc_target)
|
||||
|
||||
output_dict = {}
|
||||
# Compute flow field for source image
|
||||
if self.dense_motion_network is None:
|
||||
segment_motions = self.segment_motion(seg_target, seg_source)
|
||||
segment_motions = segment_motions.permute(0, 1, 4, 2, 3)
|
||||
mask = seg_target['segmentation'].unsqueeze(2)
|
||||
deformation = (segment_motions * mask).sum(dim=1)
|
||||
deformation = deformation.permute(0, 2, 3, 1)
|
||||
else:
|
||||
motion = self.dense_motion_network(source_image=source_image, seg_target=seg_target,
|
||||
seg_source=seg_source)
|
||||
deformation = motion['deformation']
|
||||
|
||||
# Deform source encoding according to the motion
|
||||
enc_source = self.deform_input(enc_source, deformation)
|
||||
|
||||
if self.estimate_visibility:
|
||||
if self.dense_motion_network is None:
|
||||
visibility = seg_source['segmentation'][:, 1:].sum(dim=1, keepdim=True) * \
|
||||
(1 - seg_target['segmentation'][:, 1:].sum(dim=1, keepdim=True).detach())
|
||||
visibility = 1 - visibility
|
||||
else:
|
||||
visibility = motion['visibility']
|
||||
|
||||
if enc_source.shape[2] != visibility.shape[2] or enc_source.shape[3] != visibility.shape[3]:
|
||||
visibility = F.interpolate(visibility, size=enc_source.shape[2:], mode='bilinear')
|
||||
enc_source = enc_source * visibility
|
||||
|
||||
blend_mask = self.blend_downsample(blend_mask)
|
||||
# If source segmentation is provided use it should be deformed before blending
|
||||
if use_source_segmentation:
|
||||
blend_mask = self.deform_input(blend_mask, deformation)
|
||||
|
||||
out = enc_target * (1 - blend_mask) + enc_source * blend_mask
|
||||
|
||||
out = self.bottleneck(out)
|
||||
|
||||
for i in range(len(self.up_blocks)):
|
||||
out = self.up_blocks[i](out)
|
||||
|
||||
out = self.final(out)
|
||||
out = F.sigmoid(out)
|
||||
|
||||
output_dict["prediction"] = out
|
||||
|
||||
return output_dict
|
||||
|
||||
|
||||
def load_checkpoints(config, checkpoint, blend_scale=0.125, first_order_motion_model=False, cpu=False):
|
||||
with open(config) as f:
|
||||
config = yaml.safe_load(f)#yaml.load(f)
|
||||
|
||||
reconstruction_module = PartSwapGenerator(blend_scale=blend_scale,
|
||||
first_order_motion_model=first_order_motion_model,
|
||||
**config['model_params']['reconstruction_module_params'],
|
||||
**config['model_params']['common_params'])
|
||||
|
||||
if not cpu:
|
||||
reconstruction_module.cuda()
|
||||
|
||||
segmentation_module = SegmentationModule(**config['model_params']['segmentation_module_params'],
|
||||
**config['model_params']['common_params'])
|
||||
if not cpu:
|
||||
segmentation_module.cuda()
|
||||
|
||||
if cpu:
|
||||
checkpoint = torch.load(checkpoint, map_location=torch.device('cpu'))
|
||||
else:
|
||||
checkpoint = torch.load(checkpoint)
|
||||
|
||||
load_reconstruction_module(reconstruction_module, checkpoint)
|
||||
load_segmentation_module(segmentation_module, checkpoint)
|
||||
|
||||
if not cpu:
|
||||
reconstruction_module = DataParallelWithCallback(reconstruction_module)
|
||||
segmentation_module = DataParallelWithCallback(segmentation_module)
|
||||
|
||||
reconstruction_module.eval()
|
||||
segmentation_module.eval()
|
||||
|
||||
return reconstruction_module, segmentation_module
|
||||
|
||||
|
||||
def load_face_parser(cpu=False):
|
||||
from face_parsing.model import BiSeNet
|
||||
|
||||
face_parser = BiSeNet(n_classes=19)
|
||||
if not cpu:
|
||||
face_parser.cuda()
|
||||
face_parser.load_state_dict(torch.load('face_parsing/cp/79999_iter.pth'))
|
||||
else:
|
||||
face_parser.load_state_dict(torch.load('face_parsing/cp/79999_iter.pth', map_location=torch.device('cpu')))
|
||||
|
||||
face_parser.eval()
|
||||
|
||||
mean = torch.Tensor(np.array([0.485, 0.456, 0.406], dtype=np.float32)).view(1, 3, 1, 1)
|
||||
std = torch.Tensor(np.array([0.229, 0.224, 0.225], dtype=np.float32)).view(1, 3, 1, 1)
|
||||
|
||||
if not cpu:
|
||||
face_parser.mean = mean.cuda()
|
||||
face_parser.std = std.cuda()
|
||||
else:
|
||||
face_parser.mean = mean
|
||||
face_parser.std = std
|
||||
|
||||
return face_parser
|
||||
|
||||
|
||||
def make_video(swap_index, source_image, target_video, reconstruction_module, segmentation_module, face_parser=None,
|
||||
hard=False, use_source_segmentation=False, cpu=False):
|
||||
assert type(swap_index) == list
|
||||
with torch.no_grad():
|
||||
predictions = []
|
||||
source = torch.tensor(source_image[np.newaxis].astype(np.float32)).permute(0, 3, 1, 2)
|
||||
if not cpu:
|
||||
source = source.cuda()
|
||||
target = torch.tensor(np.array(target_video)[np.newaxis].astype(np.float32)).permute(0, 4, 1, 2, 3)
|
||||
seg_source = segmentation_module(source)
|
||||
|
||||
for frame_idx in range(target.shape[2]): # tqdm(range(target.shape[2])):
|
||||
target_frame = target[:, :, frame_idx]
|
||||
if not cpu:
|
||||
target_frame = target_frame.cuda()
|
||||
|
||||
seg_target = segmentation_module(target_frame)
|
||||
|
||||
# Computing blend mask
|
||||
if face_parser is not None:
|
||||
blend_mask = F.interpolate(source if use_source_segmentation else target_frame, size=(512, 512))
|
||||
blend_mask = (blend_mask - face_parser.mean) / face_parser.std
|
||||
blend_mask = torch.softmax(face_parser(blend_mask)[0], dim=1)
|
||||
else:
|
||||
blend_mask = seg_source['segmentation'] if use_source_segmentation else seg_target['segmentation']
|
||||
|
||||
blend_mask = blend_mask[:, swap_index].sum(dim=1, keepdim=True)
|
||||
if hard:
|
||||
blend_mask = (blend_mask > 0.5).type(blend_mask.type())
|
||||
|
||||
out = reconstruction_module(source, target_frame, seg_source=seg_source, seg_target=seg_target, blend_mask=blend_mask, use_source_segmentation=use_source_segmentation)
|
||||
|
||||
predictions.append(np.transpose(out['prediction'].data.cpu().numpy(), [0, 2, 3, 1])[0])
|
||||
return predictions
|
||||
|
||||
class EPIC:
|
||||
def __init__(self, checkpoint_path, config_path, fake_face_path):
|
||||
print("Running speed_evaluation")
|
||||
self.swap_indices = [2, 3, 9, 11, 15] #Indices of face regions to swap
|
||||
self.fake_face = resize(imageio.imread(fake_face_path), (256, 256))[..., :3]
|
||||
self.reconstruction_module, self.segmentation_module = load_checkpoints(config_path, checkpoint_path, blend_scale=1, cpu=True)
|
||||
|
||||
def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray:
|
||||
return obfuscate(swap_index=self.swap_indices,
|
||||
source_image=self.fake_face,
|
||||
target_image=face_roi_img_bgr,
|
||||
reconstruction_module=self.reconstruction_module,
|
||||
segmentation_module=self.segmentation_module)
|
||||
|
||||
|
||||
#python face_obfuscator.py --config config/vox-256-sem-15segments.yaml --checkpoint stuff/vox-15segments.pth.tar --swap_index 2,3,9,11,15
|
||||
def obfuscate(swap_index, source_image, target_image, reconstruction_module, segmentation_module):
|
||||
original_shape = target_image.shape
|
||||
model_output = img_as_ubyte(make_video(swap_index=swap_index,
|
||||
source_image=source_image,
|
||||
target_video=[resize(target_image, (256, 256))[..., :3]],
|
||||
reconstruction_module=reconstruction_module,
|
||||
segmentation_module=segmentation_module)[0])
|
||||
matched = match_histograms(model_output, target_image)
|
||||
output = cv2.resize(matched, (original_shape[1], original_shape[0]), interpolation=cv2.INTER_LINEAR)
|
||||
return output
|
||||
|
||||
|
||||
def measure_speed(fake_face, target_image_paths, reconstruction_module, segmentation_module):
|
||||
times = []
|
||||
counter = 0
|
||||
for path in target_image_paths:
|
||||
target_image = imageio.imread(path)
|
||||
original_shape = target_image.shape
|
||||
fake_face = resize(fake_face, (256, 256))[..., :3] #256
|
||||
target_video = [target_image]
|
||||
target_video = [resize(frame, (256, 256))[..., :3] for frame in target_video]
|
||||
swap_indices = [2, 3, 9, 11, 15]
|
||||
start = time.time()
|
||||
output = obfuscate(swap_indices, fake_face, target_video, reconstruction_module, segmentation_module)
|
||||
output = cv2.resize(output, (original_shape[1], original_shape[0]), interpolation=cv2.INTER_LINEAR)
|
||||
end = time.time()
|
||||
times.append(end - start) #0.9638 bei 256 UND 0.241 bei 128
|
||||
print(counter)
|
||||
counter += 1
|
||||
avg = sum(times) / len(times)
|
||||
return avg
|
||||
|
||||
|
||||
def main():
|
||||
print("Running speed_evaluation")
|
||||
checkpoint = "stuff/vox-15segments.pth.tar"
|
||||
config = "config/vox-256-sem-15segments.yaml"
|
||||
fake_face = imageio.imread("stuff/fake_face.jpg")
|
||||
target_image_paths = os.listdir("stuff/speed_eval_images/")
|
||||
random.shuffle(target_image_paths)
|
||||
target_image_paths = [os.path.join("stuff/speed_eval_images/", path) for path in target_image_paths[:1000]]
|
||||
blend_scale = 1
|
||||
reconstruction_module, segmentation_module = load_checkpoints(config, checkpoint, blend_scale=blend_scale, cpu=True)
|
||||
avg_speed = measure_speed(fake_face, target_image_paths, reconstruction_module, segmentation_module)
|
||||
print(avg_speed)
|
||||
print("Done")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
# parser = ArgumentParser()
|
||||
# parser.add_argument("--config", required=True, help="path to config")
|
||||
# parser.add_argument("--checkpoint", default='vox-cpk.pth.tar', help="path to checkpoint to restore")
|
||||
# parser.add_argument("--swap_index", default="1,2,5", type=lambda x: list(map(int, x.split(','))),
|
||||
# help='index of swaped parts')
|
||||
# parser.add_argument("--hard", action="store_true", help="use hard segmentation labels for blending")
|
||||
# parser.add_argument("--use_source_segmentation", action="store_true", help="use source segmentation for swaping")
|
||||
# parser.add_argument("--first_order_motion_model", action="store_true", help="use first order model for alignment")
|
||||
# parser.add_argument("--supervised", action="store_true",
|
||||
# help="use supervised segmentation labels for blending. Only for faces.")
|
||||
# parser.add_argument("--cpu", action="store_true", help="cpu mode")
|
||||
#
|
||||
# opt = parser.parse_args()
|
||||
#
|
||||
# blend_scale = (256 / 4) / 512 if opt.supervised else 1
|
||||
# swap_index = opt.swap_index
|
||||
# hard = opt.hard
|
||||
# cpu = opt.cpu
|
||||
# use_source_segmentation = opt.use_source_segmentation
|
||||
# if opt.supervised:
|
||||
# face_parser = load_face_parser(opt.cpu)
|
||||
# else:
|
||||
# face_parser = None
|
||||
#
|
||||
# reconstruction_module, segmentation_module = load_checkpoints(opt.config, opt.checkpoint, blend_scale=blend_scale,
|
||||
# first_order_motion_model=opt.first_order_motion_model,
|
||||
# cpu=cpu)
|
||||
# api.run()
|
||||
@@ -0,0 +1,195 @@
|
||||
import os
|
||||
from skimage import io, img_as_float32
|
||||
from skimage.color import gray2rgb
|
||||
from sklearn.model_selection import train_test_split
|
||||
from imageio import mimread
|
||||
|
||||
import numpy as np
|
||||
from torch.utils.data import Dataset
|
||||
import pandas as pd
|
||||
from augmentation import AllAugmentationTransform
|
||||
import glob
|
||||
|
||||
|
||||
def read_video(name, image_shape):
|
||||
"""
|
||||
Read video which can be:
|
||||
- an image of concatenated frames
|
||||
- '.mp4' and'.gif'
|
||||
- folder with images
|
||||
"""
|
||||
|
||||
if os.path.isdir(name):
|
||||
frames = sorted(os.listdir(name))
|
||||
num_frames = len(frames)
|
||||
video_array = np.array([img_as_float32(io.imread(os.path.join(name, frames[idx]))) for idx in range(num_frames)])
|
||||
elif name.lower().endswith('.png') or name.lower().endswith('.jpg'):
|
||||
image = io.imread(name)
|
||||
|
||||
if len(image.shape) == 2 or image.shape[2] == 1:
|
||||
image = gray2rgb(image)
|
||||
|
||||
if image.shape[2] == 4:
|
||||
image = image[..., :3]
|
||||
|
||||
image = img_as_float32(image)
|
||||
|
||||
video_array = np.moveaxis(image, 1, 0)
|
||||
|
||||
video_array = video_array.reshape((-1,) + image_shape)
|
||||
video_array = np.moveaxis(video_array, 1, 2)
|
||||
elif name.lower().endswith('.gif') or name.lower().endswith('.mp4') or name.lower().endswith('.mov'):
|
||||
video = np.array(mimread(name))
|
||||
if len(video.shape) == 3:
|
||||
video = np.array([gray2rgb(frame) for frame in video])
|
||||
if video.shape[-1] == 4:
|
||||
video = video[..., :3]
|
||||
video_array = img_as_float32(video)
|
||||
else:
|
||||
raise Exception("Unknown file extensions %s" % name)
|
||||
|
||||
return video_array
|
||||
|
||||
|
||||
class FramesDataset(Dataset):
|
||||
"""
|
||||
Dataset of videos, videos can be represented as:
|
||||
- an image of concatenated frames
|
||||
- '.mp4' and'.gif'
|
||||
- folder with images
|
||||
"""
|
||||
|
||||
def __init__(self, root_dir, image_shape=(256, 256, 3), id_sampling=False, is_train=True,
|
||||
random_seed=0, pairs_list=None, augmentation_params=None):
|
||||
self.root_dir = root_dir
|
||||
self.images = os.listdir(root_dir)
|
||||
self.image_shape = tuple(image_shape)
|
||||
self.pairs_list = pairs_list
|
||||
self.id_sampling = id_sampling
|
||||
if os.path.exists(os.path.join(root_dir, 'train')):
|
||||
assert os.path.exists(os.path.join(root_dir, 'test'))
|
||||
print("Use predefined train-test split.")
|
||||
if id_sampling:
|
||||
train_images = {os.path.basename(image).split('#')[0] for image in os.listdir(os.path.join(root_dir, 'train'))}
|
||||
train_images = list(train_images)
|
||||
else:
|
||||
train_images = os.listdir(os.path.join(root_dir, 'train'))
|
||||
test_images = os.listdir(os.path.join(root_dir, 'test'))
|
||||
self.root_dir = os.path.join(self.root_dir, 'train' if is_train else 'test')
|
||||
else:
|
||||
print("Use random train-test split.")
|
||||
train_images, test_images = train_test_split(self.images, random_state=random_seed, test_size=0.2)
|
||||
|
||||
if is_train:
|
||||
self.images = train_images
|
||||
else:
|
||||
self.images = test_images
|
||||
|
||||
self.is_train = is_train
|
||||
|
||||
if self.is_train:
|
||||
self.transform = AllAugmentationTransform(**augmentation_params)
|
||||
else:
|
||||
self.transform = None
|
||||
|
||||
def __len__(self):
|
||||
return len(self.images)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
if self.is_train and self.id_sampling:
|
||||
name = self.images[idx]
|
||||
path = np.random.choice(glob.glob(os.path.join(self.root_dir, name + '*.mp4')))
|
||||
else:
|
||||
name = self.images[idx]
|
||||
path = os.path.join(self.root_dir, name)
|
||||
|
||||
video_name = os.path.basename(path)
|
||||
|
||||
if self.is_train and os.path.isdir(path):
|
||||
frames = os.listdir(path)
|
||||
num_frames = len(frames)
|
||||
frame_idx = np.sort(np.random.choice(num_frames, replace=True, size=2))
|
||||
video_array = [img_as_float32(io.imread(os.path.join(path, frames[idx]))) for idx in frame_idx]
|
||||
else:
|
||||
video_array = read_video(path, image_shape=self.image_shape)
|
||||
num_frames = len(video_array)
|
||||
frame_idx = np.sort(np.random.choice(num_frames, replace=True, size=2)) if self.is_train else range(num_frames)
|
||||
video_array = video_array[frame_idx]
|
||||
|
||||
if self.transform is not None:
|
||||
video_array = self.transform(video_array)
|
||||
|
||||
out = {}
|
||||
if self.is_train:
|
||||
source = np.array(video_array[0], dtype='float32')
|
||||
target = np.array(video_array[1], dtype='float32')
|
||||
|
||||
out['target'] = target.transpose((2, 0, 1))
|
||||
out['source'] = source.transpose((2, 0, 1))
|
||||
else:
|
||||
video = np.array(video_array, dtype='float32')
|
||||
out['video'] = video.transpose((3, 0, 1, 2))
|
||||
|
||||
out['name'] = video_name
|
||||
|
||||
return out
|
||||
|
||||
|
||||
class DatasetRepeater(Dataset):
|
||||
"""
|
||||
Pass several times over the same dataset for better i/o performance
|
||||
"""
|
||||
def __init__(self, dataset, num_repeats=100):
|
||||
self.dataset = dataset
|
||||
self.num_repeats = num_repeats
|
||||
|
||||
|
||||
def __len__(self):
|
||||
return self.num_repeats * self.dataset.__len__()
|
||||
|
||||
|
||||
def __getitem__(self, idx):
|
||||
return self.dataset[idx % self.dataset.__len__()]
|
||||
|
||||
|
||||
class PairedDataset(Dataset):
|
||||
"""
|
||||
Dataset of pairs for animation.
|
||||
"""
|
||||
|
||||
def __init__(self, initial_dataset, number_of_pairs, seed=0):
|
||||
self.initial_dataset = initial_dataset
|
||||
pairs_list = self.initial_dataset.pairs_list
|
||||
|
||||
np.random.seed(seed)
|
||||
|
||||
if pairs_list is None:
|
||||
max_idx = min(number_of_pairs, len(initial_dataset))
|
||||
nx, ny = max_idx, max_idx
|
||||
xy = np.mgrid[:nx, :ny].reshape(2, -1).T
|
||||
number_of_pairs = min(xy.shape[0], number_of_pairs)
|
||||
self.pairs = xy.take(np.random.choice(xy.shape[0], number_of_pairs, replace=False), axis=0)
|
||||
else:
|
||||
images = self.initial_dataset.images
|
||||
name_to_index = {name: index for index, name in enumerate(images)}
|
||||
pairs = pd.read_csv(pairs_list)
|
||||
pairs = pairs[np.logical_and(pairs['source'].isin(images), pairs['target'].isin(images))]
|
||||
|
||||
number_of_pairs = min(pairs.shape[0], number_of_pairs)
|
||||
self.pairs = []
|
||||
self.start_frames = []
|
||||
for ind in range(number_of_pairs):
|
||||
self.pairs.append(
|
||||
(name_to_index[pairs['target'].iloc[ind]], name_to_index[pairs['source'].iloc[ind]]))
|
||||
|
||||
def __len__(self):
|
||||
return len(self.pairs)
|
||||
|
||||
def __getitem__(self, idx):
|
||||
pair = self.pairs[idx]
|
||||
first = self.initial_dataset[pair[0]]
|
||||
second = self.initial_dataset[pair[1]]
|
||||
first = {'target_' + key: value for key, value in first.items()}
|
||||
second = {'source_' + key: value for key, value in second.items()}
|
||||
|
||||
return {**first, **second}
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,223 @@
|
||||
import numpy as np
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
import imageio
|
||||
|
||||
import os
|
||||
#from skimage.draw import circle
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import collections
|
||||
|
||||
|
||||
def partial_state_dict_load(module, state_dict):
|
||||
own_state = module.state_dict()
|
||||
for name, param in state_dict.items():
|
||||
if name not in own_state:
|
||||
continue
|
||||
|
||||
if isinstance(param, torch.nn.Parameter):
|
||||
# backwards compatibility for serialized parameters
|
||||
param = param.data
|
||||
own_state[name].copy_(param)
|
||||
|
||||
|
||||
def load_reconstruction_module(module, checkpoint):
|
||||
if 'generator' in checkpoint:
|
||||
partial_state_dict_load(module, checkpoint['generator'])
|
||||
else:
|
||||
module.load_state_dict(checkpoint['reconstruction_module'])
|
||||
|
||||
|
||||
def load_segmentation_module(module, checkpoint):
|
||||
if 'kp_detector' in checkpoint:
|
||||
partial_state_dict_load(module, checkpoint['kp_detector'])
|
||||
module.state_dict()['affine.weight'].copy_(checkpoint['kp_detector']['jacobian.weight'])
|
||||
module.state_dict()['affine.bias'].copy_(checkpoint['kp_detector']['jacobian.bias'])
|
||||
module.state_dict()['shift.weight'].copy_(checkpoint['kp_detector']['kp.weight'])
|
||||
module.state_dict()['shift.bias'].copy_(checkpoint['kp_detector']['kp.bias'])
|
||||
if 'semantic_seg.weight' in checkpoint['kp_detector']:
|
||||
module.state_dict()['segmentation.weight'].copy_(checkpoint['kp_detector']['semantic_seg.weight'])
|
||||
module.state_dict()['segmentation.bias'].copy_(checkpoint['kp_detector']['semantic_seg.bias'])
|
||||
else:
|
||||
print ('Segmentation part initialized at random.')
|
||||
else:
|
||||
module.load_state_dict(checkpoint['segmentation_module'])
|
||||
|
||||
|
||||
|
||||
class Logger:
|
||||
def __init__(self, log_dir, checkpoint_freq=100, visualizer_params=None, zfill_num=8, log_file_name='log.txt'):
|
||||
self.loss_list = []
|
||||
self.cpk_dir = log_dir
|
||||
self.visualizations_dir = os.path.join(log_dir, 'train-vis')
|
||||
if not os.path.exists(self.visualizations_dir):
|
||||
os.makedirs(self.visualizations_dir)
|
||||
self.log_file = open(os.path.join(log_dir, log_file_name), 'a')
|
||||
self.zfill_num = zfill_num
|
||||
self.visualizer = Visualizer(**visualizer_params)
|
||||
self.checkpoint_freq = checkpoint_freq
|
||||
self.epoch = 0
|
||||
self.best_loss = float('inf')
|
||||
self.names = None
|
||||
|
||||
def log_scores(self, loss_names):
|
||||
loss_mean = np.array(self.loss_list).mean(axis=0)
|
||||
|
||||
loss_string = "; ".join(["%s - %.5f" % (name, value) for name, value in zip(loss_names, loss_mean)])
|
||||
loss_string = str(self.epoch).zfill(self.zfill_num) + ") " + loss_string
|
||||
|
||||
print(loss_string, file=self.log_file)
|
||||
self.loss_list = []
|
||||
self.log_file.flush()
|
||||
|
||||
def visualize_rec(self, inp, out):
|
||||
image = self.visualizer.visualize(inp['target'], inp['source'], out)
|
||||
imageio.imsave(os.path.join(self.visualizations_dir, "%s-rec.png" % str(self.epoch).zfill(self.zfill_num)), image)
|
||||
|
||||
def save_cpk(self, emergent=False):
|
||||
cpk = {k: v.state_dict() for k, v in self.models.items()}
|
||||
cpk['epoch'] = self.epoch
|
||||
cpk_path = os.path.join(self.cpk_dir, '%s-checkpoint.pth.tar' % str(self.epoch).zfill(self.zfill_num))
|
||||
if not (os.path.exists(cpk_path) and emergent):
|
||||
torch.save(cpk, cpk_path)
|
||||
|
||||
@staticmethod
|
||||
def load_cpk(checkpoint_path, reconstruction_module=None, segmentation_module=None,
|
||||
optimizer_reconstruction_module=None, optimizer_segmentation_module=None):
|
||||
checkpoint = torch.load(checkpoint_path)
|
||||
if reconstruction_module is not None:
|
||||
load_reconstruction_module(reconstruction_module, checkpoint)
|
||||
|
||||
if segmentation_module is not None:
|
||||
load_segmentation_module(segmentation_module, checkpoint)
|
||||
|
||||
if optimizer_reconstruction_module is not None and 'generator' not in checkpoint :
|
||||
optimizer_reconstruction_module.load_state_dict(checkpoint['optimizer_reconstruction_module'])
|
||||
|
||||
if optimizer_segmentation_module is not None and 'generator' not in checkpoint :
|
||||
optimizer_segmentation_module.load_state_dict(checkpoint['optimizer_segmentation_module'])
|
||||
|
||||
return 0 if 'generator' in checkpoint else checkpoint['epoch']
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
if 'models' in self.__dict__:
|
||||
self.save_cpk()
|
||||
self.log_file.close()
|
||||
|
||||
def log_iter(self, losses):
|
||||
losses = collections.OrderedDict(losses.items())
|
||||
if self.names is None:
|
||||
self.names = list(losses.keys())
|
||||
self.loss_list.append(list(losses.values()))
|
||||
|
||||
def log_epoch(self, epoch, models, inp, out):
|
||||
self.epoch = epoch
|
||||
self.models = models
|
||||
if (self.epoch + 1) % self.checkpoint_freq == 0:
|
||||
self.save_cpk()
|
||||
self.log_scores(self.names)
|
||||
self.visualize_rec(inp, out)
|
||||
|
||||
|
||||
class Visualizer:
|
||||
def __init__(self, kp_size=5, draw_border=False, colormap='gist_rainbow'):
|
||||
self.kp_size = kp_size
|
||||
self.draw_border = draw_border
|
||||
self.colormap = plt.get_cmap(colormap)
|
||||
|
||||
def draw_image_with_kp(self, image, kp_array):
|
||||
image = np.copy(image)
|
||||
spatial_size = np.array(image.shape[:2][::-1])[np.newaxis]
|
||||
kp_array = spatial_size * (kp_array + 1) / 2
|
||||
num_kp = kp_array.shape[0]
|
||||
#for kp_ind, kp in enumerate(kp_array): TODO Removed this circle lines
|
||||
# rr, cc = circle(kp[1], kp[0], self.kp_size, shape=image.shape[:2])
|
||||
# image[rr, cc] = np.array(self.colormap(kp_ind / num_kp))[:3]
|
||||
return image
|
||||
|
||||
def create_image_column_with_kp(self, images, kp):
|
||||
image_array = np.array([self.draw_image_with_kp(v, k) for v, k in zip(images, kp)])
|
||||
return self.create_image_column(image_array)
|
||||
|
||||
def create_image_column(self, images):
|
||||
if self.draw_border:
|
||||
images = np.copy(images)
|
||||
images[:, :, [0, -1]] = (1, 1, 1)
|
||||
images[:, :, [0, -1]] = (1, 1, 1)
|
||||
return np.concatenate(list(images), axis=0)
|
||||
|
||||
def create_image_grid(self, *args):
|
||||
out = []
|
||||
for arg in args:
|
||||
if type(arg) == tuple:
|
||||
out.append(self.create_image_column_with_kp(arg[0], arg[1]))
|
||||
else:
|
||||
out.append(self.create_image_column(arg))
|
||||
return np.concatenate(out, axis=1)
|
||||
|
||||
def visualize(self, target, source, out):
|
||||
images = []
|
||||
|
||||
# Source image with keypoints
|
||||
source = source.data.cpu()
|
||||
source = np.transpose(source, [0, 2, 3, 1])
|
||||
images.append(source)
|
||||
|
||||
target = target.data.cpu().numpy()
|
||||
target = np.transpose(target, [0, 2, 3, 1])
|
||||
images.append(target)
|
||||
|
||||
# Deformed image
|
||||
if 'deformed' in out:
|
||||
deformed = out['deformed'].data.cpu().numpy()
|
||||
deformed = np.transpose(deformed, [0, 2, 3, 1])
|
||||
images.append(deformed)
|
||||
|
||||
prediction = out['prediction'].data.cpu().numpy()
|
||||
prediction = np.transpose(prediction, [0, 2, 3, 1])
|
||||
images.append(prediction)
|
||||
|
||||
## Visibility map
|
||||
if 'visibility_map' in out:
|
||||
visibility_map = out['visibility_map'].data.cpu().repeat(1, 3, 1, 1)
|
||||
visibility_map = F.interpolate(visibility_map, size=source.shape[1:3]).numpy()
|
||||
visibility_map = np.transpose(visibility_map, [0, 2, 3, 1])
|
||||
images.append(visibility_map)
|
||||
|
||||
if 'segmentation' in out['seg_target']:
|
||||
full_mask = []
|
||||
full_mask_bin = []
|
||||
|
||||
mask_bin = F.interpolate(out['seg_target']['segmentation'], size=source.shape[1:3], mode='bilinear')
|
||||
mask_bin = (torch.max(mask_bin, dim=1, keepdim=True)[0] == mask_bin).float()
|
||||
|
||||
for i in range(out['seg_target']['segmentation'].shape[1]):
|
||||
mask = out['seg_target']['segmentation'][:, i:(i+1)].data.cpu().repeat(1, 3, 1, 1)
|
||||
mask = F.interpolate(mask, size=source.shape[1:3], mode='bilinear')
|
||||
mask = np.transpose(mask.numpy(), (0, 2, 3, 1))
|
||||
mask_bin_part = mask_bin[:, i:(i+1)].data.cpu().repeat(1, 3, 1, 1)
|
||||
|
||||
mask_bin_part = np.transpose(mask_bin_part.numpy(), (0, 2, 3, 1))
|
||||
|
||||
if i != 0:
|
||||
color = np.array(self.colormap((i - 1) / (out['seg_target']['segmentation'].shape[1] - 1)))[:3]
|
||||
else:
|
||||
color = np.array((0, 0, 0))
|
||||
|
||||
color = color.reshape((1, 1, 1, 3))
|
||||
|
||||
full_mask.append(mask * color)
|
||||
full_mask_bin.append(mask_bin_part * color)
|
||||
images.append(sum(full_mask))
|
||||
images.append(0.3 * target + 0.7 * sum(full_mask))
|
||||
images.append(sum(full_mask_bin))
|
||||
images.append(0.3 * target + 0.7 * sum(full_mask_bin))
|
||||
|
||||
image = self.create_image_grid(*images)
|
||||
image = (255 * image).astype(np.uint8)
|
||||
return image
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,110 @@
|
||||
"""
|
||||
Dense motion module from first order motion model, it is not part of the paper and provided only for the reference
|
||||
"""
|
||||
|
||||
from torch import nn
|
||||
import torch.nn.functional as F
|
||||
import torch
|
||||
from models.epic.modules.util import Hourglass, AntiAliasInterpolation2d, make_coordinate_grid, kp2gaussian
|
||||
|
||||
|
||||
class DenseMotionNetwork(nn.Module):
|
||||
"""
|
||||
Module that predicting a dense motion from sparse motion representation given by seg_source and seg_target
|
||||
"""
|
||||
|
||||
def __init__(self, block_expansion=64, num_blocks=5, max_features=1024, num_kp=10, num_channels=3,
|
||||
estimate_visibility=True, scale_factor=0.25, kp_variance=0.01):
|
||||
super(DenseMotionNetwork, self).__init__()
|
||||
self.hourglass = Hourglass(block_expansion=block_expansion, in_features=(num_kp + 1) * (num_channels + 1),
|
||||
max_features=max_features, num_blocks=num_blocks)
|
||||
|
||||
self.mask = nn.Conv2d(self.hourglass.out_filters, num_kp + 1, kernel_size=(7, 7), padding=(3, 3))
|
||||
|
||||
if estimate_visibility:
|
||||
self.occlusion = nn.Conv2d(self.hourglass.out_filters, 1, kernel_size=(7, 7), padding=(3, 3))
|
||||
else:
|
||||
self.occlusion = None
|
||||
|
||||
self.num_kp = num_kp
|
||||
self.scale_factor = scale_factor
|
||||
self.kp_variance = kp_variance
|
||||
|
||||
if self.scale_factor != 1:
|
||||
self.down = AntiAliasInterpolation2d(num_channels, self.scale_factor)
|
||||
|
||||
def create_heatmap_representations(self, source_image, seg_target, seg_source):
|
||||
"""
|
||||
Eq 6. in the paper H_k(z)
|
||||
"""
|
||||
spatial_size = source_image.shape[2:]
|
||||
gaussian_target = kp2gaussian(seg_target, spatial_size=spatial_size, kp_variance=self.kp_variance)
|
||||
gaussian_source = kp2gaussian(seg_source, spatial_size=spatial_size, kp_variance=self.kp_variance)
|
||||
heatmap = gaussian_target - gaussian_source
|
||||
|
||||
# adding background feature
|
||||
zeros = torch.zeros(heatmap.shape[0], 1, spatial_size[0], spatial_size[1]).type(heatmap.type())
|
||||
heatmap = torch.cat([zeros, heatmap], dim=1)
|
||||
heatmap = heatmap.unsqueeze(2)
|
||||
return heatmap
|
||||
|
||||
def create_sparse_motions(self, source_image, seg_target, seg_source):
|
||||
bs, _, h, w = source_image.shape
|
||||
identity_grid = make_coordinate_grid((h, w), type=seg_source['shift'].type())
|
||||
identity_grid = identity_grid.view(1, 1, h, w, 2)
|
||||
coordinate_grid = identity_grid - seg_target['shift'].view(bs, self.num_kp, 1, 1, 2)
|
||||
if 'affine' in seg_target:
|
||||
affine = torch.matmul(seg_source['affine'], torch.inverse(seg_target['affine']))
|
||||
affine = affine.unsqueeze(-3).unsqueeze(-3)
|
||||
affine = affine.repeat(1, 1, h, w, 1, 1)
|
||||
coordinate_grid = torch.matmul(affine, coordinate_grid.unsqueeze(-1))
|
||||
coordinate_grid = coordinate_grid.squeeze(-1)
|
||||
|
||||
target_to_source = coordinate_grid + seg_source['shift'].view(bs, self.num_kp, 1, 1, 2)
|
||||
|
||||
# adding background feature
|
||||
identity_grid = identity_grid.repeat(bs, 1, 1, 1, 1)
|
||||
sparse_motions = torch.cat([identity_grid, target_to_source], dim=1)
|
||||
return sparse_motions
|
||||
|
||||
def create_deformed_source_image(self, source_image, sparse_motions):
|
||||
bs, _, h, w = source_image.shape
|
||||
source_repeat = source_image.unsqueeze(1).unsqueeze(1).repeat(1, self.num_kp + 1, 1, 1, 1, 1)
|
||||
source_repeat = source_repeat.view(bs * (self.num_kp + 1), -1, h, w)
|
||||
sparse_motions = sparse_motions.view((bs * (self.num_kp + 1), h, w, -1))
|
||||
sparse_deformed = F.grid_sample(source_repeat, sparse_motions)
|
||||
sparse_deformed = sparse_deformed.view((bs, self.num_kp + 1, -1, h, w))
|
||||
return sparse_deformed
|
||||
|
||||
def forward(self, source_image, seg_target, seg_source):
|
||||
if self.scale_factor != 1:
|
||||
source_image = self.down(source_image)
|
||||
|
||||
bs, _, h, w = source_image.shape
|
||||
|
||||
out_dict = dict()
|
||||
heatmap_representation = self.create_heatmap_representations(source_image, seg_target, seg_source)
|
||||
sparse_motion = self.create_sparse_motions(source_image, seg_target, seg_source)
|
||||
deformed_source = self.create_deformed_source_image(source_image, sparse_motion)
|
||||
out_dict['sparse_deformed'] = deformed_source
|
||||
|
||||
input = torch.cat([heatmap_representation, deformed_source], dim=2)
|
||||
input = input.view(bs, -1, h, w)
|
||||
|
||||
prediction = self.hourglass(input)
|
||||
|
||||
mask = self.mask(prediction)
|
||||
mask = F.softmax(mask, dim=1)
|
||||
out_dict['mask'] = mask
|
||||
mask = mask.unsqueeze(2)
|
||||
sparse_motion = sparse_motion.permute(0, 1, 4, 2, 3)
|
||||
deformation = (sparse_motion * mask).sum(dim=1)
|
||||
deformation = deformation.permute(0, 2, 3, 1)
|
||||
|
||||
out_dict['deformation'] = deformation
|
||||
|
||||
if self.occlusion:
|
||||
visibility = torch.sigmoid(self.occlusion(prediction))
|
||||
out_dict['visibility'] = visibility
|
||||
|
||||
return out_dict
|
||||
@@ -0,0 +1,182 @@
|
||||
from torch import nn
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from modules.util import AntiAliasInterpolation2d, make_coordinate_grid
|
||||
from torchvision import models
|
||||
import numpy as np
|
||||
from torch.autograd import grad
|
||||
|
||||
|
||||
class Vgg19(torch.nn.Module):
|
||||
def __init__(self, requires_grad=False):
|
||||
super(Vgg19, self).__init__()
|
||||
vgg_pretrained_features = models.vgg19(pretrained=True).features
|
||||
self.slice1 = torch.nn.Sequential()
|
||||
self.slice2 = torch.nn.Sequential()
|
||||
self.slice3 = torch.nn.Sequential()
|
||||
self.slice4 = torch.nn.Sequential()
|
||||
self.slice5 = torch.nn.Sequential()
|
||||
for x in range(2):
|
||||
self.slice1.add_module(str(x), vgg_pretrained_features[x])
|
||||
for x in range(2, 7):
|
||||
self.slice2.add_module(str(x), vgg_pretrained_features[x])
|
||||
for x in range(7, 12):
|
||||
self.slice3.add_module(str(x), vgg_pretrained_features[x])
|
||||
for x in range(12, 21):
|
||||
self.slice4.add_module(str(x), vgg_pretrained_features[x])
|
||||
for x in range(21, 30):
|
||||
self.slice5.add_module(str(x), vgg_pretrained_features[x])
|
||||
|
||||
self.mean = torch.nn.Parameter(data=torch.Tensor(np.array([0.485, 0.456, 0.406]).reshape((1, 3, 1, 1))),
|
||||
requires_grad=False)
|
||||
self.std = torch.nn.Parameter(data=torch.Tensor(np.array([0.229, 0.224, 0.225]).reshape((1, 3, 1, 1))),
|
||||
requires_grad=False)
|
||||
|
||||
if not requires_grad:
|
||||
for param in self.parameters():
|
||||
param.requires_grad = False
|
||||
|
||||
def forward(self, X):
|
||||
X = (X - self.mean) / self.std
|
||||
h_relu1 = self.slice1(X)
|
||||
h_relu2 = self.slice2(h_relu1)
|
||||
h_relu3 = self.slice3(h_relu2)
|
||||
h_relu4 = self.slice4(h_relu3)
|
||||
h_relu5 = self.slice5(h_relu4)
|
||||
out = [h_relu1, h_relu2, h_relu3, h_relu4, h_relu5]
|
||||
return out
|
||||
|
||||
|
||||
class ImagePyramide(torch.nn.Module):
|
||||
def __init__(self, scales, num_channels):
|
||||
super(ImagePyramide, self).__init__()
|
||||
downs = {}
|
||||
for scale in scales:
|
||||
downs[str(scale).replace('.', '-')] = AntiAliasInterpolation2d(num_channels, scale)
|
||||
self.downs = nn.ModuleDict(downs)
|
||||
|
||||
def forward(self, x):
|
||||
out_dict = {}
|
||||
for scale, down_module in self.downs.items():
|
||||
out_dict['prediction_' + str(scale).replace('-', '.')] = down_module(x)
|
||||
return out_dict
|
||||
|
||||
|
||||
class Transform:
|
||||
def __init__(self, bs, **kwargs):
|
||||
noise = torch.normal(mean=0, std=kwargs['sigma_affine'] * torch.ones([bs, 2, 3]))
|
||||
self.theta = noise + torch.eye(2, 3).view(1, 2, 3)
|
||||
self.bs = bs
|
||||
|
||||
if ('sigma_tps' in kwargs) and ('points_tps' in kwargs):
|
||||
self.tps = True
|
||||
self.control_points = make_coordinate_grid((kwargs['points_tps'], kwargs['points_tps']), type=noise.type())
|
||||
self.control_points = self.control_points.unsqueeze(0)
|
||||
self.control_params = torch.normal(mean=0,
|
||||
std=kwargs['sigma_tps'] * torch.ones([bs, 1, kwargs['points_tps'] ** 2]))
|
||||
else:
|
||||
self.tps = False
|
||||
|
||||
def transform_frame(self, frame):
|
||||
grid = make_coordinate_grid(frame.shape[2:], type=frame.type()).unsqueeze(0)
|
||||
grid = grid.view(1, frame.shape[2] * frame.shape[3], 2)
|
||||
grid = self.warp_coordinates(grid).view(self.bs, frame.shape[2], frame.shape[3], 2)
|
||||
return F.grid_sample(frame, grid, padding_mode="border")
|
||||
|
||||
def warp_coordinates(self, coordinates):
|
||||
theta = self.theta.type(coordinates.type())
|
||||
theta = theta.unsqueeze(1)
|
||||
transformed = torch.matmul(theta[:, :, :, :2], coordinates.unsqueeze(-1)) + theta[:, :, :, 2:]
|
||||
transformed = transformed.squeeze(-1)
|
||||
|
||||
if self.tps:
|
||||
control_points = self.control_points.type(coordinates.type())
|
||||
control_params = self.control_params.type(coordinates.type())
|
||||
distances = coordinates.view(coordinates.shape[0], -1, 1, 2) - control_points.view(1, 1, -1, 2)
|
||||
distances = torch.abs(distances).sum(-1)
|
||||
|
||||
result = distances ** 2
|
||||
result = result * torch.log(distances + 1e-6)
|
||||
result = result * control_params
|
||||
result = result.sum(dim=2).view(self.bs, coordinates.shape[1], 1)
|
||||
transformed = transformed + result
|
||||
|
||||
return transformed
|
||||
|
||||
def affine(self, coordinates):
|
||||
new_coordinates = self.warp_coordinates(coordinates)
|
||||
grad_x = grad(new_coordinates[..., 0].sum(), coordinates, create_graph=True)
|
||||
grad_y = grad(new_coordinates[..., 1].sum(), coordinates, create_graph=True)
|
||||
affine = torch.cat([grad_x[0].unsqueeze(-2), grad_y[0].unsqueeze(-2)], dim=-2)
|
||||
return affine
|
||||
|
||||
|
||||
def detach_kp(kp):
|
||||
return {key: value.detach() for key, value in kp.items()}
|
||||
|
||||
|
||||
class FullModel(torch.nn.Module):
|
||||
"""
|
||||
Merge all reconstruction_module related updates into single model for better multi-gpu usage
|
||||
"""
|
||||
|
||||
def __init__(self, segmentation_module, reconstruction_module, train_params):
|
||||
super(FullModel, self).__init__()
|
||||
self.segmentation_module = segmentation_module
|
||||
self.reconstruction_module = reconstruction_module
|
||||
self.train_params = train_params
|
||||
self.scales = train_params['scales']
|
||||
self.pyramide = ImagePyramide(self.scales, reconstruction_module.num_channels).cuda()
|
||||
self.loss_weights = train_params['loss_weights']
|
||||
if sum(self.loss_weights['perceptual']) != 0:
|
||||
self.vgg = Vgg19().cuda()
|
||||
|
||||
def forward(self, x):
|
||||
seg_source = self.segmentation_module(x['source'])
|
||||
seg_target = self.segmentation_module(x['target'])
|
||||
|
||||
generated = self.reconstruction_module(x['source'], seg_source=seg_source, seg_target=seg_target)
|
||||
generated.update({'seg_source': seg_source, 'seg_target': seg_target})
|
||||
|
||||
loss_values = {}
|
||||
|
||||
pyramide_real = self.pyramide(x['target'])
|
||||
pyramide_generated = self.pyramide(generated['prediction'])
|
||||
|
||||
if sum(self.loss_weights['perceptual']) != 0:
|
||||
value_total = 0
|
||||
for scale in self.scales:
|
||||
x_vgg = self.vgg(pyramide_generated['prediction_' + str(scale)])
|
||||
y_vgg = self.vgg(pyramide_real['prediction_' + str(scale)])
|
||||
|
||||
for i, weight in enumerate(self.loss_weights['perceptual']):
|
||||
value = torch.abs(x_vgg[i] - y_vgg[i].detach()).mean()
|
||||
value_total += self.loss_weights['perceptual'][i] * value
|
||||
loss_values['perceptual'] = value_total
|
||||
|
||||
if self.loss_weights['equivariance'] != 0:
|
||||
transform = Transform(x['target'].shape[0], **self.train_params['transform_params'])
|
||||
transformed_frame = transform.transform_frame(x['target'])
|
||||
transformed_seg = self.segmentation_module(transformed_frame)
|
||||
|
||||
generated['transformed_frame'] = transformed_frame
|
||||
generated['transformed_seg'] = transformed_seg
|
||||
|
||||
value = torch.abs(seg_target['shift'] - transform.warp_coordinates(transformed_seg['shift'])).mean()
|
||||
loss_values['equivariance_shift'] = self.loss_weights['equivariance'] * value
|
||||
|
||||
## affine loss part
|
||||
if 'affine' in seg_target:
|
||||
affine_transformed = torch.matmul(transform.affine(transformed_seg['shift']),
|
||||
transformed_seg['affine'])
|
||||
|
||||
normed_target = torch.inverse(seg_target['affine'])
|
||||
normed_transformed = affine_transformed
|
||||
value = torch.matmul(normed_target, normed_transformed)
|
||||
|
||||
eye = torch.eye(2).view(1, 1, 2, 2).type(value.type())
|
||||
|
||||
value = torch.abs(eye - value).mean()
|
||||
loss_values['equivariance_affine'] = self.loss_weights['equivariance'] * value
|
||||
|
||||
return loss_values, generated
|
||||
@@ -0,0 +1,109 @@
|
||||
import torch
|
||||
from torch import nn
|
||||
import torch.nn.functional as F
|
||||
from models.epic.modules.util import ResBlock2d, SameBlock2d, UpBlock2d, DownBlock2d
|
||||
from models.epic.modules.util import make_coordinate_grid
|
||||
|
||||
|
||||
class ReconstructionModule(nn.Module):
|
||||
"""
|
||||
Reconstruct target from source and segmentation of target and part transformations
|
||||
"""
|
||||
|
||||
def __init__(self, num_channels, block_expansion, max_features, num_down_blocks,
|
||||
num_bottleneck_blocks, num_segments, estimate_visibility=False, **kwargs):
|
||||
super(ReconstructionModule, self).__init__()
|
||||
|
||||
self.first = SameBlock2d(num_channels, block_expansion, kernel_size=(7, 7), padding=(3, 3))
|
||||
|
||||
down_blocks = []
|
||||
for i in range(num_down_blocks):
|
||||
in_features = min(max_features, block_expansion * (2 ** i))
|
||||
out_features = min(max_features, block_expansion * (2 ** (i + 1)))
|
||||
down_blocks.append(DownBlock2d(in_features, out_features, kernel_size=(3, 3), padding=(1, 1)))
|
||||
self.down_blocks = nn.ModuleList(down_blocks)
|
||||
|
||||
up_blocks = []
|
||||
for i in range(num_down_blocks):
|
||||
in_features = min(max_features, block_expansion * (2 ** (num_down_blocks - i)))
|
||||
out_features = min(max_features, block_expansion * (2 ** (num_down_blocks - i - 1)))
|
||||
up_blocks.append(UpBlock2d(in_features, out_features, kernel_size=(3, 3), padding=(1, 1)))
|
||||
self.up_blocks = nn.ModuleList(up_blocks)
|
||||
|
||||
self.bottleneck = torch.nn.Sequential()
|
||||
in_features = min(max_features, block_expansion * (2 ** num_down_blocks))
|
||||
for i in range(num_bottleneck_blocks):
|
||||
self.bottleneck.add_module('r' + str(i), ResBlock2d(in_features, kernel_size=(3, 3), padding=(1, 1)))
|
||||
|
||||
self.final = nn.Conv2d(block_expansion, num_channels, kernel_size=(7, 7), padding=(3, 3))
|
||||
self.estimate_visibility = estimate_visibility
|
||||
self.num_channels = num_channels
|
||||
self.num_segments = num_segments
|
||||
|
||||
def segment_motion(self, seg_target, seg_source):
|
||||
bs, _, h, w = seg_target['segmentation'].shape
|
||||
identity_grid = make_coordinate_grid((h, w), type=seg_source['shift'].type())
|
||||
identity_grid = identity_grid.view(1, 1, h, w, 2)
|
||||
coordinate_grid = identity_grid - seg_target['shift'].view(bs, self.num_segments, 1, 1, 2)
|
||||
if 'affine' in seg_target:
|
||||
affine = torch.matmul(seg_source['affine'], torch.inverse(seg_target['affine']))
|
||||
affine = affine.unsqueeze(-3).unsqueeze(-3)
|
||||
affine = affine.repeat(1, 1, h, w, 1, 1)
|
||||
coordinate_grid = torch.matmul(affine, coordinate_grid.unsqueeze(-1))
|
||||
coordinate_grid = coordinate_grid.squeeze(-1)
|
||||
|
||||
target_to_source = coordinate_grid + seg_source['shift'].view(bs, self.num_segments, 1, 1, 2)
|
||||
|
||||
# adding background feature
|
||||
identity_grid = identity_grid.repeat(bs, 1, 1, 1, 1)
|
||||
return torch.cat([identity_grid, target_to_source], dim=1)
|
||||
|
||||
def deform_input(self, inp, deformation):
|
||||
_, h_old, w_old, _ = deformation.shape
|
||||
_, _, h, w = inp.shape
|
||||
if h_old != h or w_old != w:
|
||||
deformation = deformation.permute(0, 3, 1, 2)
|
||||
deformation = F.interpolate(deformation, size=(h, w), mode='bilinear')
|
||||
deformation = deformation.permute(0, 2, 3, 1)
|
||||
return F.grid_sample(inp, deformation)
|
||||
|
||||
def forward(self, source_image, seg_target, seg_source):
|
||||
# Encoding (downsampling) part
|
||||
out = self.first(source_image)
|
||||
for i in range(len(self.down_blocks)):
|
||||
out = self.down_blocks[i](out)
|
||||
|
||||
output_dict = {}
|
||||
|
||||
# Computing segment motion
|
||||
segment_motions = self.segment_motion(seg_target, seg_source)
|
||||
segment_motions = segment_motions.permute(0, 1, 4, 2, 3)
|
||||
mask = seg_target['segmentation'].unsqueeze(2)
|
||||
deformation = (segment_motions * mask).sum(dim=1)
|
||||
deformation = deformation.permute(0, 2, 3, 1)
|
||||
|
||||
# Deform according to motion
|
||||
out = self.deform_input(out, deformation)
|
||||
output_dict["deformed"] = self.deform_input(source_image, deformation)
|
||||
|
||||
if self.estimate_visibility:
|
||||
visibility = seg_source['segmentation'][:, 1:].sum(dim=1, keepdim=True) * \
|
||||
(1 - seg_target['segmentation'][:, 1:].sum(dim=1, keepdim=True).detach())
|
||||
visibility = 1 - visibility
|
||||
|
||||
if out.shape[2] != visibility.shape[2] or out.shape[3] != visibility.shape[3]:
|
||||
visibility = F.interpolate(visibility, size=out.shape[2:], mode='bilinear')
|
||||
out = out * visibility
|
||||
output_dict['visibility_maps'] = visibility
|
||||
|
||||
out = self.bottleneck(out)
|
||||
|
||||
for i in range(len(self.up_blocks)):
|
||||
out = self.up_blocks[i](out)
|
||||
|
||||
out = self.final(out)
|
||||
out = F.sigmoid(out)
|
||||
|
||||
output_dict["prediction"] = out
|
||||
|
||||
return output_dict
|
||||
@@ -0,0 +1,78 @@
|
||||
from torch import nn
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
from models.epic.modules.util import Hourglass, make_coordinate_grid, AntiAliasInterpolation2d
|
||||
|
||||
|
||||
class SegmentationModule(nn.Module):
|
||||
"""
|
||||
Computing a segmentation map and affine transformations.
|
||||
"""
|
||||
|
||||
def __init__(self, block_expansion, num_segments, num_channels, max_features,
|
||||
num_blocks, temperature, estimate_affine_part=False, scale_factor=1):
|
||||
super(SegmentationModule, self).__init__()
|
||||
|
||||
self.predictor = Hourglass(block_expansion, in_features=num_channels,
|
||||
max_features=max_features, num_blocks=num_blocks)
|
||||
self.num_segments = num_segments
|
||||
self.shift = nn.Conv2d(in_channels=self.predictor.out_filters, out_channels=num_segments, kernel_size=(7, 7),
|
||||
padding=(3, 3))
|
||||
|
||||
if estimate_affine_part:
|
||||
self.affine = nn.Conv2d(in_channels=self.predictor.out_filters,
|
||||
out_channels=4 * num_segments, kernel_size=(7, 7), padding=(3, 3))
|
||||
self.affine.weight.data.zero_()
|
||||
self.affine.bias.data.copy_(torch.tensor([1, 0, 0, 1] * num_segments, dtype=torch.float))
|
||||
else:
|
||||
self.affine = None
|
||||
|
||||
self.segmentation = nn.Conv2d(in_channels=self.predictor.out_filters,
|
||||
out_channels=(1 + num_segments), kernel_size=(7, 7), padding=(3, 3))
|
||||
|
||||
self.temperature = temperature
|
||||
self.scale_factor = scale_factor
|
||||
if self.scale_factor != 1:
|
||||
self.down = AntiAliasInterpolation2d(num_channels, self.scale_factor)
|
||||
|
||||
def gaussian2kp(self, heatmap):
|
||||
"""
|
||||
Extract the mean and the variance from a heatmap
|
||||
"""
|
||||
shape = heatmap.shape
|
||||
heatmap = heatmap.unsqueeze(-1)
|
||||
grid = make_coordinate_grid(shape[2:], heatmap.type()).unsqueeze_(0).unsqueeze_(0)
|
||||
result = (heatmap * grid).sum(dim=(2, 3))
|
||||
|
||||
return result
|
||||
|
||||
def forward(self, x):
|
||||
if self.scale_factor != 1:
|
||||
x = self.down(x)
|
||||
|
||||
out = {}
|
||||
feature_map = self.predictor(x)
|
||||
out['segmentation'] = F.softmax(self.segmentation(feature_map), dim=1)
|
||||
|
||||
prediction = self.shift(feature_map)
|
||||
|
||||
final_shape = prediction.shape
|
||||
heatmap = prediction.view(final_shape[0], final_shape[1], -1)
|
||||
heatmap = F.softmax(heatmap / self.temperature, dim=2)
|
||||
heatmap = heatmap.view(*final_shape)
|
||||
|
||||
out['shift'] = self.gaussian2kp(heatmap)
|
||||
|
||||
if self.affine is not None:
|
||||
affine_map = self.affine(feature_map)
|
||||
affine_map = affine_map.reshape(final_shape[0], self.num_segments, 4, final_shape[2],
|
||||
final_shape[3])
|
||||
heatmap = heatmap.unsqueeze(2)
|
||||
|
||||
affine = heatmap * affine_map
|
||||
affine = affine.view(final_shape[0], final_shape[1], 4, -1)
|
||||
affine = affine.sum(dim=-1)
|
||||
affine = affine.view(affine.shape[0], affine.shape[1], 2, 2)
|
||||
out['affine'] = affine
|
||||
|
||||
return out
|
||||
@@ -0,0 +1,243 @@
|
||||
from torch import nn
|
||||
|
||||
import torch.nn.functional as F
|
||||
import torch
|
||||
|
||||
from sync_batchnorm import SynchronizedBatchNorm2d as BatchNorm2d
|
||||
|
||||
|
||||
def kp2gaussian(kp, spatial_size, kp_variance):
|
||||
"""
|
||||
Transform a keypoint into gaussian like representation
|
||||
"""
|
||||
mean = kp['shift']
|
||||
|
||||
coordinate_grid = make_coordinate_grid(spatial_size, mean.type())
|
||||
number_of_leading_dimensions = len(mean.shape) - 1
|
||||
shape = (1,) * number_of_leading_dimensions + coordinate_grid.shape
|
||||
coordinate_grid = coordinate_grid.view(*shape)
|
||||
repeats = mean.shape[:number_of_leading_dimensions] + (1, 1, 1)
|
||||
coordinate_grid = coordinate_grid.repeat(*repeats)
|
||||
|
||||
# Preprocess kp shape
|
||||
shape = mean.shape[:number_of_leading_dimensions] + (1, 1, 2)
|
||||
mean = mean.view(*shape)
|
||||
|
||||
mean_sub = (coordinate_grid - mean)
|
||||
|
||||
out = torch.exp(-0.5 * (mean_sub ** 2).sum(-1) / kp_variance)
|
||||
|
||||
return out
|
||||
|
||||
|
||||
def make_coordinate_grid(spatial_size, type):
|
||||
"""
|
||||
Create a meshgrid [-1,1] x [-1,1] of given spatial_size.
|
||||
"""
|
||||
h, w = spatial_size
|
||||
x = torch.arange(w).type(type)
|
||||
y = torch.arange(h).type(type)
|
||||
|
||||
x = (2 * (x / (w - 1)) - 1)
|
||||
y = (2 * (y / (h - 1)) - 1)
|
||||
|
||||
yy = y.view(-1, 1).repeat(1, w)
|
||||
xx = x.view(1, -1).repeat(h, 1)
|
||||
|
||||
meshed = torch.cat([xx.unsqueeze_(2), yy.unsqueeze_(2)], 2)
|
||||
|
||||
return meshed
|
||||
|
||||
|
||||
class ResBlock2d(nn.Module):
|
||||
"""
|
||||
Res block, preserve spatial resolution.
|
||||
"""
|
||||
|
||||
def __init__(self, in_features, kernel_size, padding):
|
||||
super(ResBlock2d, self).__init__()
|
||||
self.conv1 = nn.Conv2d(in_channels=in_features, out_channels=in_features, kernel_size=kernel_size,
|
||||
padding=padding)
|
||||
self.conv2 = nn.Conv2d(in_channels=in_features, out_channels=in_features, kernel_size=kernel_size,
|
||||
padding=padding)
|
||||
self.norm1 = BatchNorm2d(in_features, affine=True)
|
||||
self.norm2 = BatchNorm2d(in_features, affine=True)
|
||||
|
||||
def forward(self, x):
|
||||
out = self.norm1(x)
|
||||
out = F.relu(out)
|
||||
out = self.conv1(out)
|
||||
out = self.norm2(out)
|
||||
out = F.relu(out)
|
||||
out = self.conv2(out)
|
||||
out += x
|
||||
return out
|
||||
|
||||
|
||||
class UpBlock2d(nn.Module):
|
||||
"""
|
||||
Simple block for processing video (decoder).
|
||||
"""
|
||||
|
||||
def __init__(self, in_features, out_features, kernel_size=3, padding=1, groups=1):
|
||||
super(UpBlock2d, self).__init__()
|
||||
|
||||
self.conv = nn.Conv2d(in_channels=in_features, out_channels=out_features, kernel_size=kernel_size,
|
||||
padding=padding, groups=groups)
|
||||
self.norm = BatchNorm2d(out_features, affine=True)
|
||||
|
||||
def forward(self, x):
|
||||
out = F.interpolate(x, scale_factor=2)
|
||||
out = self.conv(out)
|
||||
out = self.norm(out)
|
||||
out = F.relu(out)
|
||||
return out
|
||||
|
||||
|
||||
class DownBlock2d(nn.Module):
|
||||
"""
|
||||
Simple block for processinGg video (encoder).
|
||||
"""
|
||||
|
||||
def __init__(self, in_features, out_features, kernel_size=3, padding=1, groups=1):
|
||||
super(DownBlock2d, self).__init__()
|
||||
self.conv = nn.Conv2d(in_channels=in_features, out_channels=out_features, kernel_size=kernel_size,
|
||||
padding=padding, groups=groups)
|
||||
self.norm = BatchNorm2d(out_features, affine=True)
|
||||
self.pool = nn.AvgPool2d(kernel_size=(2, 2))
|
||||
|
||||
def forward(self, x):
|
||||
out = self.conv(x)
|
||||
out = self.norm(out)
|
||||
out = F.relu(out)
|
||||
out = self.pool(out)
|
||||
return out
|
||||
|
||||
|
||||
class SameBlock2d(nn.Module):
|
||||
"""
|
||||
Simple block with group convolution.
|
||||
"""
|
||||
|
||||
def __init__(self, in_features, out_features, groups=1, kernel_size=3, padding=1):
|
||||
super(SameBlock2d, self).__init__()
|
||||
self.conv = nn.Conv2d(in_channels=in_features, out_channels=out_features,
|
||||
kernel_size=kernel_size, padding=padding, groups=groups)
|
||||
self.norm = BatchNorm2d(out_features, affine=True)
|
||||
|
||||
def forward(self, x):
|
||||
out = self.conv(x)
|
||||
out = self.norm(out)
|
||||
out = F.relu(out)
|
||||
return out
|
||||
|
||||
|
||||
class Encoder(nn.Module):
|
||||
"""
|
||||
Hourglass Encoder
|
||||
"""
|
||||
|
||||
def __init__(self, block_expansion, in_features, num_blocks=3, max_features=256):
|
||||
super(Encoder, self).__init__()
|
||||
|
||||
down_blocks = []
|
||||
for i in range(num_blocks):
|
||||
down_blocks.append(DownBlock2d(in_features if i == 0 else min(max_features, block_expansion * (2 ** i)),
|
||||
min(max_features, block_expansion * (2 ** (i + 1))),
|
||||
kernel_size=3, padding=1))
|
||||
self.down_blocks = nn.ModuleList(down_blocks)
|
||||
|
||||
def forward(self, x):
|
||||
outs = [x]
|
||||
for down_block in self.down_blocks:
|
||||
outs.append(down_block(outs[-1]))
|
||||
return outs
|
||||
|
||||
|
||||
class Decoder(nn.Module):
|
||||
"""
|
||||
Hourglass Decoder
|
||||
"""
|
||||
|
||||
def __init__(self, block_expansion, in_features, num_blocks=3, max_features=256):
|
||||
super(Decoder, self).__init__()
|
||||
|
||||
up_blocks = []
|
||||
|
||||
for i in range(num_blocks)[::-1]:
|
||||
in_filters = (1 if i == num_blocks - 1 else 2) * min(max_features, block_expansion * (2 ** (i + 1)))
|
||||
out_filters = min(max_features, block_expansion * (2 ** i))
|
||||
up_blocks.append(UpBlock2d(in_filters, out_filters, kernel_size=3, padding=1))
|
||||
|
||||
self.up_blocks = nn.ModuleList(up_blocks)
|
||||
self.out_filters = block_expansion + in_features
|
||||
|
||||
def forward(self, x):
|
||||
out = x.pop()
|
||||
for up_block in self.up_blocks:
|
||||
out = up_block(out)
|
||||
skip = x.pop()
|
||||
out = torch.cat([out, skip], dim=1)
|
||||
return out
|
||||
|
||||
|
||||
class Hourglass(nn.Module):
|
||||
"""
|
||||
Hourglass architecture.
|
||||
"""
|
||||
def __init__(self, block_expansion, in_features, num_blocks=3, max_features=256):
|
||||
super(Hourglass, self).__init__()
|
||||
self.encoder = Encoder(block_expansion, in_features, num_blocks, max_features)
|
||||
self.decoder = Decoder(block_expansion, in_features, num_blocks, max_features)
|
||||
self.out_filters = self.decoder.out_filters
|
||||
|
||||
def forward(self, x):
|
||||
return self.decoder(self.encoder(x))
|
||||
|
||||
|
||||
class AntiAliasInterpolation2d(nn.Module):
|
||||
def __init__(self, channels, scale):
|
||||
super(AntiAliasInterpolation2d, self).__init__()
|
||||
sigma = (1 / scale - 1) / 2
|
||||
kernel_size = 2 * round(sigma * 4) + 1
|
||||
self.ka = kernel_size // 2
|
||||
self.kb = self.ka - 1 if kernel_size % 2 == 0 else self.ka
|
||||
|
||||
kernel_size = [kernel_size, kernel_size]
|
||||
sigma = [sigma, sigma]
|
||||
# The gaussian kernel is the product of the
|
||||
# gaussian function of each dimension.
|
||||
kernel = 1
|
||||
meshgrids = torch.meshgrid(
|
||||
[
|
||||
torch.arange(size, dtype=torch.float32)
|
||||
for size in kernel_size
|
||||
]
|
||||
)
|
||||
for size, std, mgrid in zip(kernel_size, sigma, meshgrids):
|
||||
mean = (size - 1) / 2
|
||||
kernel *= torch.exp(-(mgrid - mean) ** 2 / (2 * std ** 2))
|
||||
|
||||
# Make sure sum of values in gaussian kernel equals 1.
|
||||
kernel = kernel / torch.sum(kernel)
|
||||
# Reshape to depthwise convolutional weight
|
||||
kernel = kernel.view(1, 1, *kernel.size())
|
||||
kernel = kernel.repeat(channels, *[1] * (kernel.dim() - 1))
|
||||
|
||||
self.register_buffer('weight', kernel)
|
||||
self.groups = channels
|
||||
self.scale = scale
|
||||
inv_scale = 1 / scale
|
||||
self.int_inv_scale = int(inv_scale)
|
||||
|
||||
def forward(self, input):
|
||||
if self.scale == 1.0:
|
||||
return input
|
||||
|
||||
out = F.pad(input, (self.ka, self.kb, self.ka, self.kb))
|
||||
out = F.conv2d(out, weight=self.weight, groups=self.groups)
|
||||
out = out[:, :, ::self.int_inv_scale, ::self.int_inv_scale]
|
||||
|
||||
return out
|
||||
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
|
||||
#python face_obfuscator.py --config config/vox-256-sem-15segments.yaml --checkpoint stuff/vox-15segments.pth.tar --swap_index 2,3,9,11,15
|
||||
def obfuscate(swap_index, source_image, target_image, reconstruction_module, segmentation_module):
|
||||
swapped_image = img_as_ubyte(make_video(swap_index, source_image, target_image, reconstruction_module, segmentation_module, None, False, False, True)[0])
|
||||
matched = match_histograms(swapped_image, target_image, multichannel=True)
|
||||
return matched
|
||||
|
||||
|
||||
def measure_speed():
|
||||
checkpoint = "stuff/vox-15segments.pth.tar"
|
||||
config = "config/vox-256-sem-15segments.yaml"
|
||||
reconstruction_module, segmentation_module = load_checkpoints(config, checkpoint) #TODO hier muss ggf CPU=TRUE gesetzt werden
|
||||
source_image = resize(source_image, (256, 256))[..., :3]
|
||||
target_image = [resize(target_image, (256, 256))[..., :3]]
|
||||
swap_indices = [2, 3, 9, 11, 15]
|
||||
output = obfuscate(swap_indices, source_image, target_image, reconstruction_module, segmentation_module)
|
||||
|
||||
|
||||
def obfuscate_face():
|
||||
path = r'X:\tempEpicRoflImage_IN.jpg'
|
||||
# C:\Users\Bijan\AppData\Local\Temp\tempEpicRoflImage_IN.jpg"
|
||||
target_image = imageio.imread(path)
|
||||
source_image = imageio.imread(r"faces\\" + str(face_index) + ".jpg")
|
||||
source_image = resize(source_image, (256, 256))[..., :3]
|
||||
target_video = [target_image]
|
||||
target_video = [resize(frame, (256, 256))[..., :3] for frame in target_video]
|
||||
predictions = make_video(swap_index, source_image, target_video, reconstruction_module, segmentation_module,
|
||||
face_parser, hard, use_source_segmentation, cpu)
|
||||
swapped_image = img_as_ubyte(predictions[0])
|
||||
matched = match_histograms(swapped_image, target_image, multichannel=True)
|
||||
imageio.imwrite(r'X:\tempEpicRoflImage_OUT.jpg', matched)
|
||||
# C:\Users\Bijan\AppData\Local\Temp\tempEpicRoflImage_OUT.jpg", matched)
|
||||
return json.dumps(True)
|
||||
|
||||
|
||||
def first_run():
|
||||
print('Starting test run')
|
||||
path = r'X:\tempEpicRoflImage_IN.jpg'
|
||||
# C:\Users\Bijan\AppData\Local\Temp\tempEpicRoflImage_IN.jpg
|
||||
target_image = imageio.imread(path)
|
||||
DeepFace.analyze(img_path=path, actions=['emotion'],
|
||||
enforce_detection=False)
|
||||
source_image = imageio.imread(r"faces\\" + str(face_index) + ".jpg")
|
||||
source_image = resize(source_image, (256, 256))[..., :3]
|
||||
target_video = [target_image]
|
||||
target_video = [resize(frame, (256, 256))[..., :3] for frame in target_video]
|
||||
predictions = make_video(swap_index, source_image, target_video, reconstruction_module, segmentation_module,
|
||||
face_parser, hard, use_source_segmentation, cpu)
|
||||
swapped_image = img_as_ubyte(predictions[0])
|
||||
matched = match_histograms(swapped_image, target_image, multichannel=True)
|
||||
imageio.imwrite(path, matched)
|
||||
print('Test run succeeded')
|
||||
return json.dumps(True)
|
||||
|
||||
|
||||
def main():
|
||||
print("TODO")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,242 @@
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use('Agg')
|
||||
|
||||
import yaml
|
||||
from argparse import ArgumentParser
|
||||
from tqdm import tqdm
|
||||
import sys
|
||||
|
||||
import imageio
|
||||
import numpy as np
|
||||
from skimage.transform import resize
|
||||
from skimage import img_as_ubyte
|
||||
|
||||
import torch
|
||||
from sync_batchnorm import DataParallelWithCallback
|
||||
import torch.nn.functional as F
|
||||
|
||||
from modules.segmentation_module import SegmentationModule
|
||||
from modules.reconstruction_module import ReconstructionModule
|
||||
from logger import load_reconstruction_module, load_segmentation_module
|
||||
|
||||
from modules.util import AntiAliasInterpolation2d
|
||||
from modules.dense_motion import DenseMotionNetwork
|
||||
|
||||
|
||||
if sys.version_info[0] < 3:
|
||||
raise Exception("You must use Python 3 or higher. Recommended version is Python 3.7")
|
||||
|
||||
|
||||
class PartSwapGenerator(ReconstructionModule):
|
||||
def __init__(self, blend_scale=1, first_order_motion_model=False, **kwargs):
|
||||
super(PartSwapGenerator, self).__init__(**kwargs)
|
||||
if blend_scale == 1:
|
||||
self.blend_downsample = lambda x: x
|
||||
else:
|
||||
self.blend_downsample = AntiAliasInterpolation2d(1, blend_scale)
|
||||
|
||||
if first_order_motion_model:
|
||||
self.dense_motion_network = DenseMotionNetwork()
|
||||
else:
|
||||
self.dense_motion_network = None
|
||||
|
||||
def forward(self, source_image, target_image, seg_target, seg_source, blend_mask, use_source_segmentation=False):
|
||||
# Encoding of source image
|
||||
enc_source = self.first(source_image)
|
||||
for i in range(len(self.down_blocks)):
|
||||
enc_source = self.down_blocks[i](enc_source)
|
||||
|
||||
# Encoding of target image
|
||||
enc_target = self.first(target_image)
|
||||
for i in range(len(self.down_blocks)):
|
||||
enc_target = self.down_blocks[i](enc_target)
|
||||
|
||||
output_dict = {}
|
||||
# Compute flow field for source image
|
||||
if self.dense_motion_network is None:
|
||||
segment_motions = self.segment_motion(seg_target, seg_source)
|
||||
segment_motions = segment_motions.permute(0, 1, 4, 2, 3)
|
||||
mask = seg_target['segmentation'].unsqueeze(2)
|
||||
deformation = (segment_motions * mask).sum(dim=1)
|
||||
deformation = deformation.permute(0, 2, 3, 1)
|
||||
else:
|
||||
motion = self.dense_motion_network(source_image=source_image, seg_target=seg_target,
|
||||
seg_source=seg_source)
|
||||
deformation = motion['deformation']
|
||||
|
||||
# Deform source encoding according to the motion
|
||||
enc_source = self.deform_input(enc_source, deformation)
|
||||
|
||||
if self.estimate_visibility:
|
||||
if self.dense_motion_network is None:
|
||||
visibility = seg_source['segmentation'][:, 1:].sum(dim=1, keepdim=True) * \
|
||||
(1 - seg_target['segmentation'][:, 1:].sum(dim=1, keepdim=True).detach())
|
||||
visibility = 1 - visibility
|
||||
else:
|
||||
visibility = motion['visibility']
|
||||
|
||||
if enc_source.shape[2] != visibility.shape[2] or enc_source.shape[3] != visibility.shape[3]:
|
||||
visibility = F.interpolate(visibility, size=enc_source.shape[2:], mode='bilinear')
|
||||
enc_source = enc_source * visibility
|
||||
|
||||
blend_mask = self.blend_downsample(blend_mask)
|
||||
# If source segmentation is provided use it should be deformed before blending
|
||||
if use_source_segmentation:
|
||||
blend_mask = self.deform_input(blend_mask, deformation)
|
||||
|
||||
out = enc_target * (1 - blend_mask) + enc_source * blend_mask
|
||||
|
||||
out = self.bottleneck(out)
|
||||
|
||||
for i in range(len(self.up_blocks)):
|
||||
out = self.up_blocks[i](out)
|
||||
|
||||
out = self.final(out)
|
||||
out = F.sigmoid(out)
|
||||
|
||||
output_dict["prediction"] = out
|
||||
|
||||
return output_dict
|
||||
|
||||
|
||||
def load_checkpoints(config, checkpoint, blend_scale=0.125, first_order_motion_model=False, cpu=False):
|
||||
with open(config) as f:
|
||||
config = yaml.load(f)
|
||||
|
||||
reconstruction_module = PartSwapGenerator(blend_scale=blend_scale,
|
||||
first_order_motion_model=first_order_motion_model,
|
||||
**config['model_params']['reconstruction_module_params'],
|
||||
**config['model_params']['common_params'])
|
||||
|
||||
if not cpu:
|
||||
reconstruction_module.cuda()
|
||||
|
||||
segmentation_module = SegmentationModule(**config['model_params']['segmentation_module_params'],
|
||||
**config['model_params']['common_params'])
|
||||
if not cpu:
|
||||
segmentation_module.cuda()
|
||||
|
||||
if cpu:
|
||||
checkpoint = torch.load(checkpoint, map_location=torch.device('cpu'))
|
||||
else:
|
||||
checkpoint = torch.load(checkpoint)
|
||||
|
||||
load_reconstruction_module(reconstruction_module, checkpoint)
|
||||
load_segmentation_module(segmentation_module, checkpoint)
|
||||
|
||||
if not cpu:
|
||||
reconstruction_module = DataParallelWithCallback(reconstruction_module)
|
||||
segmentation_module = DataParallelWithCallback(segmentation_module)
|
||||
|
||||
reconstruction_module.eval()
|
||||
segmentation_module.eval()
|
||||
|
||||
return reconstruction_module, segmentation_module
|
||||
|
||||
|
||||
def load_face_parser(cpu=False):
|
||||
from face_parsing.model import BiSeNet
|
||||
|
||||
face_parser = BiSeNet(n_classes=19)
|
||||
if not cpu:
|
||||
face_parser.cuda()
|
||||
face_parser.load_state_dict(torch.load('face_parsing/cp/79999_iter.pth'))
|
||||
else:
|
||||
face_parser.load_state_dict(torch.load('face_parsing/cp/79999_iter.pth', map_location=torch.device('cpu')))
|
||||
|
||||
face_parser.eval()
|
||||
|
||||
mean = torch.Tensor(np.array([0.485, 0.456, 0.406], dtype=np.float32)).view(1, 3, 1, 1)
|
||||
std = torch.Tensor(np.array([0.229, 0.224, 0.225], dtype=np.float32)).view(1, 3, 1, 1)
|
||||
|
||||
if not cpu:
|
||||
face_parser.mean = mean.cuda()
|
||||
face_parser.std = std.cuda()
|
||||
else:
|
||||
face_parser.mean = mean
|
||||
face_parser.std = std
|
||||
|
||||
return face_parser
|
||||
|
||||
|
||||
def make_video(swap_index, source_image, target_video, reconstruction_module, segmentation_module, face_parser=None,
|
||||
hard=False, use_source_segmentation=False, cpu=False):
|
||||
assert type(swap_index) == list
|
||||
with torch.no_grad():
|
||||
predictions = []
|
||||
source = torch.tensor(source_image[np.newaxis].astype(np.float32)).permute(0, 3, 1, 2)
|
||||
if not cpu:
|
||||
source = source.cuda()
|
||||
target = torch.tensor(np.array(target_video)[np.newaxis].astype(np.float32)).permute(0, 4, 1, 2, 3)
|
||||
seg_source = segmentation_module(source)
|
||||
|
||||
for frame_idx in tqdm(range(target.shape[2])):
|
||||
target_frame = target[:, :, frame_idx]
|
||||
if not cpu:
|
||||
target_frame = target_frame.cuda()
|
||||
|
||||
seg_target = segmentation_module(target_frame)
|
||||
|
||||
# Computing blend mask
|
||||
if face_parser is not None:
|
||||
blend_mask = F.interpolate(source if use_source_segmentation else target_frame, size=(512, 512))
|
||||
blend_mask = (blend_mask - face_parser.mean) / face_parser.std
|
||||
blend_mask = torch.softmax(face_parser(blend_mask)[0], dim=1)
|
||||
else:
|
||||
blend_mask = seg_source['segmentation'] if use_source_segmentation else seg_target['segmentation']
|
||||
|
||||
blend_mask = blend_mask[:, swap_index].sum(dim=1, keepdim=True)
|
||||
if hard:
|
||||
blend_mask = (blend_mask > 0.5).type(blend_mask.type())
|
||||
|
||||
out = reconstruction_module(source, target_frame, seg_source=seg_source, seg_target=seg_target,
|
||||
blend_mask=blend_mask, use_source_segmentation=use_source_segmentation)
|
||||
|
||||
predictions.append(np.transpose(out['prediction'].data.cpu().numpy(), [0, 2, 3, 1])[0])
|
||||
return predictions
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = ArgumentParser()
|
||||
parser.add_argument("--config", required=True, help="path to config")
|
||||
parser.add_argument("--checkpoint", default='vox-cpk.pth.tar', help="path to checkpoint to restore")
|
||||
|
||||
parser.add_argument("--source_image", default='sup-mat/source.png', help="path to source image")
|
||||
parser.add_argument("--target_video", default='sup-mat/source.png', help="path to target video")
|
||||
parser.add_argument("--result_video", default='result.mp4', help="path to output")
|
||||
|
||||
parser.add_argument("--swap_index", default="1,2,5", type=lambda x: list(map(int, x.split(','))),
|
||||
help='index of swaped parts')
|
||||
parser.add_argument("--hard", action="store_true", help="use hard segmentation labels for blending")
|
||||
parser.add_argument("--use_source_segmentation", action="store_true", help="use source segmentation for swaping")
|
||||
parser.add_argument("--first_order_motion_model", action="store_true", help="use first order model for alignment")
|
||||
parser.add_argument("--supervised", action="store_true",
|
||||
help="use supervised segmentation labels for blending. Only for faces.")
|
||||
|
||||
parser.add_argument("--cpu", action="store_true", help="cpu mode")
|
||||
opt = parser.parse_args()
|
||||
|
||||
source_image = imageio.imread(opt.source_image)
|
||||
|
||||
target_video = imageio.mimread(opt.target_video, memtest=False)
|
||||
source_image = resize(source_image, (256, 256))[..., :3]
|
||||
target_video = [resize(frame, (256, 256))[..., :3] for frame in target_video]
|
||||
|
||||
blend_scale = (256 / 4) / 512 if opt.supervised else 1
|
||||
reconstruction_module, segmentation_module = load_checkpoints(opt.config, opt.checkpoint, blend_scale=blend_scale,
|
||||
first_order_motion_model=opt.first_order_motion_model, cpu=opt.cpu)
|
||||
|
||||
if opt.supervised:
|
||||
face_parser = load_face_parser(opt.cpu)
|
||||
else:
|
||||
face_parser = None
|
||||
predictions = make_video(opt.swap_index, source_image, target_video, reconstruction_module, segmentation_module,
|
||||
face_parser, hard=opt.hard, use_source_segmentation=opt.use_source_segmentation, cpu=opt.cpu)
|
||||
|
||||
# Read fps of the target video and save result with the same fps
|
||||
reader = imageio.get_reader(opt.target_video)
|
||||
fps = reader.get_meta_data()['fps']
|
||||
reader.close()
|
||||
|
||||
imageio.mimsave(opt.result_video, [img_as_ubyte(frame) for frame in predictions], fps=fps)
|
||||
@@ -0,0 +1,27 @@
|
||||
cffi==1.11.5
|
||||
cloudpickle==0.5.3
|
||||
cycler==0.10.0
|
||||
dask==0.18.2
|
||||
decorator==4.3.0
|
||||
imageio==2.3.0
|
||||
kiwisolver==1.0.1
|
||||
matplotlib==2.2.2
|
||||
networkx==2.1
|
||||
numpy==1.15.0
|
||||
pandas==0.23.4
|
||||
Pillow==5.2.0
|
||||
pycparser==2.18
|
||||
pygit==0.1
|
||||
pyparsing==2.2.0
|
||||
python-dateutil==2.7.3
|
||||
pytz==2018.5
|
||||
PyWavelets==0.5.2
|
||||
PyYAML==3.13
|
||||
scikit-image==0.14.0
|
||||
scikit-learn==0.19.2
|
||||
scipy==1.1.0
|
||||
six==1.11.0
|
||||
toolz==0.9.0
|
||||
torch==1.0.0
|
||||
torchvision==0.2.1
|
||||
tqdm==4.24.0
|
||||
@@ -0,0 +1,12 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# File : __init__.py
|
||||
# Author : Jiayuan Mao
|
||||
# Email : maojiayuan@gmail.com
|
||||
# Date : 27/01/2018
|
||||
#
|
||||
# This file is part of Synchronized-BatchNorm-PyTorch.
|
||||
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
|
||||
# Distributed under MIT License.
|
||||
|
||||
from .batchnorm import SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, SynchronizedBatchNorm3d
|
||||
from .replicate import DataParallelWithCallback, patch_replication_callback
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,315 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# File : batchnorm.py
|
||||
# Author : Jiayuan Mao
|
||||
# Email : maojiayuan@gmail.com
|
||||
# Date : 27/01/2018
|
||||
#
|
||||
# This file is part of Synchronized-BatchNorm-PyTorch.
|
||||
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
|
||||
# Distributed under MIT License.
|
||||
|
||||
import collections
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
from torch.nn.modules.batchnorm import _BatchNorm
|
||||
from torch.nn.parallel._functions import ReduceAddCoalesced, Broadcast
|
||||
|
||||
from .comm import SyncMaster
|
||||
|
||||
__all__ = ['SynchronizedBatchNorm1d', 'SynchronizedBatchNorm2d', 'SynchronizedBatchNorm3d']
|
||||
|
||||
|
||||
def _sum_ft(tensor):
|
||||
"""sum over the first and last dimention"""
|
||||
return tensor.sum(dim=0).sum(dim=-1)
|
||||
|
||||
|
||||
def _unsqueeze_ft(tensor):
|
||||
"""add new dementions at the front and the tail"""
|
||||
return tensor.unsqueeze(0).unsqueeze(-1)
|
||||
|
||||
|
||||
_ChildMessage = collections.namedtuple('_ChildMessage', ['sum', 'ssum', 'sum_size'])
|
||||
_MasterMessage = collections.namedtuple('_MasterMessage', ['sum', 'inv_std'])
|
||||
|
||||
|
||||
class _SynchronizedBatchNorm(_BatchNorm):
|
||||
def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True):
|
||||
super(_SynchronizedBatchNorm, self).__init__(num_features, eps=eps, momentum=momentum, affine=affine)
|
||||
|
||||
self._sync_master = SyncMaster(self._data_parallel_master)
|
||||
|
||||
self._is_parallel = False
|
||||
self._parallel_id = None
|
||||
self._slave_pipe = None
|
||||
|
||||
def forward(self, input):
|
||||
# If it is not parallel computation or is in evaluation mode, use PyTorch's implementation.
|
||||
if not (self._is_parallel and self.training):
|
||||
return F.batch_norm(
|
||||
input, self.running_mean, self.running_var, self.weight, self.bias,
|
||||
self.training, self.momentum, self.eps)
|
||||
|
||||
# Resize the input to (B, C, -1).
|
||||
input_shape = input.size()
|
||||
input = input.view(input.size(0), self.num_features, -1)
|
||||
|
||||
# Compute the sum and square-sum.
|
||||
sum_size = input.size(0) * input.size(2)
|
||||
input_sum = _sum_ft(input)
|
||||
input_ssum = _sum_ft(input ** 2)
|
||||
|
||||
# Reduce-and-broadcast the statistics.
|
||||
if self._parallel_id == 0:
|
||||
mean, inv_std = self._sync_master.run_master(_ChildMessage(input_sum, input_ssum, sum_size))
|
||||
else:
|
||||
mean, inv_std = self._slave_pipe.run_slave(_ChildMessage(input_sum, input_ssum, sum_size))
|
||||
|
||||
# Compute the output.
|
||||
if self.affine:
|
||||
# MJY:: Fuse the multiplication for speed.
|
||||
output = (input - _unsqueeze_ft(mean)) * _unsqueeze_ft(inv_std * self.weight) + _unsqueeze_ft(self.bias)
|
||||
else:
|
||||
output = (input - _unsqueeze_ft(mean)) * _unsqueeze_ft(inv_std)
|
||||
|
||||
# Reshape it.
|
||||
return output.view(input_shape)
|
||||
|
||||
def __data_parallel_replicate__(self, ctx, copy_id):
|
||||
self._is_parallel = True
|
||||
self._parallel_id = copy_id
|
||||
|
||||
# parallel_id == 0 means master device.
|
||||
if self._parallel_id == 0:
|
||||
ctx.sync_master = self._sync_master
|
||||
else:
|
||||
self._slave_pipe = ctx.sync_master.register_slave(copy_id)
|
||||
|
||||
def _data_parallel_master(self, intermediates):
|
||||
"""Reduce the sum and square-sum, compute the statistics, and broadcast it."""
|
||||
|
||||
# Always using same "device order" makes the ReduceAdd operation faster.
|
||||
# Thanks to:: Tete Xiao (http://tetexiao.com/)
|
||||
intermediates = sorted(intermediates, key=lambda i: i[1].sum.get_device())
|
||||
|
||||
to_reduce = [i[1][:2] for i in intermediates]
|
||||
to_reduce = [j for i in to_reduce for j in i] # flatten
|
||||
target_gpus = [i[1].sum.get_device() for i in intermediates]
|
||||
|
||||
sum_size = sum([i[1].sum_size for i in intermediates])
|
||||
sum_, ssum = ReduceAddCoalesced.apply(target_gpus[0], 2, *to_reduce)
|
||||
mean, inv_std = self._compute_mean_std(sum_, ssum, sum_size)
|
||||
|
||||
broadcasted = Broadcast.apply(target_gpus, mean, inv_std)
|
||||
|
||||
outputs = []
|
||||
for i, rec in enumerate(intermediates):
|
||||
outputs.append((rec[0], _MasterMessage(*broadcasted[i*2:i*2+2])))
|
||||
|
||||
return outputs
|
||||
|
||||
def _compute_mean_std(self, sum_, ssum, size):
|
||||
"""Compute the mean and standard-deviation with sum and square-sum. This method
|
||||
also maintains the moving average on the master device."""
|
||||
assert size > 1, 'BatchNorm computes unbiased standard-deviation, which requires size > 1.'
|
||||
mean = sum_ / size
|
||||
sumvar = ssum - sum_ * mean
|
||||
unbias_var = sumvar / (size - 1)
|
||||
bias_var = sumvar / size
|
||||
|
||||
self.running_mean = (1 - self.momentum) * self.running_mean + self.momentum * mean.data
|
||||
self.running_var = (1 - self.momentum) * self.running_var + self.momentum * unbias_var.data
|
||||
|
||||
return mean, bias_var.clamp(self.eps) ** -0.5
|
||||
|
||||
|
||||
class SynchronizedBatchNorm1d(_SynchronizedBatchNorm):
|
||||
r"""Applies Synchronized Batch Normalization over a 2d or 3d input that is seen as a
|
||||
mini-batch.
|
||||
|
||||
.. math::
|
||||
|
||||
y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta
|
||||
|
||||
This module differs from the built-in PyTorch BatchNorm1d as the mean and
|
||||
standard-deviation are reduced across all devices during training.
|
||||
|
||||
For example, when one uses `nn.DataParallel` to wrap the network during
|
||||
training, PyTorch's implementation normalize the tensor on each device using
|
||||
the statistics only on that device, which accelerated the computation and
|
||||
is also easy to implement, but the statistics might be inaccurate.
|
||||
Instead, in this synchronized version, the statistics will be computed
|
||||
over all training samples distributed on multiple devices.
|
||||
|
||||
Note that, for one-GPU or CPU-only case, this module behaves exactly same
|
||||
as the built-in PyTorch implementation.
|
||||
|
||||
The mean and standard-deviation are calculated per-dimension over
|
||||
the mini-batches and gamma and beta are learnable parameter vectors
|
||||
of size C (where C is the input size).
|
||||
|
||||
During training, this layer keeps a running estimate of its computed mean
|
||||
and variance. The running sum is kept with a default momentum of 0.1.
|
||||
|
||||
During evaluation, this running mean/variance is used for normalization.
|
||||
|
||||
Because the BatchNorm is done over the `C` dimension, computing statistics
|
||||
on `(N, L)` slices, it's common terminology to call this Temporal BatchNorm
|
||||
|
||||
Args:
|
||||
num_features: num_features from an expected input of size
|
||||
`batch_size x num_features [x width]`
|
||||
eps: a value added to the denominator for numerical stability.
|
||||
Default: 1e-5
|
||||
momentum: the value used for the running_mean and running_var
|
||||
computation. Default: 0.1
|
||||
affine: a boolean value that when set to ``True``, gives the layer learnable
|
||||
affine parameters. Default: ``True``
|
||||
|
||||
Shape:
|
||||
- Input: :math:`(N, C)` or :math:`(N, C, L)`
|
||||
- Output: :math:`(N, C)` or :math:`(N, C, L)` (same shape as input)
|
||||
|
||||
Examples:
|
||||
>>> # With Learnable Parameters
|
||||
>>> m = SynchronizedBatchNorm1d(100)
|
||||
>>> # Without Learnable Parameters
|
||||
>>> m = SynchronizedBatchNorm1d(100, affine=False)
|
||||
>>> input = torch.autograd.Variable(torch.randn(20, 100))
|
||||
>>> output = m(input)
|
||||
"""
|
||||
|
||||
def _check_input_dim(self, input):
|
||||
if input.dim() != 2 and input.dim() != 3:
|
||||
raise ValueError('expected 2D or 3D input (got {}D input)'
|
||||
.format(input.dim()))
|
||||
super(SynchronizedBatchNorm1d, self)._check_input_dim(input)
|
||||
|
||||
|
||||
class SynchronizedBatchNorm2d(_SynchronizedBatchNorm):
|
||||
r"""Applies Batch Normalization over a 4d input that is seen as a mini-batch
|
||||
of 3d inputs
|
||||
|
||||
.. math::
|
||||
|
||||
y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta
|
||||
|
||||
This module differs from the built-in PyTorch BatchNorm2d as the mean and
|
||||
standard-deviation are reduced across all devices during training.
|
||||
|
||||
For example, when one uses `nn.DataParallel` to wrap the network during
|
||||
training, PyTorch's implementation normalize the tensor on each device using
|
||||
the statistics only on that device, which accelerated the computation and
|
||||
is also easy to implement, but the statistics might be inaccurate.
|
||||
Instead, in this synchronized version, the statistics will be computed
|
||||
over all training samples distributed on multiple devices.
|
||||
|
||||
Note that, for one-GPU or CPU-only case, this module behaves exactly same
|
||||
as the built-in PyTorch implementation.
|
||||
|
||||
The mean and standard-deviation are calculated per-dimension over
|
||||
the mini-batches and gamma and beta are learnable parameter vectors
|
||||
of size C (where C is the input size).
|
||||
|
||||
During training, this layer keeps a running estimate of its computed mean
|
||||
and variance. The running sum is kept with a default momentum of 0.1.
|
||||
|
||||
During evaluation, this running mean/variance is used for normalization.
|
||||
|
||||
Because the BatchNorm is done over the `C` dimension, computing statistics
|
||||
on `(N, H, W)` slices, it's common terminology to call this Spatial BatchNorm
|
||||
|
||||
Args:
|
||||
num_features: num_features from an expected input of
|
||||
size batch_size x num_features x height x width
|
||||
eps: a value added to the denominator for numerical stability.
|
||||
Default: 1e-5
|
||||
momentum: the value used for the running_mean and running_var
|
||||
computation. Default: 0.1
|
||||
affine: a boolean value that when set to ``True``, gives the layer learnable
|
||||
affine parameters. Default: ``True``
|
||||
|
||||
Shape:
|
||||
- Input: :math:`(N, C, H, W)`
|
||||
- Output: :math:`(N, C, H, W)` (same shape as input)
|
||||
|
||||
Examples:
|
||||
>>> # With Learnable Parameters
|
||||
>>> m = SynchronizedBatchNorm2d(100)
|
||||
>>> # Without Learnable Parameters
|
||||
>>> m = SynchronizedBatchNorm2d(100, affine=False)
|
||||
>>> input = torch.autograd.Variable(torch.randn(20, 100, 35, 45))
|
||||
>>> output = m(input)
|
||||
"""
|
||||
|
||||
def _check_input_dim(self, input):
|
||||
if input.dim() != 4:
|
||||
raise ValueError('expected 4D input (got {}D input)'
|
||||
.format(input.dim()))
|
||||
super(SynchronizedBatchNorm2d, self)._check_input_dim(input)
|
||||
|
||||
|
||||
class SynchronizedBatchNorm3d(_SynchronizedBatchNorm):
|
||||
r"""Applies Batch Normalization over a 5d input that is seen as a mini-batch
|
||||
of 4d inputs
|
||||
|
||||
.. math::
|
||||
|
||||
y = \frac{x - mean[x]}{ \sqrt{Var[x] + \epsilon}} * gamma + beta
|
||||
|
||||
This module differs from the built-in PyTorch BatchNorm3d as the mean and
|
||||
standard-deviation are reduced across all devices during training.
|
||||
|
||||
For example, when one uses `nn.DataParallel` to wrap the network during
|
||||
training, PyTorch's implementation normalize the tensor on each device using
|
||||
the statistics only on that device, which accelerated the computation and
|
||||
is also easy to implement, but the statistics might be inaccurate.
|
||||
Instead, in this synchronized version, the statistics will be computed
|
||||
over all training samples distributed on multiple devices.
|
||||
|
||||
Note that, for one-GPU or CPU-only case, this module behaves exactly same
|
||||
as the built-in PyTorch implementation.
|
||||
|
||||
The mean and standard-deviation are calculated per-dimension over
|
||||
the mini-batches and gamma and beta are learnable parameter vectors
|
||||
of size C (where C is the input size).
|
||||
|
||||
During training, this layer keeps a running estimate of its computed mean
|
||||
and variance. The running sum is kept with a default momentum of 0.1.
|
||||
|
||||
During evaluation, this running mean/variance is used for normalization.
|
||||
|
||||
Because the BatchNorm is done over the `C` dimension, computing statistics
|
||||
on `(N, D, H, W)` slices, it's common terminology to call this Volumetric BatchNorm
|
||||
or Spatio-temporal BatchNorm
|
||||
|
||||
Args:
|
||||
num_features: num_features from an expected input of
|
||||
size batch_size x num_features x depth x height x width
|
||||
eps: a value added to the denominator for numerical stability.
|
||||
Default: 1e-5
|
||||
momentum: the value used for the running_mean and running_var
|
||||
computation. Default: 0.1
|
||||
affine: a boolean value that when set to ``True``, gives the layer learnable
|
||||
affine parameters. Default: ``True``
|
||||
|
||||
Shape:
|
||||
- Input: :math:`(N, C, D, H, W)`
|
||||
- Output: :math:`(N, C, D, H, W)` (same shape as input)
|
||||
|
||||
Examples:
|
||||
>>> # With Learnable Parameters
|
||||
>>> m = SynchronizedBatchNorm3d(100)
|
||||
>>> # Without Learnable Parameters
|
||||
>>> m = SynchronizedBatchNorm3d(100, affine=False)
|
||||
>>> input = torch.autograd.Variable(torch.randn(20, 100, 35, 45, 10))
|
||||
>>> output = m(input)
|
||||
"""
|
||||
|
||||
def _check_input_dim(self, input):
|
||||
if input.dim() != 5:
|
||||
raise ValueError('expected 5D input (got {}D input)'
|
||||
.format(input.dim()))
|
||||
super(SynchronizedBatchNorm3d, self)._check_input_dim(input)
|
||||
@@ -0,0 +1,137 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# File : comm.py
|
||||
# Author : Jiayuan Mao
|
||||
# Email : maojiayuan@gmail.com
|
||||
# Date : 27/01/2018
|
||||
#
|
||||
# This file is part of Synchronized-BatchNorm-PyTorch.
|
||||
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
|
||||
# Distributed under MIT License.
|
||||
|
||||
import queue
|
||||
import collections
|
||||
import threading
|
||||
|
||||
__all__ = ['FutureResult', 'SlavePipe', 'SyncMaster']
|
||||
|
||||
|
||||
class FutureResult(object):
|
||||
"""A thread-safe future implementation. Used only as one-to-one pipe."""
|
||||
|
||||
def __init__(self):
|
||||
self._result = None
|
||||
self._lock = threading.Lock()
|
||||
self._cond = threading.Condition(self._lock)
|
||||
|
||||
def put(self, result):
|
||||
with self._lock:
|
||||
assert self._result is None, 'Previous result has\'t been fetched.'
|
||||
self._result = result
|
||||
self._cond.notify()
|
||||
|
||||
def get(self):
|
||||
with self._lock:
|
||||
if self._result is None:
|
||||
self._cond.wait()
|
||||
|
||||
res = self._result
|
||||
self._result = None
|
||||
return res
|
||||
|
||||
|
||||
_MasterRegistry = collections.namedtuple('MasterRegistry', ['result'])
|
||||
_SlavePipeBase = collections.namedtuple('_SlavePipeBase', ['identifier', 'queue', 'result'])
|
||||
|
||||
|
||||
class SlavePipe(_SlavePipeBase):
|
||||
"""Pipe for master-slave communication."""
|
||||
|
||||
def run_slave(self, msg):
|
||||
self.queue.put((self.identifier, msg))
|
||||
ret = self.result.get()
|
||||
self.queue.put(True)
|
||||
return ret
|
||||
|
||||
|
||||
class SyncMaster(object):
|
||||
"""An abstract `SyncMaster` object.
|
||||
|
||||
- During the replication, as the data parallel will trigger an callback of each module, all slave devices should
|
||||
call `register(id)` and obtain an `SlavePipe` to communicate with the master.
|
||||
- During the forward pass, master device invokes `run_master`, all messages from slave devices will be collected,
|
||||
and passed to a registered callback.
|
||||
- After receiving the messages, the master device should gather the information and determine to message passed
|
||||
back to each slave devices.
|
||||
"""
|
||||
|
||||
def __init__(self, master_callback):
|
||||
"""
|
||||
|
||||
Args:
|
||||
master_callback: a callback to be invoked after having collected messages from slave devices.
|
||||
"""
|
||||
self._master_callback = master_callback
|
||||
self._queue = queue.Queue()
|
||||
self._registry = collections.OrderedDict()
|
||||
self._activated = False
|
||||
|
||||
def __getstate__(self):
|
||||
return {'master_callback': self._master_callback}
|
||||
|
||||
def __setstate__(self, state):
|
||||
self.__init__(state['master_callback'])
|
||||
|
||||
def register_slave(self, identifier):
|
||||
"""
|
||||
Register an slave device.
|
||||
|
||||
Args:
|
||||
identifier: an identifier, usually is the device id.
|
||||
|
||||
Returns: a `SlavePipe` object which can be used to communicate with the master device.
|
||||
|
||||
"""
|
||||
if self._activated:
|
||||
assert self._queue.empty(), 'Queue is not clean before next initialization.'
|
||||
self._activated = False
|
||||
self._registry.clear()
|
||||
future = FutureResult()
|
||||
self._registry[identifier] = _MasterRegistry(future)
|
||||
return SlavePipe(identifier, self._queue, future)
|
||||
|
||||
def run_master(self, master_msg):
|
||||
"""
|
||||
Main entry for the master device in each forward pass.
|
||||
The messages were first collected from each devices (including the master device), and then
|
||||
an callback will be invoked to compute the message to be sent back to each devices
|
||||
(including the master device).
|
||||
|
||||
Args:
|
||||
master_msg: the message that the master want to send to itself. This will be placed as the first
|
||||
message when calling `master_callback`. For detailed usage, see `_SynchronizedBatchNorm` for an example.
|
||||
|
||||
Returns: the message to be sent back to the master device.
|
||||
|
||||
"""
|
||||
self._activated = True
|
||||
|
||||
intermediates = [(0, master_msg)]
|
||||
for i in range(self.nr_slaves):
|
||||
intermediates.append(self._queue.get())
|
||||
|
||||
results = self._master_callback(intermediates)
|
||||
assert results[0][0] == 0, 'The first result should belongs to the master.'
|
||||
|
||||
for i, res in results:
|
||||
if i == 0:
|
||||
continue
|
||||
self._registry[i].result.put(res)
|
||||
|
||||
for i in range(self.nr_slaves):
|
||||
assert self._queue.get() is True
|
||||
|
||||
return results[0][1]
|
||||
|
||||
@property
|
||||
def nr_slaves(self):
|
||||
return len(self._registry)
|
||||
@@ -0,0 +1,94 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# File : replicate.py
|
||||
# Author : Jiayuan Mao
|
||||
# Email : maojiayuan@gmail.com
|
||||
# Date : 27/01/2018
|
||||
#
|
||||
# This file is part of Synchronized-BatchNorm-PyTorch.
|
||||
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
|
||||
# Distributed under MIT License.
|
||||
|
||||
import functools
|
||||
|
||||
from torch.nn.parallel.data_parallel import DataParallel
|
||||
|
||||
__all__ = [
|
||||
'CallbackContext',
|
||||
'execute_replication_callbacks',
|
||||
'DataParallelWithCallback',
|
||||
'patch_replication_callback'
|
||||
]
|
||||
|
||||
|
||||
class CallbackContext(object):
|
||||
pass
|
||||
|
||||
|
||||
def execute_replication_callbacks(modules):
|
||||
"""
|
||||
Execute an replication callback `__data_parallel_replicate__` on each module created by original replication.
|
||||
|
||||
The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)`
|
||||
|
||||
Note that, as all modules are isomorphism, we assign each sub-module with a context
|
||||
(shared among multiple copies of this module on different devices).
|
||||
Through this context, different copies can share some information.
|
||||
|
||||
We guarantee that the callback on the master copy (the first copy) will be called ahead of calling the callback
|
||||
of any slave copies.
|
||||
"""
|
||||
master_copy = modules[0]
|
||||
nr_modules = len(list(master_copy.modules()))
|
||||
ctxs = [CallbackContext() for _ in range(nr_modules)]
|
||||
|
||||
for i, module in enumerate(modules):
|
||||
for j, m in enumerate(module.modules()):
|
||||
if hasattr(m, '__data_parallel_replicate__'):
|
||||
m.__data_parallel_replicate__(ctxs[j], i)
|
||||
|
||||
|
||||
class DataParallelWithCallback(DataParallel):
|
||||
"""
|
||||
Data Parallel with a replication callback.
|
||||
|
||||
An replication callback `__data_parallel_replicate__` of each module will be invoked after being created by
|
||||
original `replicate` function.
|
||||
The callback will be invoked with arguments `__data_parallel_replicate__(ctx, copy_id)`
|
||||
|
||||
Examples:
|
||||
> sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False)
|
||||
> sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1])
|
||||
# sync_bn.__data_parallel_replicate__ will be invoked.
|
||||
"""
|
||||
|
||||
def replicate(self, module, device_ids):
|
||||
modules = super(DataParallelWithCallback, self).replicate(module, device_ids)
|
||||
execute_replication_callbacks(modules)
|
||||
return modules
|
||||
|
||||
|
||||
def patch_replication_callback(data_parallel):
|
||||
"""
|
||||
Monkey-patch an existing `DataParallel` object. Add the replication callback.
|
||||
Useful when you have customized `DataParallel` implementation.
|
||||
|
||||
Examples:
|
||||
> sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False)
|
||||
> sync_bn = DataParallel(sync_bn, device_ids=[0, 1])
|
||||
> patch_replication_callback(sync_bn)
|
||||
# this is equivalent to
|
||||
> sync_bn = SynchronizedBatchNorm1d(10, eps=1e-5, affine=False)
|
||||
> sync_bn = DataParallelWithCallback(sync_bn, device_ids=[0, 1])
|
||||
"""
|
||||
|
||||
assert isinstance(data_parallel, DataParallel)
|
||||
|
||||
old_replicate = data_parallel.replicate
|
||||
|
||||
@functools.wraps(old_replicate)
|
||||
def new_replicate(module, device_ids):
|
||||
modules = old_replicate(module, device_ids)
|
||||
execute_replication_callbacks(modules)
|
||||
return modules
|
||||
|
||||
data_parallel.replicate = new_replicate
|
||||
@@ -0,0 +1,29 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# File : unittest.py
|
||||
# Author : Jiayuan Mao
|
||||
# Email : maojiayuan@gmail.com
|
||||
# Date : 27/01/2018
|
||||
#
|
||||
# This file is part of Synchronized-BatchNorm-PyTorch.
|
||||
# https://github.com/vacancy/Synchronized-BatchNorm-PyTorch
|
||||
# Distributed under MIT License.
|
||||
|
||||
import unittest
|
||||
|
||||
import numpy as np
|
||||
from torch.autograd import Variable
|
||||
|
||||
|
||||
def as_numpy(v):
|
||||
if isinstance(v, Variable):
|
||||
v = v.data
|
||||
return v.cpu().numpy()
|
||||
|
||||
|
||||
class TorchTestCase(unittest.TestCase):
|
||||
def assertTensorClose(self, a, b, atol=1e-3, rtol=1e-3):
|
||||
npa, npb = as_numpy(a), as_numpy(b)
|
||||
self.assertTrue(
|
||||
np.allclose(npa, npb, atol=atol),
|
||||
'Tensor close check failed\n{}\n{}\nadiff={}, rdiff={}'.format(a, b, np.abs(npa - npb).max(), np.abs((npa - npb) / np.fmax(npa, 1e-5)).max())
|
||||
)
|
||||
@@ -0,0 +1,110 @@
|
||||
import matplotlib
|
||||
|
||||
matplotlib.use('Agg')
|
||||
import os
|
||||
from tqdm import trange
|
||||
import torch
|
||||
import yaml
|
||||
|
||||
from torch.utils.data import DataLoader
|
||||
from sync_batchnorm import DataParallelWithCallback
|
||||
|
||||
from argparse import ArgumentParser
|
||||
from time import gmtime, strftime
|
||||
from shutil import copy
|
||||
|
||||
from modules.reconstruction_module import ReconstructionModule
|
||||
from modules.segmentation_module import SegmentationModule
|
||||
from logger import Logger
|
||||
from modules.model import FullModel
|
||||
|
||||
from frames_dataset import DatasetRepeater
|
||||
from frames_dataset import FramesDataset
|
||||
|
||||
|
||||
def train(config, reconstruction_module, segmentation_module, checkpoint, log_dir, dataset, device_ids):
|
||||
train_params = config['train_params']
|
||||
|
||||
optimizer_reconstruction_module = torch.optim.Adam(reconstruction_module.parameters(),
|
||||
lr=train_params['lr_reconstruction_module'], betas=(0.5, 0.999))
|
||||
optimizer_segmentation_module = torch.optim.Adam(segmentation_module.parameters(),
|
||||
lr=train_params['lr_segmentation_module'], betas=(0.5, 0.999))
|
||||
if checkpoint is not None:
|
||||
start_epoch = Logger.load_cpk(checkpoint, reconstruction_module, segmentation_module,
|
||||
optimizer_reconstruction_module, optimizer_segmentation_module)
|
||||
else:
|
||||
start_epoch = 0
|
||||
|
||||
if 'num_repeats' in train_params or train_params['num_repeats'] != 1:
|
||||
dataset = DatasetRepeater(dataset, train_params['num_repeats'])
|
||||
dataloader = DataLoader(dataset, batch_size=train_params['batch_size'], shuffle=True,
|
||||
num_workers=train_params['num_workers'], drop_last=True)
|
||||
|
||||
model = FullModel(segmentation_module, reconstruction_module, train_params)
|
||||
|
||||
reconstruction_module_full_par = DataParallelWithCallback(model, device_ids=device_ids)
|
||||
|
||||
with Logger(log_dir=log_dir, visualizer_params=config['visualizer_params'],
|
||||
checkpoint_freq=train_params['checkpoint_freq']) as logger:
|
||||
for epoch in trange(start_epoch, train_params['num_epochs']):
|
||||
for x in dataloader:
|
||||
losses_reconstruction_module, generated = reconstruction_module_full_par(x)
|
||||
|
||||
loss_values = [val.mean() for val in losses_reconstruction_module.values()]
|
||||
loss = sum(loss_values)
|
||||
|
||||
loss.backward()
|
||||
optimizer_reconstruction_module.step()
|
||||
optimizer_reconstruction_module.zero_grad()
|
||||
optimizer_segmentation_module.step()
|
||||
optimizer_segmentation_module.zero_grad()
|
||||
|
||||
losses = {key: value.mean().detach().data.cpu().numpy() for key, value in
|
||||
losses_reconstruction_module.items()}
|
||||
logger.log_iter(losses=losses)
|
||||
|
||||
logger.log_epoch(epoch, {'reconstruction_module': reconstruction_module,
|
||||
'segmentation_module': segmentation_module,
|
||||
'optimizer_reconstruction_module': optimizer_reconstruction_module,
|
||||
'optimizer_segmentation_module': optimizer_segmentation_module}, inp=x,
|
||||
out=generated)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = ArgumentParser()
|
||||
parser.add_argument("--config", required=True, help="path to config")
|
||||
parser.add_argument("--log_dir", default='log', help="path to log into")
|
||||
parser.add_argument("--checkpoint", default=None, help="path to checkpoint to restore")
|
||||
parser.add_argument("--device_ids", default="0", type=lambda x: list(map(int, x.split(','))),
|
||||
help="Names of the devices comma separated.")
|
||||
parser.add_argument("--verbose", dest="verbose", action="store_true", help="Print model architecture")
|
||||
parser.set_defaults(verbose=False)
|
||||
|
||||
opt = parser.parse_args()
|
||||
with open(opt.config) as f:
|
||||
config = yaml.load(f)
|
||||
|
||||
log_dir = os.path.join(opt.log_dir, os.path.basename(opt.config).split('.')[0])
|
||||
log_dir += ' ' + strftime("%d-%m-%y %H:%M:%S", gmtime())
|
||||
|
||||
reconstruction_module = ReconstructionModule(**config['model_params']['reconstruction_module_params'],
|
||||
**config['model_params']['common_params'])
|
||||
reconstruction_module.to(opt.device_ids[0])
|
||||
if opt.verbose:
|
||||
print(reconstruction_module)
|
||||
|
||||
segmentation_module = SegmentationModule(**config['model_params']['segmentation_module_params'],
|
||||
**config['model_params']['common_params'])
|
||||
segmentation_module.to(opt.device_ids[0])
|
||||
if opt.verbose:
|
||||
print(segmentation_module)
|
||||
|
||||
dataset = FramesDataset(is_train=True, **config['dataset_params'])
|
||||
|
||||
if not os.path.exists(log_dir):
|
||||
os.makedirs(log_dir)
|
||||
if not os.path.exists(os.path.join(log_dir, os.path.basename(opt.config))):
|
||||
copy(opt.config, log_dir)
|
||||
|
||||
print("Training...")
|
||||
train(config, reconstruction_module, segmentation_module, opt.checkpoint, log_dir, dataset, opt.device_ids)
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,32 @@
|
||||
import numpy as np
|
||||
|
||||
from obfuscation.base_obfuscation_technique import ObfuscationTechnique
|
||||
from models.epic.face_obfuscator import EPIC
|
||||
|
||||
class Epic(ObfuscationTechnique):
|
||||
"""
|
||||
Replace face with generated face
|
||||
"""
|
||||
def __init__(self):
|
||||
|
||||
#TODO: yolo11m-pose usw. git ignore anpassen
|
||||
|
||||
#TODO: In face_obfuscator.py alle imports nochmal anpassen
|
||||
#TODO: da drin nochmal alle sub dinger prüfen was da angepasst wurde jeweils
|
||||
|
||||
#TODO: in conda python 3.7 umgebung erstellen und einrichten mit requirements usw.
|
||||
#TODO: chatgpt checken
|
||||
#TODO: server, client anpassen
|
||||
|
||||
#TODO: Für alle anderen modelle das gleiche tun mit anderen python versionen
|
||||
|
||||
checkpoint_path = "models/epic/stuff/vox-15segments.pth.tar"
|
||||
config_path = "models/epic/config/vox-256-sem-15segments.yaml"
|
||||
fake_face_path = "models/epic/stuff/fake_face.jpg"
|
||||
self.model = EPIC(checkpoint_path=checkpoint_path, config_path=config_path, fake_face_path=fake_face_path)
|
||||
|
||||
def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray:
|
||||
return self.model.obfuscate(face_roi_img_bgr)
|
||||
|
||||
def name(self):
|
||||
return "EPIC"
|
||||
@@ -1,64 +0,0 @@
|
||||
import cv2
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
|
||||
from obfuscation.base_obfuscation_technique import ObfuscationTechnique
|
||||
import torch
|
||||
from transformers import CLIPImageProcessor, CLIPVisionModel
|
||||
|
||||
from diffusers import AutoencoderKL, DDPMScheduler
|
||||
from models.face_anon_simple.src.diffusers.models.referencenet.referencenet_unet_2d_condition import ReferenceNetModel
|
||||
from models.face_anon_simple.src.diffusers.models.referencenet.unet_2d_condition import UNet2DConditionModel
|
||||
from models.face_anon_simple.src.diffusers.pipelines.referencenet.pipeline_referencenet import StableDiffusionReferenceNetPipeline
|
||||
|
||||
class FAMS(ObfuscationTechnique):
|
||||
|
||||
def __init__(self):
|
||||
face_model_id = "hkung/face-anon-simple"
|
||||
clip_model_id = "openai/clip-vit-large-patch14"
|
||||
sd_model_id = "stabilityai/stable-diffusion-2-1"
|
||||
|
||||
unet = UNet2DConditionModel.from_pretrained(face_model_id, subfolder="unet", use_safetensors=True)
|
||||
referencenet = ReferenceNetModel.from_pretrained(face_model_id, subfolder="referencenet", use_safetensors=True)
|
||||
conditioning_referencenet = ReferenceNetModel.from_pretrained(face_model_id, subfolder="conditioning_referencenet", use_safetensors=True)
|
||||
vae = AutoencoderKL.from_pretrained(sd_model_id, subfolder="vae", use_safetensors=True)
|
||||
scheduler = DDPMScheduler.from_pretrained(sd_model_id, subfolder="scheduler", use_safetensors=True)
|
||||
feature_extractor = CLIPImageProcessor.from_pretrained(clip_model_id, use_safetensors=True)
|
||||
image_encoder = CLIPVisionModel.from_pretrained(clip_model_id, use_safetensors=True)
|
||||
|
||||
self.pipe = StableDiffusionReferenceNetPipeline(
|
||||
unet=unet,
|
||||
referencenet=referencenet,
|
||||
conditioning_referencenet=conditioning_referencenet,
|
||||
vae=vae,
|
||||
feature_extractor=feature_extractor,
|
||||
image_encoder=image_encoder,
|
||||
scheduler=scheduler,
|
||||
)
|
||||
self.pipe = self.pipe.to("cuda")
|
||||
self.generator = torch.manual_seed(1)
|
||||
|
||||
|
||||
def obfuscate(self, face_roi_img_bgr):
|
||||
rgb = cv2.cvtColor(face_roi_img_bgr, cv2.COLOR_BGR2RGB)
|
||||
pil_in = Image.fromarray(rgb)
|
||||
pil_in = pil_in.resize((512, 512), Image.BICUBIC) # pipeline wants 512×512
|
||||
# generate an image that anonymizes faces
|
||||
anon_image = self.pipe(
|
||||
source_image=pil_in,
|
||||
conditioning_image=pil_in,
|
||||
num_inference_steps=200,
|
||||
guidance_scale=4.0,
|
||||
generator=self.generator,
|
||||
anonymization_degree=1.25,
|
||||
width=512,
|
||||
height=512,
|
||||
).images[0]
|
||||
out_rgb = np.array(anon_image)
|
||||
out_bgr = cv2.cvtColor(out_rgb, cv2.COLOR_RGB2BGR)
|
||||
out_bgr = cv2.resize(out_bgr,(face_roi_img_bgr.shape[1], face_roi_img_bgr.shape[0]),
|
||||
interpolation=cv2.INTER_LINEAR)
|
||||
return out_bgr
|
||||
|
||||
def name(self):
|
||||
return "FAMS"
|
||||
Reference in New Issue
Block a user