gulabpatel commited on
Commit
ce88d2c
1 Parent(s): 0ac3348

Initial Space commit

Browse files
Files changed (15) hide show
  1. Dockerfile +14 -0
  2. LICENSE.md +185 -0
  3. README.md +166 -28
  4. animate.py +101 -0
  5. augmentation.py +345 -0
  6. crop-video.py +158 -0
  7. demo.ipynb +522 -0
  8. demo.py +157 -0
  9. frames_dataset.py +197 -0
  10. logger.py +208 -0
  11. old_demo.ipynb +0 -0
  12. reconstruction.py +67 -0
  13. requirements.txt +13 -0
  14. run.py +87 -0
  15. train.py +87 -0
Dockerfile ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM nvcr.io/nvidia/cuda:10.0-cudnn7-runtime-ubuntu18.04
2
+
3
+ RUN DEBIAN_FRONTEND=noninteractive apt-get -qq update \
4
+ && DEBIAN_FRONTEND=noninteractive apt-get -qqy install python3-pip ffmpeg git less nano libsm6 libxext6 libxrender-dev \
5
+ && rm -rf /var/lib/apt/lists/*
6
+
7
+ COPY . /app/
8
+ WORKDIR /app
9
+
10
+ RUN pip3 install --upgrade pip
11
+ RUN pip3 install \
12
+ https://download.pytorch.org/whl/cu100/torch-1.0.0-cp36-cp36m-linux_x86_64.whl \
13
+ git+https://github.com/1adrianb/face-alignment \
14
+ -r requirements.txt
LICENSE.md ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## creative commons
2
+
3
+ # Attribution-NonCommercial 4.0 International
4
+
5
+ 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.
6
+
7
+ ### Using Creative Commons Public Licenses
8
+
9
+ 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.
10
+
11
+ * __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).
12
+
13
+ * __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).
14
+
15
+ ## Creative Commons Attribution-NonCommercial 4.0 International Public License
16
+
17
+ 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.
18
+
19
+ ### Section 1 – Definitions.
20
+
21
+ 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.
22
+
23
+ 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.
24
+
25
+ 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.
26
+
27
+ 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.
28
+
29
+ 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.
30
+
31
+ f. __Licensed Material__ means the artistic or literary work, database, or other material to which the Licensor applied this Public License.
32
+
33
+ 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.
34
+
35
+ h. __Licensor__ means the individual(s) or entity(ies) granting rights under this Public License.
36
+
37
+ 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.
38
+
39
+ 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.
40
+
41
+ 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.
42
+
43
+ l. __You__ means the individual or entity exercising the Licensed Rights under this Public License. Your has a corresponding meaning.
44
+
45
+ ### Section 2 – Scope.
46
+
47
+ a. ___License grant.___
48
+
49
+ 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:
50
+
51
+ A. reproduce and Share the Licensed Material, in whole or in part, for NonCommercial purposes only; and
52
+
53
+ B. produce, reproduce, and Share Adapted Material for NonCommercial purposes only.
54
+
55
+ 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.
56
+
57
+ 3. __Term.__ The term of this Public License is specified in Section 6(a).
58
+
59
+ 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.
60
+
61
+ 5. __Downstream recipients.__
62
+
63
+ 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.
64
+
65
+ 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.
66
+
67
+ 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).
68
+
69
+ b. ___Other rights.___
70
+
71
+ 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.
72
+
73
+ 2. Patent and trademark rights are not licensed under this Public License.
74
+
75
+ 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.
76
+
77
+ ### Section 3 – License Conditions.
78
+
79
+ Your exercise of the Licensed Rights is expressly made subject to the following conditions.
80
+
81
+ a. ___Attribution.___
82
+
83
+ 1. If You Share the Licensed Material (including in modified form), You must:
84
+
85
+ A. retain the following if it is supplied by the Licensor with the Licensed Material:
86
+
87
+ 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);
88
+
89
+ ii. a copyright notice;
90
+
91
+ iii. a notice that refers to this Public License;
92
+
93
+ iv. a notice that refers to the disclaimer of warranties;
94
+
95
+ v. a URI or hyperlink to the Licensed Material to the extent reasonably practicable;
96
+
97
+ B. indicate if You modified the Licensed Material and retain an indication of any previous modifications; and
98
+
99
+ 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.
100
+
101
+ 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.
102
+
103
+ 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.
104
+
105
+ 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.
106
+
107
+ ### Section 4 – Sui Generis Database Rights.
108
+
109
+ Where the Licensed Rights include Sui Generis Database Rights that apply to Your use of the Licensed Material:
110
+
111
+ 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;
112
+
113
+ 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
114
+
115
+ 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.
116
+
117
+ 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.
118
+
119
+ ### Section 5 – Disclaimer of Warranties and Limitation of Liability.
120
+
121
+ 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.__
122
+
123
+ 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.__
124
+
125
+ 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.
126
+
127
+ ### Section 6 – Term and Termination.
128
+
129
+ 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.
130
+
131
+ b. Where Your right to use the Licensed Material has terminated under Section 6(a), it reinstates:
132
+
133
+ 1. automatically as of the date the violation is cured, provided it is cured within 30 days of Your discovery of the violation; or
134
+
135
+ 2. upon express reinstatement by the Licensor.
136
+
137
+ 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.
138
+
139
+ 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.
140
+
141
+ d. Sections 1, 5, 6, 7, and 8 survive termination of this Public License.
142
+
143
+ ### Section 7 – Other Terms and Conditions.
144
+
145
+ a. The Licensor shall not be bound by any additional or different terms or conditions communicated by You unless expressly agreed.
146
+
147
+ 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.
148
+
149
+ ### Section 8 – Interpretation.
150
+
151
+ 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.
152
+
153
+ 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.
154
+
155
+ 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.
156
+
157
+ 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.
158
+
159
+ > 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.
160
+ >
161
+ > Creative Commons may be contacted at creativecommons.org
162
+
163
+ --------------------------- LICENSE FOR Synchronized-BatchNorm-PyTorch --------------------------------
164
+
165
+ MIT License
166
+
167
+ Copyright (c) 2018 Jiayuan MAO
168
+
169
+ Permission is hereby granted, free of charge, to any person obtaining a copy
170
+ of this software and associated documentation files (the "Software"), to deal
171
+ in the Software without restriction, including without limitation the rights
172
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
173
+ copies of the Software, and to permit persons to whom the Software is
174
+ furnished to do so, subject to the following conditions:
175
+
176
+ The above copyright notice and this permission notice shall be included in all
177
+ copies or substantial portions of the Software.
178
+
179
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
180
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
181
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
182
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
183
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
184
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
185
+ SOFTWARE.
README.md CHANGED
@@ -1,37 +1,175 @@
1
- ---
2
- title: First Order Motion
3
- emoji: 📉
4
- colorFrom: pink
5
- colorTo: red
6
- sdk: gradio
7
- app_file: app.py
8
- pinned: false
9
- ---
10
 
11
- # Configuration
12
 
13
- `title`: _string_
14
- Display title for the Space
15
 
16
- `emoji`: _string_
17
- Space emoji (emoji-only character allowed)
18
 
19
- `colorFrom`: _string_
20
- Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
21
 
22
- `colorTo`: _string_
23
- Color for Thumbnail gradient (red, yellow, green, blue, indigo, purple, pink, gray)
 
 
 
 
24
 
25
- `sdk`: _string_
26
- Can be either `gradio` or `streamlit`
27
 
28
- `sdk_version` : _string_
29
- Only applicable for `streamlit` SDK.
30
- See [doc](https://hf.co/docs/hub/spaces) for more info on supported versions.
31
 
32
- `app_file`: _string_
33
- Path to your main application file (which contains either `gradio` or `streamlit` Python code).
34
- Path is relative to the root of the repository.
 
35
 
36
- `pinned`: _boolean_
37
- Whether the Space stays on top of your list.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <b>!!! Check out our new [paper](https://arxiv.org/pdf/2104.11280.pdf) and [framework](https://github.com/snap-research/articulated-animation) improved for articulated objects</b>
 
 
 
 
 
 
 
 
2
 
3
+ # First Order Motion Model for Image Animation
4
 
5
+ This repository contains the source code for the paper [First Order Motion Model for Image Animation](https://papers.nips.cc/paper/8935-first-order-motion-model-for-image-animation) by Aliaksandr Siarohin, [Stéphane Lathuilière](http://stelat.eu), [Sergey Tulyakov](http://stulyakov.com), [Elisa Ricci](http://elisaricci.eu/) and [Nicu Sebe](http://disi.unitn.it/~sebe/).
 
6
 
7
+ ## Example animations
 
8
 
9
+ The videos on the left show the driving videos. The first row on the right for each dataset shows the source videos. The bottom row contains the animated sequences with motion transferred from the driving video and object taken from the source image. We trained a separate network for each task.
 
10
 
11
+ ### VoxCeleb Dataset
12
+ ![Screenshot](sup-mat/vox-teaser.gif)
13
+ ### Fashion Dataset
14
+ ![Screenshot](sup-mat/fashion-teaser.gif)
15
+ ### MGIF Dataset
16
+ ![Screenshot](sup-mat/mgif-teaser.gif)
17
 
 
 
18
 
19
+ ### Installation
 
 
20
 
21
+ We support ```python3```. To install the dependencies run:
22
+ ```
23
+ pip install -r requirements.txt
24
+ ```
25
 
26
+ ### YAML configs
27
+
28
+ There are several configuration (```config/dataset_name.yaml```) files one for each `dataset`. See ```config/taichi-256.yaml``` to get description of each parameter.
29
+
30
+
31
+ ### Pre-trained checkpoint
32
+ Checkpoints can be found under following link: [google-drive](https://drive.google.com/open?id=1PyQJmkdCsAkOYwUyaj_l-l0as-iLDgeH) or [yandex-disk](https://yadi.sk/d/lEw8uRm140L_eQ).
33
+
34
+ ### Animation Demo
35
+ To run a demo, download checkpoint and run the following command:
36
+ ```
37
+ python demo.py --config config/dataset_name.yaml --driving_video path/to/driving --source_image path/to/source --checkpoint path/to/checkpoint --relative --adapt_scale
38
+ ```
39
+ The result will be stored in ```result.mp4```.
40
+
41
+ The driving videos and source images should be cropped before it can be used in our method. To obtain some semi-automatic crop suggestions you can use ```python crop-video.py --inp some_youtube_video.mp4```. It will generate commands for crops using ffmpeg. In order to use the script, face-alligment library is needed:
42
+ ```
43
+ git clone https://github.com/1adrianb/face-alignment
44
+ cd face-alignment
45
+ pip install -r requirements.txt
46
+ python setup.py install
47
+ ```
48
+
49
+ ### Animation demo with Docker
50
+
51
+ If you are having trouble getting the demo to work because of library compatibility issues,
52
+ and you're running Linux, you might try running it inside a Docker container, which would
53
+ give you better control over the execution environment.
54
+
55
+ Requirements: Docker 19.03+ and [nvidia-docker](https://github.com/NVIDIA/nvidia-docker)
56
+ installed and able to successfully run the `nvidia-docker` usage tests.
57
+
58
+ We'll first build the container.
59
+
60
+ ```
61
+ docker build -t first-order-model .
62
+ ```
63
+
64
+ And now that we have the container available locally, we can use it to run the demo.
65
+
66
+ ```
67
+ docker run -it --rm --gpus all \
68
+ -v $HOME/first-order-model:/app first-order-model \
69
+ python3 demo.py --config config/vox-256.yaml \
70
+ --driving_video driving.mp4 \
71
+ --source_image source.png \
72
+ --checkpoint vox-cpk.pth.tar \
73
+ --result_video result.mp4 \
74
+ --relative --adapt_scale
75
+ ```
76
+
77
+ ### Colab Demo
78
+ @graphemecluster prepared a gui-demo for the google-colab see: ```demo.ipynb```. To run press ```Open In Colab``` button.
79
+
80
+ For old demo, see ```old-demo.ipynb```.
81
+
82
+ ### Face-swap
83
+ It is possible to modify the method to perform face-swap using supervised segmentation masks.
84
+ ![Screenshot](sup-mat/face-swap.gif)
85
+ For both unsupervised and supervised video editing, such as face-swap, please refer to [Motion Co-Segmentation](https://github.com/AliaksandrSiarohin/motion-cosegmentation).
86
+
87
+
88
+ ### Training
89
+
90
+ To train a model on specific dataset run:
91
+ ```
92
+ CUDA_VISIBLE_DEVICES=0,1,2,3 python run.py --config config/dataset_name.yaml --device_ids 0,1,2,3
93
+ ```
94
+ The code will create a folder in the log directory (each run will create a time-stamped new directory).
95
+ Checkpoints will be saved to this folder.
96
+ To check the loss values during training see ```log.txt```.
97
+ You can also check training data reconstructions in the ```train-vis``` subfolder.
98
+ By default the batch size is tunned to run on 2 or 4 Titan-X gpu (appart from speed it does not make much difference). You can change the batch size in the train_params in corresponding ```.yaml``` file.
99
+
100
+ ### Evaluation on video reconstruction
101
+
102
+ To evaluate the reconstruction performance run:
103
+ ```
104
+ CUDA_VISIBLE_DEVICES=0 python run.py --config config/dataset_name.yaml --mode reconstruction --checkpoint path/to/checkpoint
105
+ ```
106
+ You will need to specify the path to the checkpoint,
107
+ the ```reconstruction``` subfolder will be created in the checkpoint folder.
108
+ The generated video will be stored to this folder, also generated videos will be stored in ```png``` subfolder in loss-less '.png' format for evaluation.
109
+ Instructions for computing metrics from the paper can be found: https://github.com/AliaksandrSiarohin/pose-evaluation.
110
+
111
+ ### Image animation
112
+
113
+ In order to animate videos run:
114
+ ```
115
+ CUDA_VISIBLE_DEVICES=0 python run.py --config config/dataset_name.yaml --mode animate --checkpoint path/to/checkpoint
116
+ ```
117
+ You will need to specify the path to the checkpoint,
118
+ the ```animation``` subfolder will be created in the same folder as the checkpoint.
119
+ You can find the generated video there and its loss-less version in the ```png``` subfolder.
120
+ By default video from test set will be randomly paired, but you can specify the "source,driving" pairs in the corresponding ```.csv``` files. The path to this file should be specified in corresponding ```.yaml``` file in pairs_list setting.
121
+
122
+ There are 2 different ways of performing animation:
123
+ by using **absolute** keypoint locations or by using **relative** keypoint locations.
124
+
125
+ 1) <i>Animation using absolute coordinates:</i> the animation is performed using the absolute postions of the driving video and appearance of the source image.
126
+ In this way there are no specific requirements for the driving video and source appearance that is used.
127
+ However this usually leads to poor performance since unrelevant details such as shape is transfered.
128
+ Check animate parameters in ```taichi-256.yaml``` to enable this mode.
129
+
130
+ <img src="sup-mat/absolute-demo.gif" width="512">
131
+
132
+ 2) <i>Animation using relative coordinates:</i> from the driving video we first estimate the relative movement of each keypoint,
133
+ then we add this movement to the absolute position of keypoints in the source image.
134
+ This keypoint along with source image is used for animation. This usually leads to better performance, however this requires
135
+ that the object in the first frame of the video and in the source image have the same pose
136
+
137
+ <img src="sup-mat/relative-demo.gif" width="512">
138
+
139
+
140
+ ### Datasets
141
+
142
+ 1) **Bair**. This dataset can be directly [downloaded](https://yadi.sk/d/Rr-fjn-PdmmqeA).
143
+
144
+ 2) **Mgif**. This dataset can be directly [downloaded](https://yadi.sk/d/5VdqLARizmnj3Q).
145
+
146
+ 3) **Fashion**. Follow the instruction on dataset downloading [from](https://vision.cs.ubc.ca/datasets/fashion/).
147
+
148
+ 4) **Taichi**. Follow the instructions in [data/taichi-loading](data/taichi-loading/README.md) or instructions from https://github.com/AliaksandrSiarohin/video-preprocessing.
149
+
150
+ 5) **Nemo**. Please follow the [instructions](https://www.uva-nemo.org/) on how to download the dataset. Then the dataset should be preprocessed using scripts from https://github.com/AliaksandrSiarohin/video-preprocessing.
151
+
152
+ 6) **VoxCeleb**. Please follow the instruction from https://github.com/AliaksandrSiarohin/video-preprocessing.
153
+
154
+
155
+ ### Training on your own dataset
156
+ 1) Resize all the videos to the same size e.g 256x256, the videos can be in '.gif', '.mp4' or folder with images.
157
+ We recommend the later, for each video make a separate folder with all the frames in '.png' format. This format is loss-less, and it has better i/o performance.
158
+
159
+ 2) Create a folder ```data/dataset_name``` with 2 subfolders ```train``` and ```test```, put training videos in the ```train``` and testing in the ```test```.
160
+
161
+ 3) Create a config ```config/dataset_name.yaml```, in dataset_params specify the root dir the ```root_dir: data/dataset_name```. Also adjust the number of epoch in train_params.
162
+
163
+ #### Additional notes
164
+
165
+ Citation:
166
+
167
+ ```
168
+ @InProceedings{Siarohin_2019_NeurIPS,
169
+ author={Siarohin, Aliaksandr and Lathuilière, Stéphane and Tulyakov, Sergey and Ricci, Elisa and Sebe, Nicu},
170
+ title={First Order Motion Model for Image Animation},
171
+ booktitle = {Conference on Neural Information Processing Systems (NeurIPS)},
172
+ month = {December},
173
+ year = {2019}
174
+ }
175
+ ```
animate.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from tqdm import tqdm
3
+
4
+ import torch
5
+ from torch.utils.data import DataLoader
6
+
7
+ from frames_dataset import PairedDataset
8
+ from logger import Logger, Visualizer
9
+ import imageio
10
+ from scipy.spatial import ConvexHull
11
+ import numpy as np
12
+
13
+ from sync_batchnorm import DataParallelWithCallback
14
+
15
+
16
+ def normalize_kp(kp_source, kp_driving, kp_driving_initial, adapt_movement_scale=False,
17
+ use_relative_movement=False, use_relative_jacobian=False):
18
+ if adapt_movement_scale:
19
+ source_area = ConvexHull(kp_source['value'][0].data.cpu().numpy()).volume
20
+ driving_area = ConvexHull(kp_driving_initial['value'][0].data.cpu().numpy()).volume
21
+ adapt_movement_scale = np.sqrt(source_area) / np.sqrt(driving_area)
22
+ else:
23
+ adapt_movement_scale = 1
24
+
25
+ kp_new = {k: v for k, v in kp_driving.items()}
26
+
27
+ if use_relative_movement:
28
+ kp_value_diff = (kp_driving['value'] - kp_driving_initial['value'])
29
+ kp_value_diff *= adapt_movement_scale
30
+ kp_new['value'] = kp_value_diff + kp_source['value']
31
+
32
+ if use_relative_jacobian:
33
+ jacobian_diff = torch.matmul(kp_driving['jacobian'], torch.inverse(kp_driving_initial['jacobian']))
34
+ kp_new['jacobian'] = torch.matmul(jacobian_diff, kp_source['jacobian'])
35
+
36
+ return kp_new
37
+
38
+
39
+ def animate(config, generator, kp_detector, checkpoint, log_dir, dataset):
40
+ log_dir = os.path.join(log_dir, 'animation')
41
+ png_dir = os.path.join(log_dir, 'png')
42
+ animate_params = config['animate_params']
43
+
44
+ dataset = PairedDataset(initial_dataset=dataset, number_of_pairs=animate_params['num_pairs'])
45
+ dataloader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=1)
46
+
47
+ if checkpoint is not None:
48
+ Logger.load_cpk(checkpoint, generator=generator, kp_detector=kp_detector)
49
+ else:
50
+ raise AttributeError("Checkpoint should be specified for mode='animate'.")
51
+
52
+ if not os.path.exists(log_dir):
53
+ os.makedirs(log_dir)
54
+
55
+ if not os.path.exists(png_dir):
56
+ os.makedirs(png_dir)
57
+
58
+ if torch.cuda.is_available():
59
+ generator = DataParallelWithCallback(generator)
60
+ kp_detector = DataParallelWithCallback(kp_detector)
61
+
62
+ generator.eval()
63
+ kp_detector.eval()
64
+
65
+ for it, x in tqdm(enumerate(dataloader)):
66
+ with torch.no_grad():
67
+ predictions = []
68
+ visualizations = []
69
+
70
+ driving_video = x['driving_video']
71
+ source_frame = x['source_video'][:, :, 0, :, :]
72
+
73
+ kp_source = kp_detector(source_frame)
74
+ kp_driving_initial = kp_detector(driving_video[:, :, 0])
75
+
76
+ for frame_idx in range(driving_video.shape[2]):
77
+ driving_frame = driving_video[:, :, frame_idx]
78
+ kp_driving = kp_detector(driving_frame)
79
+ kp_norm = normalize_kp(kp_source=kp_source, kp_driving=kp_driving,
80
+ kp_driving_initial=kp_driving_initial, **animate_params['normalization_params'])
81
+ out = generator(source_frame, kp_source=kp_source, kp_driving=kp_norm)
82
+
83
+ out['kp_driving'] = kp_driving
84
+ out['kp_source'] = kp_source
85
+ out['kp_norm'] = kp_norm
86
+
87
+ del out['sparse_deformed']
88
+
89
+ predictions.append(np.transpose(out['prediction'].data.cpu().numpy(), [0, 2, 3, 1])[0])
90
+
91
+ visualization = Visualizer(**config['visualizer_params']).visualize(source=source_frame,
92
+ driving=driving_frame, out=out)
93
+ visualization = visualization
94
+ visualizations.append(visualization)
95
+
96
+ predictions = np.concatenate(predictions, axis=1)
97
+ result_name = "-".join([x['driving_name'][0], x['source_name'][0]])
98
+ imageio.imsave(os.path.join(png_dir, result_name + '.png'), (255 * predictions).astype(np.uint8))
99
+
100
+ image_name = result_name + animate_params['format']
101
+ imageio.mimsave(os.path.join(log_dir, image_name), visualizations)
augmentation.py ADDED
@@ -0,0 +1,345 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Code from https://github.com/hassony2/torch_videovision
3
+ """
4
+
5
+ import numbers
6
+
7
+ import random
8
+ import numpy as np
9
+ import PIL
10
+
11
+ from skimage.transform import resize, rotate
12
+ from skimage.util import pad
13
+ import torchvision
14
+
15
+ import warnings
16
+
17
+ from skimage import img_as_ubyte, img_as_float
18
+
19
+
20
+ def crop_clip(clip, min_h, min_w, h, w):
21
+ if isinstance(clip[0], np.ndarray):
22
+ cropped = [img[min_h:min_h + h, min_w:min_w + w, :] for img in clip]
23
+
24
+ elif isinstance(clip[0], PIL.Image.Image):
25
+ cropped = [
26
+ img.crop((min_w, min_h, min_w + w, min_h + h)) for img in clip
27
+ ]
28
+ else:
29
+ raise TypeError('Expected numpy.ndarray or PIL.Image' +
30
+ 'but got list of {0}'.format(type(clip[0])))
31
+ return cropped
32
+
33
+
34
+ def pad_clip(clip, h, w):
35
+ im_h, im_w = clip[0].shape[:2]
36
+ pad_h = (0, 0) if h < im_h else ((h - im_h) // 2, (h - im_h + 1) // 2)
37
+ pad_w = (0, 0) if w < im_w else ((w - im_w) // 2, (w - im_w + 1) // 2)
38
+
39
+ return pad(clip, ((0, 0), pad_h, pad_w, (0, 0)), mode='edge')
40
+
41
+
42
+ def resize_clip(clip, size, interpolation='bilinear'):
43
+ if isinstance(clip[0], np.ndarray):
44
+ if isinstance(size, numbers.Number):
45
+ im_h, im_w, im_c = clip[0].shape
46
+ # Min spatial dim already matches minimal size
47
+ if (im_w <= im_h and im_w == size) or (im_h <= im_w
48
+ and im_h == size):
49
+ return clip
50
+ new_h, new_w = get_resize_sizes(im_h, im_w, size)
51
+ size = (new_w, new_h)
52
+ else:
53
+ size = size[1], size[0]
54
+
55
+ scaled = [
56
+ resize(img, size, order=1 if interpolation == 'bilinear' else 0, preserve_range=True,
57
+ mode='constant', anti_aliasing=True) for img in clip
58
+ ]
59
+ elif isinstance(clip[0], PIL.Image.Image):
60
+ if isinstance(size, numbers.Number):
61
+ im_w, im_h = clip[0].size
62
+ # Min spatial dim already matches minimal size
63
+ if (im_w <= im_h and im_w == size) or (im_h <= im_w
64
+ and im_h == size):
65
+ return clip
66
+ new_h, new_w = get_resize_sizes(im_h, im_w, size)
67
+ size = (new_w, new_h)
68
+ else:
69
+ size = size[1], size[0]
70
+ if interpolation == 'bilinear':
71
+ pil_inter = PIL.Image.NEAREST
72
+ else:
73
+ pil_inter = PIL.Image.BILINEAR
74
+ scaled = [img.resize(size, pil_inter) for img in clip]
75
+ else:
76
+ raise TypeError('Expected numpy.ndarray or PIL.Image' +
77
+ 'but got list of {0}'.format(type(clip[0])))
78
+ return scaled
79
+
80
+
81
+ def get_resize_sizes(im_h, im_w, size):
82
+ if im_w < im_h:
83
+ ow = size
84
+ oh = int(size * im_h / im_w)
85
+ else:
86
+ oh = size
87
+ ow = int(size * im_w / im_h)
88
+ return oh, ow
89
+
90
+
91
+ class RandomFlip(object):
92
+ def __init__(self, time_flip=False, horizontal_flip=False):
93
+ self.time_flip = time_flip
94
+ self.horizontal_flip = horizontal_flip
95
+
96
+ def __call__(self, clip):
97
+ if random.random() < 0.5 and self.time_flip:
98
+ return clip[::-1]
99
+ if random.random() < 0.5 and self.horizontal_flip:
100
+ return [np.fliplr(img) for img in clip]
101
+
102
+ return clip
103
+
104
+
105
+ class RandomResize(object):
106
+ """Resizes a list of (H x W x C) numpy.ndarray to the final size
107
+ The larger the original image is, the more times it takes to
108
+ interpolate
109
+ Args:
110
+ interpolation (str): Can be one of 'nearest', 'bilinear'
111
+ defaults to nearest
112
+ size (tuple): (widht, height)
113
+ """
114
+
115
+ def __init__(self, ratio=(3. / 4., 4. / 3.), interpolation='nearest'):
116
+ self.ratio = ratio
117
+ self.interpolation = interpolation
118
+
119
+ def __call__(self, clip):
120
+ scaling_factor = random.uniform(self.ratio[0], self.ratio[1])
121
+
122
+ if isinstance(clip[0], np.ndarray):
123
+ im_h, im_w, im_c = clip[0].shape
124
+ elif isinstance(clip[0], PIL.Image.Image):
125
+ im_w, im_h = clip[0].size
126
+
127
+ new_w = int(im_w * scaling_factor)
128
+ new_h = int(im_h * scaling_factor)
129
+ new_size = (new_w, new_h)
130
+ resized = resize_clip(
131
+ clip, new_size, interpolation=self.interpolation)
132
+
133
+ return resized
134
+
135
+
136
+ class RandomCrop(object):
137
+ """Extract random crop at the same location for a list of videos
138
+ Args:
139
+ size (sequence or int): Desired output size for the
140
+ crop in format (h, w)
141
+ """
142
+
143
+ def __init__(self, size):
144
+ if isinstance(size, numbers.Number):
145
+ size = (size, size)
146
+
147
+ self.size = size
148
+
149
+ def __call__(self, clip):
150
+ """
151
+ Args:
152
+ img (PIL.Image or numpy.ndarray): List of videos to be cropped
153
+ in format (h, w, c) in numpy.ndarray
154
+ Returns:
155
+ PIL.Image or numpy.ndarray: Cropped list of videos
156
+ """
157
+ h, w = self.size
158
+ if isinstance(clip[0], np.ndarray):
159
+ im_h, im_w, im_c = clip[0].shape
160
+ elif isinstance(clip[0], PIL.Image.Image):
161
+ im_w, im_h = clip[0].size
162
+ else:
163
+ raise TypeError('Expected numpy.ndarray or PIL.Image' +
164
+ 'but got list of {0}'.format(type(clip[0])))
165
+
166
+ clip = pad_clip(clip, h, w)
167
+ im_h, im_w = clip.shape[1:3]
168
+ x1 = 0 if h == im_h else random.randint(0, im_w - w)
169
+ y1 = 0 if w == im_w else random.randint(0, im_h - h)
170
+ cropped = crop_clip(clip, y1, x1, h, w)
171
+
172
+ return cropped
173
+
174
+
175
+ class RandomRotation(object):
176
+ """Rotate entire clip randomly by a random angle within
177
+ given bounds
178
+ Args:
179
+ degrees (sequence or int): Range of degrees to select from
180
+ If degrees is a number instead of sequence like (min, max),
181
+ the range of degrees, will be (-degrees, +degrees).
182
+ """
183
+
184
+ def __init__(self, degrees):
185
+ if isinstance(degrees, numbers.Number):
186
+ if degrees < 0:
187
+ raise ValueError('If degrees is a single number,'
188
+ 'must be positive')
189
+ degrees = (-degrees, degrees)
190
+ else:
191
+ if len(degrees) != 2:
192
+ raise ValueError('If degrees is a sequence,'
193
+ 'it must be of len 2.')
194
+
195
+ self.degrees = degrees
196
+
197
+ def __call__(self, clip):
198
+ """
199
+ Args:
200
+ img (PIL.Image or numpy.ndarray): List of videos to be cropped
201
+ in format (h, w, c) in numpy.ndarray
202
+ Returns:
203
+ PIL.Image or numpy.ndarray: Cropped list of videos
204
+ """
205
+ angle = random.uniform(self.degrees[0], self.degrees[1])
206
+ if isinstance(clip[0], np.ndarray):
207
+ rotated = [rotate(image=img, angle=angle, preserve_range=True) for img in clip]
208
+ elif isinstance(clip[0], PIL.Image.Image):
209
+ rotated = [img.rotate(angle) for img in clip]
210
+ else:
211
+ raise TypeError('Expected numpy.ndarray or PIL.Image' +
212
+ 'but got list of {0}'.format(type(clip[0])))
213
+
214
+ return rotated
215
+
216
+
217
+ class ColorJitter(object):
218
+ """Randomly change the brightness, contrast and saturation and hue of the clip
219
+ Args:
220
+ brightness (float): How much to jitter brightness. brightness_factor
221
+ is chosen uniformly from [max(0, 1 - brightness), 1 + brightness].
222
+ contrast (float): How much to jitter contrast. contrast_factor
223
+ is chosen uniformly from [max(0, 1 - contrast), 1 + contrast].
224
+ saturation (float): How much to jitter saturation. saturation_factor
225
+ is chosen uniformly from [max(0, 1 - saturation), 1 + saturation].
226
+ hue(float): How much to jitter hue. hue_factor is chosen uniformly from
227
+ [-hue, hue]. Should be >=0 and <= 0.5.
228
+ """
229
+
230
+ def __init__(self, brightness=0, contrast=0, saturation=0, hue=0):
231
+ self.brightness = brightness
232
+ self.contrast = contrast
233
+ self.saturation = saturation
234
+ self.hue = hue
235
+
236
+ def get_params(self, brightness, contrast, saturation, hue):
237
+ if brightness > 0:
238
+ brightness_factor = random.uniform(
239
+ max(0, 1 - brightness), 1 + brightness)
240
+ else:
241
+ brightness_factor = None
242
+
243
+ if contrast > 0:
244
+ contrast_factor = random.uniform(
245
+ max(0, 1 - contrast), 1 + contrast)
246
+ else:
247
+ contrast_factor = None
248
+
249
+ if saturation > 0:
250
+ saturation_factor = random.uniform(
251
+ max(0, 1 - saturation), 1 + saturation)
252
+ else:
253
+ saturation_factor = None
254
+
255
+ if hue > 0:
256
+ hue_factor = random.uniform(-hue, hue)
257
+ else:
258
+ hue_factor = None
259
+ return brightness_factor, contrast_factor, saturation_factor, hue_factor
260
+
261
+ def __call__(self, clip):
262
+ """
263
+ Args:
264
+ clip (list): list of PIL.Image
265
+ Returns:
266
+ list PIL.Image : list of transformed PIL.Image
267
+ """
268
+ if isinstance(clip[0], np.ndarray):
269
+ brightness, contrast, saturation, hue = self.get_params(
270
+ self.brightness, self.contrast, self.saturation, self.hue)
271
+
272
+ # Create img transform function sequence
273
+ img_transforms = []
274
+ if brightness is not None:
275
+ img_transforms.append(lambda img: torchvision.transforms.functional.adjust_brightness(img, brightness))
276
+ if saturation is not None:
277
+ img_transforms.append(lambda img: torchvision.transforms.functional.adjust_saturation(img, saturation))
278
+ if hue is not None:
279
+ img_transforms.append(lambda img: torchvision.transforms.functional.adjust_hue(img, hue))
280
+ if contrast is not None:
281
+ img_transforms.append(lambda img: torchvision.transforms.functional.adjust_contrast(img, contrast))
282
+ random.shuffle(img_transforms)
283
+ img_transforms = [img_as_ubyte, torchvision.transforms.ToPILImage()] + img_transforms + [np.array,
284
+ img_as_float]
285
+
286
+ with warnings.catch_warnings():
287
+ warnings.simplefilter("ignore")
288
+ jittered_clip = []
289
+ for img in clip:
290
+ jittered_img = img
291
+ for func in img_transforms:
292
+ jittered_img = func(jittered_img)
293
+ jittered_clip.append(jittered_img.astype('float32'))
294
+ elif isinstance(clip[0], PIL.Image.Image):
295
+ brightness, contrast, saturation, hue = self.get_params(
296
+ self.brightness, self.contrast, self.saturation, self.hue)
297
+
298
+ # Create img transform function sequence
299
+ img_transforms = []
300
+ if brightness is not None:
301
+ img_transforms.append(lambda img: torchvision.transforms.functional.adjust_brightness(img, brightness))
302
+ if saturation is not None:
303
+ img_transforms.append(lambda img: torchvision.transforms.functional.adjust_saturation(img, saturation))
304
+ if hue is not None:
305
+ img_transforms.append(lambda img: torchvision.transforms.functional.adjust_hue(img, hue))
306
+ if contrast is not None:
307
+ img_transforms.append(lambda img: torchvision.transforms.functional.adjust_contrast(img, contrast))
308
+ random.shuffle(img_transforms)
309
+
310
+ # Apply to all videos
311
+ jittered_clip = []
312
+ for img in clip:
313
+ for func in img_transforms:
314
+ jittered_img = func(img)
315
+ jittered_clip.append(jittered_img)
316
+
317
+ else:
318
+ raise TypeError('Expected numpy.ndarray or PIL.Image' +
319
+ 'but got list of {0}'.format(type(clip[0])))
320
+ return jittered_clip
321
+
322
+
323
+ class AllAugmentationTransform:
324
+ def __init__(self, resize_param=None, rotation_param=None, flip_param=None, crop_param=None, jitter_param=None):
325
+ self.transforms = []
326
+
327
+ if flip_param is not None:
328
+ self.transforms.append(RandomFlip(**flip_param))
329
+
330
+ if rotation_param is not None:
331
+ self.transforms.append(RandomRotation(**rotation_param))
332
+
333
+ if resize_param is not None:
334
+ self.transforms.append(RandomResize(**resize_param))
335
+
336
+ if crop_param is not None:
337
+ self.transforms.append(RandomCrop(**crop_param))
338
+
339
+ if jitter_param is not None:
340
+ self.transforms.append(ColorJitter(**jitter_param))
341
+
342
+ def __call__(self, clip):
343
+ for t in self.transforms:
344
+ clip = t(clip)
345
+ return clip
crop-video.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import face_alignment
2
+ import skimage.io
3
+ import numpy
4
+ from argparse import ArgumentParser
5
+ from skimage import img_as_ubyte
6
+ from skimage.transform import resize
7
+ from tqdm import tqdm
8
+ import os
9
+ import imageio
10
+ import numpy as np
11
+ import warnings
12
+ warnings.filterwarnings("ignore")
13
+
14
+ def extract_bbox(frame, fa):
15
+ if max(frame.shape[0], frame.shape[1]) > 640:
16
+ scale_factor = max(frame.shape[0], frame.shape[1]) / 640.0
17
+ frame = resize(frame, (int(frame.shape[0] / scale_factor), int(frame.shape[1] / scale_factor)))
18
+ frame = img_as_ubyte(frame)
19
+ else:
20
+ scale_factor = 1
21
+ frame = frame[..., :3]
22
+ bboxes = fa.face_detector.detect_from_image(frame[..., ::-1])
23
+ if len(bboxes) == 0:
24
+ return []
25
+ return np.array(bboxes)[:, :-1] * scale_factor
26
+
27
+
28
+
29
+ def bb_intersection_over_union(boxA, boxB):
30
+ xA = max(boxA[0], boxB[0])
31
+ yA = max(boxA[1], boxB[1])
32
+ xB = min(boxA[2], boxB[2])
33
+ yB = min(boxA[3], boxB[3])
34
+ interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)
35
+ boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)
36
+ boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)
37
+ iou = interArea / float(boxAArea + boxBArea - interArea)
38
+ return iou
39
+
40
+
41
+ def join(tube_bbox, bbox):
42
+ xA = min(tube_bbox[0], bbox[0])
43
+ yA = min(tube_bbox[1], bbox[1])
44
+ xB = max(tube_bbox[2], bbox[2])
45
+ yB = max(tube_bbox[3], bbox[3])
46
+ return (xA, yA, xB, yB)
47
+
48
+
49
+ def compute_bbox(start, end, fps, tube_bbox, frame_shape, inp, image_shape, increase_area=0.1):
50
+ left, top, right, bot = tube_bbox
51
+ width = right - left
52
+ height = bot - top
53
+
54
+ #Computing aspect preserving bbox
55
+ width_increase = max(increase_area, ((1 + 2 * increase_area) * height - width) / (2 * width))
56
+ height_increase = max(increase_area, ((1 + 2 * increase_area) * width - height) / (2 * height))
57
+
58
+ left = int(left - width_increase * width)
59
+ top = int(top - height_increase * height)
60
+ right = int(right + width_increase * width)
61
+ bot = int(bot + height_increase * height)
62
+
63
+ top, bot, left, right = max(0, top), min(bot, frame_shape[0]), max(0, left), min(right, frame_shape[1])
64
+ h, w = bot - top, right - left
65
+
66
+ start = start / fps
67
+ end = end / fps
68
+ time = end - start
69
+
70
+ scale = f'{image_shape[0]}:{image_shape[1]}'
71
+
72
+ return f'ffmpeg -i {inp} -ss {start} -t {time} -filter:v "crop={w}:{h}:{left}:{top}, scale={scale}" crop.mp4'
73
+
74
+
75
+ def compute_bbox_trajectories(trajectories, fps, frame_shape, args):
76
+ commands = []
77
+ for i, (bbox, tube_bbox, start, end) in enumerate(trajectories):
78
+ if (end - start) > args.min_frames:
79
+ command = compute_bbox(start, end, fps, tube_bbox, frame_shape, inp=args.inp, image_shape=args.image_shape, increase_area=args.increase)
80
+ commands.append(command)
81
+ return commands
82
+
83
+
84
+ def process_video(args):
85
+ device = 'cpu' if args.cpu else 'cuda'
86
+ fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, flip_input=False, device=device)
87
+ video = imageio.get_reader(args.inp)
88
+
89
+ trajectories = []
90
+ previous_frame = None
91
+ fps = video.get_meta_data()['fps']
92
+ commands = []
93
+ try:
94
+ for i, frame in tqdm(enumerate(video)):
95
+ frame_shape = frame.shape
96
+ bboxes = extract_bbox(frame, fa)
97
+ ## For each trajectory check the criterion
98
+ not_valid_trajectories = []
99
+ valid_trajectories = []
100
+
101
+ for trajectory in trajectories:
102
+ tube_bbox = trajectory[0]
103
+ intersection = 0
104
+ for bbox in bboxes:
105
+ intersection = max(intersection, bb_intersection_over_union(tube_bbox, bbox))
106
+ if intersection > args.iou_with_initial:
107
+ valid_trajectories.append(trajectory)
108
+ else:
109
+ not_valid_trajectories.append(trajectory)
110
+
111
+ commands += compute_bbox_trajectories(not_valid_trajectories, fps, frame_shape, args)
112
+ trajectories = valid_trajectories
113
+
114
+ ## Assign bbox to trajectories, create new trajectories
115
+ for bbox in bboxes:
116
+ intersection = 0
117
+ current_trajectory = None
118
+ for trajectory in trajectories:
119
+ tube_bbox = trajectory[0]
120
+ current_intersection = bb_intersection_over_union(tube_bbox, bbox)
121
+ if intersection < current_intersection and current_intersection > args.iou_with_initial:
122
+ intersection = bb_intersection_over_union(tube_bbox, bbox)
123
+ current_trajectory = trajectory
124
+
125
+ ## Create new trajectory
126
+ if current_trajectory is None:
127
+ trajectories.append([bbox, bbox, i, i])
128
+ else:
129
+ current_trajectory[3] = i
130
+ current_trajectory[1] = join(current_trajectory[1], bbox)
131
+
132
+
133
+ except IndexError as e:
134
+ raise (e)
135
+
136
+ commands += compute_bbox_trajectories(trajectories, fps, frame_shape, args)
137
+ return commands
138
+
139
+
140
+ if __name__ == "__main__":
141
+ parser = ArgumentParser()
142
+
143
+ parser.add_argument("--image_shape", default=(256, 256), type=lambda x: tuple(map(int, x.split(','))),
144
+ help="Image shape")
145
+ parser.add_argument("--increase", default=0.1, type=float, help='Increase bbox by this amount')
146
+ parser.add_argument("--iou_with_initial", type=float, default=0.25, help="The minimal allowed iou with inital bbox")
147
+ parser.add_argument("--inp", required=True, help='Input image or video')
148
+ parser.add_argument("--min_frames", type=int, default=150, help='Minimum number of frames')
149
+ parser.add_argument("--cpu", dest="cpu", action="store_true", help="cpu mode.")
150
+
151
+
152
+ args = parser.parse_args()
153
+
154
+ commands = process_video(args)
155
+ for command in commands:
156
+ print (command)
157
+
158
+
demo.ipynb ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "nbformat": 4,
3
+ "nbformat_minor": 0,
4
+ "metadata": {
5
+ "colab": {
6
+ "name": "first-order-model-demo",
7
+ "provenance": []
8
+ },
9
+ "kernelspec": {
10
+ "name": "python3",
11
+ "display_name": "Python 3"
12
+ },
13
+ "accelerator": "GPU"
14
+ },
15
+ "cells": [
16
+ {
17
+ "cell_type": "markdown",
18
+ "metadata": {
19
+ "id": "view-in-github",
20
+ "colab_type": "text"
21
+ },
22
+ "source": [
23
+ "<a href=\"https://colab.research.google.com/github/AliaksandrSiarohin/first-order-model/blob/master/demo.ipynb\" target=\"_parent\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"/></a>",
24
+ "<a href=\"https://kaggle.com/kernels/welcome?src=https://github.com/AliaksandrSiarohin/first-order-model/blob/master/demo.ipynb\" target=\"_parent\"><img alt=\"Kaggle\" title=\"Open in Kaggle\" src=\"https://kaggle.com/static/images/open-in-kaggle.svg\"></a>"
25
+ ]
26
+ },
27
+ {
28
+ "cell_type": "markdown",
29
+ "metadata": {
30
+ "id": "cdO_RxQZLahB"
31
+ },
32
+ "source": [
33
+ "# Demo for paper \"First Order Motion Model for Image Animation\"\n",
34
+ "To try the demo, press the 2 play buttons in order and scroll to the bottom. Note that it may take several minutes to load."
35
+ ]
36
+ },
37
+ {
38
+ "cell_type": "code",
39
+ "metadata": {
40
+ "id": "UCMFMJV7K-ag"
41
+ },
42
+ "source": [
43
+ "!pip install ffmpy &> /dev/null\n",
44
+ "!git init -q .\n",
45
+ "!git remote add origin https://github.com/AliaksandrSiarohin/first-order-model\n",
46
+ "!git pull -q origin master\n",
47
+ "!git clone -q https://github.com/graphemecluster/first-order-model-demo demo"
48
+ ],
49
+ "execution_count": null,
50
+ "outputs": []
51
+ },
52
+ {
53
+ "cell_type": "code",
54
+ "metadata": {
55
+ "id": "Oxi6-riLOgnm"
56
+ },
57
+ "source": [
58
+ "import IPython.display\n",
59
+ "import PIL.Image\n",
60
+ "import cv2\n",
61
+ "import imageio\n",
62
+ "import io\n",
63
+ "import ipywidgets\n",
64
+ "import numpy\n",
65
+ "import os.path\n",
66
+ "import requests\n",
67
+ "import skimage.transform\n",
68
+ "import warnings\n",
69
+ "from base64 import b64encode\n",
70
+ "from demo import load_checkpoints, make_animation\n",
71
+ "from ffmpy import FFmpeg\n",
72
+ "from google.colab import files, output\n",
73
+ "from IPython.display import HTML, Javascript\n",
74
+ "from skimage import img_as_ubyte\n",
75
+ "warnings.filterwarnings(\"ignore\")\n",
76
+ "os.makedirs(\"user\", exist_ok=True)\n",
77
+ "\n",
78
+ "display(HTML(\"\"\"\n",
79
+ "<style>\n",
80
+ ".widget-box > * {\n",
81
+ "\tflex-shrink: 0;\n",
82
+ "}\n",
83
+ ".widget-tab {\n",
84
+ "\tmin-width: 0;\n",
85
+ "\tflex: 1 1 auto;\n",
86
+ "}\n",
87
+ ".widget-tab .p-TabBar-tabLabel {\n",
88
+ "\tfont-size: 15px;\n",
89
+ "}\n",
90
+ ".widget-upload {\n",
91
+ "\tbackground-color: tan;\n",
92
+ "}\n",
93
+ ".widget-button {\n",
94
+ "\tfont-size: 18px;\n",
95
+ "\twidth: 160px;\n",
96
+ "\theight: 34px;\n",
97
+ "\tline-height: 34px;\n",
98
+ "}\n",
99
+ ".widget-dropdown {\n",
100
+ "\twidth: 250px;\n",
101
+ "}\n",
102
+ ".widget-checkbox {\n",
103
+ " width: 650px;\n",
104
+ "}\n",
105
+ ".widget-checkbox + .widget-checkbox {\n",
106
+ " margin-top: -6px;\n",
107
+ "}\n",
108
+ ".input-widget .output_html {\n",
109
+ "\ttext-align: center;\n",
110
+ "\twidth: 266px;\n",
111
+ "\theight: 266px;\n",
112
+ "\tline-height: 266px;\n",
113
+ "\tcolor: lightgray;\n",
114
+ "\tfont-size: 72px;\n",
115
+ "}\n",
116
+ "div.stream {\n",
117
+ "\tdisplay: none;\n",
118
+ "}\n",
119
+ ".title {\n",
120
+ "\tfont-size: 20px;\n",
121
+ "\tfont-weight: bold;\n",
122
+ "\tmargin: 12px 0 6px 0;\n",
123
+ "}\n",
124
+ ".warning {\n",
125
+ "\tdisplay: none;\n",
126
+ "\tcolor: red;\n",
127
+ "\tmargin-left: 10px;\n",
128
+ "}\n",
129
+ ".warn {\n",
130
+ "\tdisplay: initial;\n",
131
+ "}\n",
132
+ ".resource {\n",
133
+ "\tcursor: pointer;\n",
134
+ "\tborder: 1px solid gray;\n",
135
+ "\tmargin: 5px;\n",
136
+ "\twidth: 160px;\n",
137
+ "\theight: 160px;\n",
138
+ "\tmin-width: 160px;\n",
139
+ "\tmin-height: 160px;\n",
140
+ "\tmax-width: 160px;\n",
141
+ "\tmax-height: 160px;\n",
142
+ "\t-webkit-box-sizing: initial;\n",
143
+ "\tbox-sizing: initial;\n",
144
+ "}\n",
145
+ ".resource:hover {\n",
146
+ "\tborder: 6px solid crimson;\n",
147
+ "\tmargin: 0;\n",
148
+ "}\n",
149
+ ".selected {\n",
150
+ "\tborder: 6px solid seagreen;\n",
151
+ "\tmargin: 0;\n",
152
+ "}\n",
153
+ ".input-widget {\n",
154
+ "\twidth: 266px;\n",
155
+ "\theight: 266px;\n",
156
+ "\tborder: 1px solid gray;\n",
157
+ "}\n",
158
+ ".input-button {\n",
159
+ "\twidth: 268px;\n",
160
+ "\tfont-size: 15px;\n",
161
+ "\tmargin: 2px 0 0;\n",
162
+ "}\n",
163
+ ".output-widget {\n",
164
+ "\twidth: 256px;\n",
165
+ "\theight: 256px;\n",
166
+ "\tborder: 1px solid gray;\n",
167
+ "}\n",
168
+ ".output-button {\n",
169
+ "\twidth: 258px;\n",
170
+ "\tfont-size: 15px;\n",
171
+ "\tmargin: 2px 0 0;\n",
172
+ "}\n",
173
+ ".uploaded {\n",
174
+ "\twidth: 256px;\n",
175
+ "\theight: 256px;\n",
176
+ "\tborder: 6px solid seagreen;\n",
177
+ "\tmargin: 0;\n",
178
+ "}\n",
179
+ ".label-or {\n",
180
+ "\talign-self: center;\n",
181
+ "\tfont-size: 20px;\n",
182
+ "\tmargin: 16px;\n",
183
+ "}\n",
184
+ ".loading {\n",
185
+ "\talign-items: center;\n",
186
+ "\twidth: fit-content;\n",
187
+ "}\n",
188
+ ".loader {\n",
189
+ "\tmargin: 32px 0 16px 0;\n",
190
+ "\twidth: 48px;\n",
191
+ "\theight: 48px;\n",
192
+ "\tmin-width: 48px;\n",
193
+ "\tmin-height: 48px;\n",
194
+ "\tmax-width: 48px;\n",
195
+ "\tmax-height: 48px;\n",
196
+ "\tborder: 4px solid whitesmoke;\n",
197
+ "\tborder-top-color: gray;\n",
198
+ "\tborder-radius: 50%;\n",
199
+ "\tanimation: spin 1.8s linear infinite;\n",
200
+ "}\n",
201
+ ".loading-label {\n",
202
+ "\tcolor: gray;\n",
203
+ "}\n",
204
+ ".comparison-widget {\n",
205
+ "\twidth: 256px;\n",
206
+ "\theight: 256px;\n",
207
+ "\tborder: 1px solid gray;\n",
208
+ "\tmargin-left: 2px;\n",
209
+ "}\n",
210
+ ".comparison-label {\n",
211
+ "\tcolor: gray;\n",
212
+ "\tfont-size: 14px;\n",
213
+ "\ttext-align: center;\n",
214
+ "\tposition: relative;\n",
215
+ "\tbottom: 3px;\n",
216
+ "}\n",
217
+ "@keyframes spin {\n",
218
+ "\tfrom { transform: rotate(0deg); }\n",
219
+ "\tto { transform: rotate(360deg); }\n",
220
+ "}\n",
221
+ "</style>\n",
222
+ "\"\"\"))\n",
223
+ "\n",
224
+ "def thumbnail(file):\n",
225
+ "\treturn imageio.get_reader(file, mode='I', format='FFMPEG').get_next_data()\n",
226
+ "\n",
227
+ "def create_image(i, j):\n",
228
+ "\timage_widget = ipywidgets.Image(\n",
229
+ "\t\tvalue=open('demo/images/%d%d.png' % (i, j), 'rb').read(),\n",
230
+ "\t\tformat='png'\n",
231
+ "\t)\n",
232
+ "\timage_widget.add_class('resource')\n",
233
+ "\timage_widget.add_class('resource-image')\n",
234
+ "\timage_widget.add_class('resource-image%d%d' % (i, j))\n",
235
+ "\treturn image_widget\n",
236
+ "\n",
237
+ "def create_video(i):\n",
238
+ "\tvideo_widget = ipywidgets.Image(\n",
239
+ "\t\tvalue=cv2.imencode('.png', cv2.cvtColor(thumbnail('demo/videos/%d.mp4' % i), cv2.COLOR_RGB2BGR))[1].tostring(),\n",
240
+ "\t\tformat='png'\n",
241
+ "\t)\n",
242
+ "\tvideo_widget.add_class('resource')\n",
243
+ "\tvideo_widget.add_class('resource-video')\n",
244
+ "\tvideo_widget.add_class('resource-video%d' % i)\n",
245
+ "\treturn video_widget\n",
246
+ "\n",
247
+ "def create_title(title):\n",
248
+ "\ttitle_widget = ipywidgets.Label(title)\n",
249
+ "\ttitle_widget.add_class('title')\n",
250
+ "\treturn title_widget\n",
251
+ "\n",
252
+ "def download_output(button):\n",
253
+ "\tcomplete.layout.display = 'none'\n",
254
+ "\tloading.layout.display = ''\n",
255
+ "\tfiles.download('output.mp4')\n",
256
+ "\tloading.layout.display = 'none'\n",
257
+ "\tcomplete.layout.display = ''\n",
258
+ "\n",
259
+ "def convert_output(button):\n",
260
+ "\tcomplete.layout.display = 'none'\n",
261
+ "\tloading.layout.display = ''\n",
262
+ "\tFFmpeg(inputs={'output.mp4': None}, outputs={'scaled.mp4': '-vf \"scale=1080x1080:flags=lanczos,pad=1920:1080:420:0\" -y'}).run()\n",
263
+ "\tfiles.download('scaled.mp4')\n",
264
+ "\tloading.layout.display = 'none'\n",
265
+ "\tcomplete.layout.display = ''\n",
266
+ "\n",
267
+ "def back_to_main(button):\n",
268
+ "\tcomplete.layout.display = 'none'\n",
269
+ "\tmain.layout.display = ''\n",
270
+ "\n",
271
+ "label_or = ipywidgets.Label('or')\n",
272
+ "label_or.add_class('label-or')\n",
273
+ "\n",
274
+ "image_titles = ['Peoples', 'Cartoons', 'Dolls', 'Game of Thrones', 'Statues']\n",
275
+ "image_lengths = [8, 4, 8, 9, 4]\n",
276
+ "\n",
277
+ "image_tab = ipywidgets.Tab()\n",
278
+ "image_tab.children = [ipywidgets.HBox([create_image(i, j) for j in range(length)]) for i, length in enumerate(image_lengths)]\n",
279
+ "for i, title in enumerate(image_titles):\n",
280
+ "\timage_tab.set_title(i, title)\n",
281
+ "\n",
282
+ "input_image_widget = ipywidgets.Output()\n",
283
+ "input_image_widget.add_class('input-widget')\n",
284
+ "upload_input_image_button = ipywidgets.FileUpload(accept='image/*', button_style='primary')\n",
285
+ "upload_input_image_button.add_class('input-button')\n",
286
+ "image_part = ipywidgets.HBox([\n",
287
+ "\tipywidgets.VBox([input_image_widget, upload_input_image_button]),\n",
288
+ "\tlabel_or,\n",
289
+ "\timage_tab\n",
290
+ "])\n",
291
+ "\n",
292
+ "video_tab = ipywidgets.Tab()\n",
293
+ "video_tab.children = [ipywidgets.HBox([create_video(i) for i in range(5)])]\n",
294
+ "video_tab.set_title(0, 'All Videos')\n",
295
+ "\n",
296
+ "input_video_widget = ipywidgets.Output()\n",
297
+ "input_video_widget.add_class('input-widget')\n",
298
+ "upload_input_video_button = ipywidgets.FileUpload(accept='video/*', button_style='primary')\n",
299
+ "upload_input_video_button.add_class('input-button')\n",
300
+ "video_part = ipywidgets.HBox([\n",
301
+ "\tipywidgets.VBox([input_video_widget, upload_input_video_button]),\n",
302
+ "\tlabel_or,\n",
303
+ "\tvideo_tab\n",
304
+ "])\n",
305
+ "\n",
306
+ "model = ipywidgets.Dropdown(\n",
307
+ "\tdescription=\"Model:\",\n",
308
+ "\toptions=[\n",
309
+ "\t\t'vox',\n",
310
+ "\t\t'vox-adv',\n",
311
+ "\t\t'taichi',\n",
312
+ "\t\t'taichi-adv',\n",
313
+ "\t\t'nemo',\n",
314
+ "\t\t'mgif',\n",
315
+ "\t\t'fashion',\n",
316
+ "\t\t'bair'\n",
317
+ "\t]\n",
318
+ ")\n",
319
+ "warning = ipywidgets.HTML('<b>Warning:</b> Upload your own images and videos (see README)')\n",
320
+ "warning.add_class('warning')\n",
321
+ "model_part = ipywidgets.HBox([model, warning])\n",
322
+ "\n",
323
+ "relative = ipywidgets.Checkbox(description=\"Relative keypoint displacement (Inherit object proporions from the video)\", value=True)\n",
324
+ "adapt_movement_scale = ipywidgets.Checkbox(description=\"Adapt movement scale (Don’t touch unless you know want you are doing)\", value=True)\n",
325
+ "generate_button = ipywidgets.Button(description=\"Generate\", button_style='primary')\n",
326
+ "main = ipywidgets.VBox([\n",
327
+ "\tcreate_title('Choose Image'),\n",
328
+ "\timage_part,\n",
329
+ "\tcreate_title('Choose Video'),\n",
330
+ "\tvideo_part,\n",
331
+ "\tcreate_title('Settings'),\n",
332
+ "\tmodel_part,\n",
333
+ "\trelative,\n",
334
+ "\tadapt_movement_scale,\n",
335
+ "\tgenerate_button\n",
336
+ "])\n",
337
+ "\n",
338
+ "loader = ipywidgets.Label()\n",
339
+ "loader.add_class(\"loader\")\n",
340
+ "loading_label = ipywidgets.Label(\"This may take several minutes to process…\")\n",
341
+ "loading_label.add_class(\"loading-label\")\n",
342
+ "loading = ipywidgets.VBox([loader, loading_label])\n",
343
+ "loading.add_class('loading')\n",
344
+ "\n",
345
+ "output_widget = ipywidgets.Output()\n",
346
+ "output_widget.add_class('output-widget')\n",
347
+ "download = ipywidgets.Button(description='Download', button_style='primary')\n",
348
+ "download.add_class('output-button')\n",
349
+ "download.on_click(download_output)\n",
350
+ "convert = ipywidgets.Button(description='Convert to 1920×1080', button_style='primary')\n",
351
+ "convert.add_class('output-button')\n",
352
+ "convert.on_click(convert_output)\n",
353
+ "back = ipywidgets.Button(description='Back', button_style='primary')\n",
354
+ "back.add_class('output-button')\n",
355
+ "back.on_click(back_to_main)\n",
356
+ "\n",
357
+ "comparison_widget = ipywidgets.Output()\n",
358
+ "comparison_widget.add_class('comparison-widget')\n",
359
+ "comparison_label = ipywidgets.Label('Comparison')\n",
360
+ "comparison_label.add_class('comparison-label')\n",
361
+ "complete = ipywidgets.HBox([\n",
362
+ "\tipywidgets.VBox([output_widget, download, convert, back]),\n",
363
+ "\tipywidgets.VBox([comparison_widget, comparison_label])\n",
364
+ "])\n",
365
+ "\n",
366
+ "display(ipywidgets.VBox([main, loading, complete]))\n",
367
+ "display(Javascript(\"\"\"\n",
368
+ "var images, videos;\n",
369
+ "function deselectImages() {\n",
370
+ "\timages.forEach(function(item) {\n",
371
+ "\t\titem.classList.remove(\"selected\");\n",
372
+ "\t});\n",
373
+ "}\n",
374
+ "function deselectVideos() {\n",
375
+ "\tvideos.forEach(function(item) {\n",
376
+ "\t\titem.classList.remove(\"selected\");\n",
377
+ "\t});\n",
378
+ "}\n",
379
+ "function invokePython(func) {\n",
380
+ "\tgoogle.colab.kernel.invokeFunction(\"notebook.\" + func, [].slice.call(arguments, 1), {});\n",
381
+ "}\n",
382
+ "setTimeout(function() {\n",
383
+ "\t(images = [].slice.call(document.getElementsByClassName(\"resource-image\"))).forEach(function(item) {\n",
384
+ "\t\titem.addEventListener(\"click\", function() {\n",
385
+ "\t\t\tdeselectImages();\n",
386
+ "\t\t\titem.classList.add(\"selected\");\n",
387
+ "\t\t\tinvokePython(\"select_image\", item.className.match(/resource-image(\\d\\d)/)[1]);\n",
388
+ "\t\t});\n",
389
+ "\t});\n",
390
+ "\timages[0].classList.add(\"selected\");\n",
391
+ "\t(videos = [].slice.call(document.getElementsByClassName(\"resource-video\"))).forEach(function(item) {\n",
392
+ "\t\titem.addEventListener(\"click\", function() {\n",
393
+ "\t\t\tdeselectVideos();\n",
394
+ "\t\t\titem.classList.add(\"selected\");\n",
395
+ "\t\t\tinvokePython(\"select_video\", item.className.match(/resource-video(\\d)/)[1]);\n",
396
+ "\t\t});\n",
397
+ "\t});\n",
398
+ "\tvideos[0].classList.add(\"selected\");\n",
399
+ "}, 1000);\n",
400
+ "\"\"\"))\n",
401
+ "\n",
402
+ "selected_image = None\n",
403
+ "def select_image(filename):\n",
404
+ "\tglobal selected_image\n",
405
+ "\tselected_image = resize(PIL.Image.open('demo/images/%s.png' % filename).convert(\"RGB\"))\n",
406
+ "\tinput_image_widget.clear_output(wait=True)\n",
407
+ "\twith input_image_widget:\n",
408
+ "\t\tdisplay(HTML('Image'))\n",
409
+ "\tinput_image_widget.remove_class('uploaded')\n",
410
+ "output.register_callback(\"notebook.select_image\", select_image)\n",
411
+ "\n",
412
+ "selected_video = None\n",
413
+ "def select_video(filename):\n",
414
+ "\tglobal selected_video\n",
415
+ "\tselected_video = 'demo/videos/%s.mp4' % filename\n",
416
+ "\tinput_video_widget.clear_output(wait=True)\n",
417
+ "\twith input_video_widget:\n",
418
+ "\t\tdisplay(HTML('Video'))\n",
419
+ "\tinput_video_widget.remove_class('uploaded')\n",
420
+ "output.register_callback(\"notebook.select_video\", select_video)\n",
421
+ "\n",
422
+ "def resize(image, size=(256, 256)):\n",
423
+ " w, h = image.size\n",
424
+ " d = min(w, h)\n",
425
+ " r = ((w - d) // 2, (h - d) // 2, (w + d) // 2, (h + d) // 2)\n",
426
+ " return image.resize(size, resample=PIL.Image.LANCZOS, box=r)\n",
427
+ "\n",
428
+ "def upload_image(change):\n",
429
+ "\tglobal selected_image\n",
430
+ "\tfor name, file_info in upload_input_image_button.value.items():\n",
431
+ "\t\tcontent = file_info['content']\n",
432
+ "\tif content is not None:\n",
433
+ "\t\tselected_image = resize(PIL.Image.open(io.BytesIO(content)).convert(\"RGB\"))\n",
434
+ "\t\tinput_image_widget.clear_output(wait=True)\n",
435
+ "\t\twith input_image_widget:\n",
436
+ "\t\t\tdisplay(selected_image)\n",
437
+ "\t\tinput_image_widget.add_class('uploaded')\n",
438
+ "\t\tdisplay(Javascript('deselectImages()'))\n",
439
+ "upload_input_image_button.observe(upload_image, names='value')\n",
440
+ "\n",
441
+ "def upload_video(change):\n",
442
+ "\tglobal selected_video\n",
443
+ "\tfor name, file_info in upload_input_video_button.value.items():\n",
444
+ "\t\tcontent = file_info['content']\n",
445
+ "\tif content is not None:\n",
446
+ "\t\tselected_video = 'user/' + name\n",
447
+ "\t\tpreview = resize(PIL.Image.fromarray(thumbnail(content)).convert(\"RGB\"))\n",
448
+ "\t\tinput_video_widget.clear_output(wait=True)\n",
449
+ "\t\twith input_video_widget:\n",
450
+ "\t\t\tdisplay(preview)\n",
451
+ "\t\tinput_video_widget.add_class('uploaded')\n",
452
+ "\t\tdisplay(Javascript('deselectVideos()'))\n",
453
+ "\t\twith open(selected_video, 'wb') as video:\n",
454
+ "\t\t\tvideo.write(content)\n",
455
+ "upload_input_video_button.observe(upload_video, names='value')\n",
456
+ "\n",
457
+ "def change_model(change):\n",
458
+ "\tif model.value.startswith('vox'):\n",
459
+ "\t\twarning.remove_class('warn')\n",
460
+ "\telse:\n",
461
+ "\t\twarning.add_class('warn')\n",
462
+ "model.observe(change_model, names='value')\n",
463
+ "\n",
464
+ "def generate(button):\n",
465
+ "\tmain.layout.display = 'none'\n",
466
+ "\tloading.layout.display = ''\n",
467
+ "\tfilename = model.value + ('' if model.value == 'fashion' else '-cpk') + '.pth.tar'\n",
468
+ "\tif not os.path.isfile(filename):\n",
469
+ "\t\tdownload = requests.get(requests.get('https://cloud-api.yandex.net/v1/disk/public/resources/download?public_key=https://yadi.sk/d/lEw8uRm140L_eQ&path=/' + filename).json().get('href'))\n",
470
+ "\t\twith open(filename, 'wb') as checkpoint:\n",
471
+ "\t\t\tcheckpoint.write(download.content)\n",
472
+ "\treader = imageio.get_reader(selected_video, mode='I', format='FFMPEG')\n",
473
+ "\tfps = reader.get_meta_data()['fps']\n",
474
+ "\tdriving_video = []\n",
475
+ "\tfor frame in reader:\n",
476
+ "\t\tdriving_video.append(frame)\n",
477
+ "\tgenerator, kp_detector = load_checkpoints(config_path='config/%s-256.yaml' % model.value, checkpoint_path=filename)\n",
478
+ "\tpredictions = make_animation(\n",
479
+ "\t\tskimage.transform.resize(numpy.asarray(selected_image), (256, 256)),\n",
480
+ "\t\t[skimage.transform.resize(frame, (256, 256)) for frame in driving_video],\n",
481
+ "\t\tgenerator,\n",
482
+ "\t\tkp_detector,\n",
483
+ "\t\trelative=relative.value,\n",
484
+ "\t\tadapt_movement_scale=adapt_movement_scale.value\n",
485
+ "\t)\n",
486
+ "\tif selected_video.startswith('user/') or selected_video == 'demo/videos/0.mp4':\n",
487
+ "\t\timageio.mimsave('temp.mp4', [img_as_ubyte(frame) for frame in predictions], fps=fps)\n",
488
+ "\t\tFFmpeg(inputs={'temp.mp4': None, selected_video: None}, outputs={'output.mp4': '-c copy -y'}).run()\n",
489
+ "\telse:\n",
490
+ "\t\timageio.mimsave('output.mp4', [img_as_ubyte(frame) for frame in predictions], fps=fps)\n",
491
+ "\tloading.layout.display = 'none'\n",
492
+ "\tcomplete.layout.display = ''\n",
493
+ "\twith output_widget:\n",
494
+ "\t\tdisplay(HTML('<video id=\"left\" controls src=\"data:video/mp4;base64,%s\" />' % b64encode(open('output.mp4', 'rb').read()).decode()))\n",
495
+ "\twith comparison_widget:\n",
496
+ "\t\tdisplay(HTML('<video id=\"right\" muted src=\"data:video/mp4;base64,%s\" />' % b64encode(open(selected_video, 'rb').read()).decode()))\n",
497
+ "\tdisplay(Javascript(\"\"\"\n",
498
+ "\t(function(left, right) {\n",
499
+ "\t\tleft.addEventListener(\"play\", function() {\n",
500
+ "\t\t\tright.play();\n",
501
+ "\t\t});\n",
502
+ "\t\tleft.addEventListener(\"pause\", function() {\n",
503
+ "\t\t\tright.pause();\n",
504
+ "\t\t});\n",
505
+ "\t\tleft.addEventListener(\"seeking\", function() {\n",
506
+ "\t\t\tright.currentTime = left.currentTime;\n",
507
+ "\t\t});\n",
508
+ "\t})(document.getElementById(\"left\"), document.getElementById(\"right\"));\n",
509
+ "\t\"\"\"))\n",
510
+ "\t\n",
511
+ "generate_button.on_click(generate)\n",
512
+ "\n",
513
+ "loading.layout.display = 'none'\n",
514
+ "complete.layout.display = 'none'\n",
515
+ "select_image('00')\n",
516
+ "select_video('0')"
517
+ ],
518
+ "execution_count": null,
519
+ "outputs": []
520
+ }
521
+ ]
522
+ }
demo.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib
2
+ matplotlib.use('Agg')
3
+ import os, sys
4
+ import yaml
5
+ from argparse import ArgumentParser
6
+ from tqdm import tqdm
7
+
8
+ import imageio
9
+ import numpy as np
10
+ from skimage.transform import resize
11
+ from skimage import img_as_ubyte
12
+ import torch
13
+ from sync_batchnorm import DataParallelWithCallback
14
+
15
+ from modules.generator import OcclusionAwareGenerator
16
+ from modules.keypoint_detector import KPDetector
17
+ from animate import normalize_kp
18
+ from scipy.spatial import ConvexHull
19
+
20
+
21
+ if sys.version_info[0] < 3:
22
+ raise Exception("You must use Python 3 or higher. Recommended version is Python 3.7")
23
+
24
+ def load_checkpoints(config_path, checkpoint_path, cpu=False):
25
+
26
+ with open(config_path) as f:
27
+ config = yaml.load(f)
28
+
29
+ generator = OcclusionAwareGenerator(**config['model_params']['generator_params'],
30
+ **config['model_params']['common_params'])
31
+ if not cpu:
32
+ generator.cuda()
33
+
34
+ kp_detector = KPDetector(**config['model_params']['kp_detector_params'],
35
+ **config['model_params']['common_params'])
36
+ if not cpu:
37
+ kp_detector.cuda()
38
+
39
+ if cpu:
40
+ checkpoint = torch.load(checkpoint_path, map_location=torch.device('cpu'))
41
+ else:
42
+ checkpoint = torch.load(checkpoint_path)
43
+
44
+ generator.load_state_dict(checkpoint['generator'])
45
+ kp_detector.load_state_dict(checkpoint['kp_detector'])
46
+
47
+ if not cpu:
48
+ generator = DataParallelWithCallback(generator)
49
+ kp_detector = DataParallelWithCallback(kp_detector)
50
+
51
+ generator.eval()
52
+ kp_detector.eval()
53
+
54
+ return generator, kp_detector
55
+
56
+
57
+ def make_animation(source_image, driving_video, generator, kp_detector, relative=True, adapt_movement_scale=True, cpu=False):
58
+ with torch.no_grad():
59
+ predictions = []
60
+ source = torch.tensor(source_image[np.newaxis].astype(np.float32)).permute(0, 3, 1, 2)
61
+ if not cpu:
62
+ source = source.cuda()
63
+ driving = torch.tensor(np.array(driving_video)[np.newaxis].astype(np.float32)).permute(0, 4, 1, 2, 3)
64
+ kp_source = kp_detector(source)
65
+ kp_driving_initial = kp_detector(driving[:, :, 0])
66
+
67
+ for frame_idx in tqdm(range(driving.shape[2])):
68
+ driving_frame = driving[:, :, frame_idx]
69
+ if not cpu:
70
+ driving_frame = driving_frame.cuda()
71
+ kp_driving = kp_detector(driving_frame)
72
+ kp_norm = normalize_kp(kp_source=kp_source, kp_driving=kp_driving,
73
+ kp_driving_initial=kp_driving_initial, use_relative_movement=relative,
74
+ use_relative_jacobian=relative, adapt_movement_scale=adapt_movement_scale)
75
+ out = generator(source, kp_source=kp_source, kp_driving=kp_norm)
76
+
77
+ predictions.append(np.transpose(out['prediction'].data.cpu().numpy(), [0, 2, 3, 1])[0])
78
+ return predictions
79
+
80
+ def find_best_frame(source, driving, cpu=False):
81
+ import face_alignment
82
+
83
+ def normalize_kp(kp):
84
+ kp = kp - kp.mean(axis=0, keepdims=True)
85
+ area = ConvexHull(kp[:, :2]).volume
86
+ area = np.sqrt(area)
87
+ kp[:, :2] = kp[:, :2] / area
88
+ return kp
89
+
90
+ fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, flip_input=True,
91
+ device='cpu' if cpu else 'cuda')
92
+ kp_source = fa.get_landmarks(255 * source)[0]
93
+ kp_source = normalize_kp(kp_source)
94
+ norm = float('inf')
95
+ frame_num = 0
96
+ for i, image in tqdm(enumerate(driving)):
97
+ kp_driving = fa.get_landmarks(255 * image)[0]
98
+ kp_driving = normalize_kp(kp_driving)
99
+ new_norm = (np.abs(kp_source - kp_driving) ** 2).sum()
100
+ if new_norm < norm:
101
+ norm = new_norm
102
+ frame_num = i
103
+ return frame_num
104
+
105
+ if __name__ == "__main__":
106
+ parser = ArgumentParser()
107
+ parser.add_argument("--config", required=True, help="path to config")
108
+ parser.add_argument("--checkpoint", default='vox-cpk.pth.tar', help="path to checkpoint to restore")
109
+
110
+ parser.add_argument("--source_image", default='sup-mat/source.png', help="path to source image")
111
+ parser.add_argument("--driving_video", default='sup-mat/source.png', help="path to driving video")
112
+ parser.add_argument("--result_video", default='result.mp4', help="path to output")
113
+
114
+ parser.add_argument("--relative", dest="relative", action="store_true", help="use relative or absolute keypoint coordinates")
115
+ parser.add_argument("--adapt_scale", dest="adapt_scale", action="store_true", help="adapt movement scale based on convex hull of keypoints")
116
+
117
+ parser.add_argument("--find_best_frame", dest="find_best_frame", action="store_true",
118
+ help="Generate from the frame that is the most alligned with source. (Only for faces, requires face_aligment lib)")
119
+
120
+ parser.add_argument("--best_frame", dest="best_frame", type=int, default=None,
121
+ help="Set frame to start from.")
122
+
123
+ parser.add_argument("--cpu", dest="cpu", action="store_true", help="cpu mode.")
124
+
125
+
126
+ parser.set_defaults(relative=False)
127
+ parser.set_defaults(adapt_scale=False)
128
+
129
+ opt = parser.parse_args()
130
+
131
+ source_image = imageio.imread(opt.source_image)
132
+ reader = imageio.get_reader(opt.driving_video)
133
+ fps = reader.get_meta_data()['fps']
134
+ driving_video = []
135
+ try:
136
+ for im in reader:
137
+ driving_video.append(im)
138
+ except RuntimeError:
139
+ pass
140
+ reader.close()
141
+
142
+ source_image = resize(source_image, (256, 256))[..., :3]
143
+ driving_video = [resize(frame, (256, 256))[..., :3] for frame in driving_video]
144
+ generator, kp_detector = load_checkpoints(config_path=opt.config, checkpoint_path=opt.checkpoint, cpu=opt.cpu)
145
+
146
+ if opt.find_best_frame or opt.best_frame is not None:
147
+ i = opt.best_frame if opt.best_frame is not None else find_best_frame(source_image, driving_video, cpu=opt.cpu)
148
+ print ("Best frame: " + str(i))
149
+ driving_forward = driving_video[i:]
150
+ driving_backward = driving_video[:(i+1)][::-1]
151
+ predictions_forward = make_animation(source_image, driving_forward, generator, kp_detector, relative=opt.relative, adapt_movement_scale=opt.adapt_scale, cpu=opt.cpu)
152
+ predictions_backward = make_animation(source_image, driving_backward, generator, kp_detector, relative=opt.relative, adapt_movement_scale=opt.adapt_scale, cpu=opt.cpu)
153
+ predictions = predictions_backward[::-1] + predictions_forward[1:]
154
+ else:
155
+ predictions = make_animation(source_image, driving_video, generator, kp_detector, relative=opt.relative, adapt_movement_scale=opt.adapt_scale, cpu=opt.cpu)
156
+ imageio.mimsave(opt.result_video, [img_as_ubyte(frame) for frame in predictions], fps=fps)
157
+
frames_dataset.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from skimage import io, img_as_float32
3
+ from skimage.color import gray2rgb
4
+ from sklearn.model_selection import train_test_split
5
+ from imageio import mimread
6
+
7
+ import numpy as np
8
+ from torch.utils.data import Dataset
9
+ import pandas as pd
10
+ from augmentation import AllAugmentationTransform
11
+ import glob
12
+
13
+
14
+ def read_video(name, frame_shape):
15
+ """
16
+ Read video which can be:
17
+ - an image of concatenated frames
18
+ - '.mp4' and'.gif'
19
+ - folder with videos
20
+ """
21
+
22
+ if os.path.isdir(name):
23
+ frames = sorted(os.listdir(name))
24
+ num_frames = len(frames)
25
+ video_array = np.array(
26
+ [img_as_float32(io.imread(os.path.join(name, frames[idx]))) for idx in range(num_frames)])
27
+ elif name.lower().endswith('.png') or name.lower().endswith('.jpg'):
28
+ image = io.imread(name)
29
+
30
+ if len(image.shape) == 2 or image.shape[2] == 1:
31
+ image = gray2rgb(image)
32
+
33
+ if image.shape[2] == 4:
34
+ image = image[..., :3]
35
+
36
+ image = img_as_float32(image)
37
+
38
+ video_array = np.moveaxis(image, 1, 0)
39
+
40
+ video_array = video_array.reshape((-1,) + frame_shape)
41
+ video_array = np.moveaxis(video_array, 1, 2)
42
+ elif name.lower().endswith('.gif') or name.lower().endswith('.mp4') or name.lower().endswith('.mov'):
43
+ video = np.array(mimread(name))
44
+ if len(video.shape) == 3:
45
+ video = np.array([gray2rgb(frame) for frame in video])
46
+ if video.shape[-1] == 4:
47
+ video = video[..., :3]
48
+ video_array = img_as_float32(video)
49
+ else:
50
+ raise Exception("Unknown file extensions %s" % name)
51
+
52
+ return video_array
53
+
54
+
55
+ class FramesDataset(Dataset):
56
+ """
57
+ Dataset of videos, each video can be represented as:
58
+ - an image of concatenated frames
59
+ - '.mp4' or '.gif'
60
+ - folder with all frames
61
+ """
62
+
63
+ def __init__(self, root_dir, frame_shape=(256, 256, 3), id_sampling=False, is_train=True,
64
+ random_seed=0, pairs_list=None, augmentation_params=None):
65
+ self.root_dir = root_dir
66
+ self.videos = os.listdir(root_dir)
67
+ self.frame_shape = tuple(frame_shape)
68
+ self.pairs_list = pairs_list
69
+ self.id_sampling = id_sampling
70
+ if os.path.exists(os.path.join(root_dir, 'train')):
71
+ assert os.path.exists(os.path.join(root_dir, 'test'))
72
+ print("Use predefined train-test split.")
73
+ if id_sampling:
74
+ train_videos = {os.path.basename(video).split('#')[0] for video in
75
+ os.listdir(os.path.join(root_dir, 'train'))}
76
+ train_videos = list(train_videos)
77
+ else:
78
+ train_videos = os.listdir(os.path.join(root_dir, 'train'))
79
+ test_videos = os.listdir(os.path.join(root_dir, 'test'))
80
+ self.root_dir = os.path.join(self.root_dir, 'train' if is_train else 'test')
81
+ else:
82
+ print("Use random train-test split.")
83
+ train_videos, test_videos = train_test_split(self.videos, random_state=random_seed, test_size=0.2)
84
+
85
+ if is_train:
86
+ self.videos = train_videos
87
+ else:
88
+ self.videos = test_videos
89
+
90
+ self.is_train = is_train
91
+
92
+ if self.is_train:
93
+ self.transform = AllAugmentationTransform(**augmentation_params)
94
+ else:
95
+ self.transform = None
96
+
97
+ def __len__(self):
98
+ return len(self.videos)
99
+
100
+ def __getitem__(self, idx):
101
+ if self.is_train and self.id_sampling:
102
+ name = self.videos[idx]
103
+ path = np.random.choice(glob.glob(os.path.join(self.root_dir, name + '*.mp4')))
104
+ else:
105
+ name = self.videos[idx]
106
+ path = os.path.join(self.root_dir, name)
107
+
108
+ video_name = os.path.basename(path)
109
+
110
+ if self.is_train and os.path.isdir(path):
111
+ frames = os.listdir(path)
112
+ num_frames = len(frames)
113
+ frame_idx = np.sort(np.random.choice(num_frames, replace=True, size=2))
114
+ video_array = [img_as_float32(io.imread(os.path.join(path, frames[idx]))) for idx in frame_idx]
115
+ else:
116
+ video_array = read_video(path, frame_shape=self.frame_shape)
117
+ num_frames = len(video_array)
118
+ frame_idx = np.sort(np.random.choice(num_frames, replace=True, size=2)) if self.is_train else range(
119
+ num_frames)
120
+ video_array = video_array[frame_idx]
121
+
122
+ if self.transform is not None:
123
+ video_array = self.transform(video_array)
124
+
125
+ out = {}
126
+ if self.is_train:
127
+ source = np.array(video_array[0], dtype='float32')
128
+ driving = np.array(video_array[1], dtype='float32')
129
+
130
+ out['driving'] = driving.transpose((2, 0, 1))
131
+ out['source'] = source.transpose((2, 0, 1))
132
+ else:
133
+ video = np.array(video_array, dtype='float32')
134
+ out['video'] = video.transpose((3, 0, 1, 2))
135
+
136
+ out['name'] = video_name
137
+
138
+ return out
139
+
140
+
141
+ class DatasetRepeater(Dataset):
142
+ """
143
+ Pass several times over the same dataset for better i/o performance
144
+ """
145
+
146
+ def __init__(self, dataset, num_repeats=100):
147
+ self.dataset = dataset
148
+ self.num_repeats = num_repeats
149
+
150
+ def __len__(self):
151
+ return self.num_repeats * self.dataset.__len__()
152
+
153
+ def __getitem__(self, idx):
154
+ return self.dataset[idx % self.dataset.__len__()]
155
+
156
+
157
+ class PairedDataset(Dataset):
158
+ """
159
+ Dataset of pairs for animation.
160
+ """
161
+
162
+ def __init__(self, initial_dataset, number_of_pairs, seed=0):
163
+ self.initial_dataset = initial_dataset
164
+ pairs_list = self.initial_dataset.pairs_list
165
+
166
+ np.random.seed(seed)
167
+
168
+ if pairs_list is None:
169
+ max_idx = min(number_of_pairs, len(initial_dataset))
170
+ nx, ny = max_idx, max_idx
171
+ xy = np.mgrid[:nx, :ny].reshape(2, -1).T
172
+ number_of_pairs = min(xy.shape[0], number_of_pairs)
173
+ self.pairs = xy.take(np.random.choice(xy.shape[0], number_of_pairs, replace=False), axis=0)
174
+ else:
175
+ videos = self.initial_dataset.videos
176
+ name_to_index = {name: index for index, name in enumerate(videos)}
177
+ pairs = pd.read_csv(pairs_list)
178
+ pairs = pairs[np.logical_and(pairs['source'].isin(videos), pairs['driving'].isin(videos))]
179
+
180
+ number_of_pairs = min(pairs.shape[0], number_of_pairs)
181
+ self.pairs = []
182
+ self.start_frames = []
183
+ for ind in range(number_of_pairs):
184
+ self.pairs.append(
185
+ (name_to_index[pairs['driving'].iloc[ind]], name_to_index[pairs['source'].iloc[ind]]))
186
+
187
+ def __len__(self):
188
+ return len(self.pairs)
189
+
190
+ def __getitem__(self, idx):
191
+ pair = self.pairs[idx]
192
+ first = self.initial_dataset[pair[0]]
193
+ second = self.initial_dataset[pair[1]]
194
+ first = {'driving_' + key: value for key, value in first.items()}
195
+ second = {'source_' + key: value for key, value in second.items()}
196
+
197
+ return {**first, **second}
logger.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ import torch
3
+ import torch.nn.functional as F
4
+ import imageio
5
+
6
+ import os
7
+ from skimage.draw import circle
8
+
9
+ import matplotlib.pyplot as plt
10
+ import collections
11
+
12
+
13
+ class Logger:
14
+ def __init__(self, log_dir, checkpoint_freq=100, visualizer_params=None, zfill_num=8, log_file_name='log.txt'):
15
+
16
+ self.loss_list = []
17
+ self.cpk_dir = log_dir
18
+ self.visualizations_dir = os.path.join(log_dir, 'train-vis')
19
+ if not os.path.exists(self.visualizations_dir):
20
+ os.makedirs(self.visualizations_dir)
21
+ self.log_file = open(os.path.join(log_dir, log_file_name), 'a')
22
+ self.zfill_num = zfill_num
23
+ self.visualizer = Visualizer(**visualizer_params)
24
+ self.checkpoint_freq = checkpoint_freq
25
+ self.epoch = 0
26
+ self.best_loss = float('inf')
27
+ self.names = None
28
+
29
+ def log_scores(self, loss_names):
30
+ loss_mean = np.array(self.loss_list).mean(axis=0)
31
+
32
+ loss_string = "; ".join(["%s - %.5f" % (name, value) for name, value in zip(loss_names, loss_mean)])
33
+ loss_string = str(self.epoch).zfill(self.zfill_num) + ") " + loss_string
34
+
35
+ print(loss_string, file=self.log_file)
36
+ self.loss_list = []
37
+ self.log_file.flush()
38
+
39
+ def visualize_rec(self, inp, out):
40
+ image = self.visualizer.visualize(inp['driving'], inp['source'], out)
41
+ imageio.imsave(os.path.join(self.visualizations_dir, "%s-rec.png" % str(self.epoch).zfill(self.zfill_num)), image)
42
+
43
+ def save_cpk(self, emergent=False):
44
+ cpk = {k: v.state_dict() for k, v in self.models.items()}
45
+ cpk['epoch'] = self.epoch
46
+ cpk_path = os.path.join(self.cpk_dir, '%s-checkpoint.pth.tar' % str(self.epoch).zfill(self.zfill_num))
47
+ if not (os.path.exists(cpk_path) and emergent):
48
+ torch.save(cpk, cpk_path)
49
+
50
+ @staticmethod
51
+ def load_cpk(checkpoint_path, generator=None, discriminator=None, kp_detector=None,
52
+ optimizer_generator=None, optimizer_discriminator=None, optimizer_kp_detector=None):
53
+ checkpoint = torch.load(checkpoint_path)
54
+ if generator is not None:
55
+ generator.load_state_dict(checkpoint['generator'])
56
+ if kp_detector is not None:
57
+ kp_detector.load_state_dict(checkpoint['kp_detector'])
58
+ if discriminator is not None:
59
+ try:
60
+ discriminator.load_state_dict(checkpoint['discriminator'])
61
+ except:
62
+ print ('No discriminator in the state-dict. Dicriminator will be randomly initialized')
63
+ if optimizer_generator is not None:
64
+ optimizer_generator.load_state_dict(checkpoint['optimizer_generator'])
65
+ if optimizer_discriminator is not None:
66
+ try:
67
+ optimizer_discriminator.load_state_dict(checkpoint['optimizer_discriminator'])
68
+ except RuntimeError as e:
69
+ print ('No discriminator optimizer in the state-dict. Optimizer will be not initialized')
70
+ if optimizer_kp_detector is not None:
71
+ optimizer_kp_detector.load_state_dict(checkpoint['optimizer_kp_detector'])
72
+
73
+ return checkpoint['epoch']
74
+
75
+ def __enter__(self):
76
+ return self
77
+
78
+ def __exit__(self, exc_type, exc_val, exc_tb):
79
+ if 'models' in self.__dict__:
80
+ self.save_cpk()
81
+ self.log_file.close()
82
+
83
+ def log_iter(self, losses):
84
+ losses = collections.OrderedDict(losses.items())
85
+ if self.names is None:
86
+ self.names = list(losses.keys())
87
+ self.loss_list.append(list(losses.values()))
88
+
89
+ def log_epoch(self, epoch, models, inp, out):
90
+ self.epoch = epoch
91
+ self.models = models
92
+ if (self.epoch + 1) % self.checkpoint_freq == 0:
93
+ self.save_cpk()
94
+ self.log_scores(self.names)
95
+ self.visualize_rec(inp, out)
96
+
97
+
98
+ class Visualizer:
99
+ def __init__(self, kp_size=5, draw_border=False, colormap='gist_rainbow'):
100
+ self.kp_size = kp_size
101
+ self.draw_border = draw_border
102
+ self.colormap = plt.get_cmap(colormap)
103
+
104
+ def draw_image_with_kp(self, image, kp_array):
105
+ image = np.copy(image)
106
+ spatial_size = np.array(image.shape[:2][::-1])[np.newaxis]
107
+ kp_array = spatial_size * (kp_array + 1) / 2
108
+ num_kp = kp_array.shape[0]
109
+ for kp_ind, kp in enumerate(kp_array):
110
+ rr, cc = circle(kp[1], kp[0], self.kp_size, shape=image.shape[:2])
111
+ image[rr, cc] = np.array(self.colormap(kp_ind / num_kp))[:3]
112
+ return image
113
+
114
+ def create_image_column_with_kp(self, images, kp):
115
+ image_array = np.array([self.draw_image_with_kp(v, k) for v, k in zip(images, kp)])
116
+ return self.create_image_column(image_array)
117
+
118
+ def create_image_column(self, images):
119
+ if self.draw_border:
120
+ images = np.copy(images)
121
+ images[:, :, [0, -1]] = (1, 1, 1)
122
+ images[:, :, [0, -1]] = (1, 1, 1)
123
+ return np.concatenate(list(images), axis=0)
124
+
125
+ def create_image_grid(self, *args):
126
+ out = []
127
+ for arg in args:
128
+ if type(arg) == tuple:
129
+ out.append(self.create_image_column_with_kp(arg[0], arg[1]))
130
+ else:
131
+ out.append(self.create_image_column(arg))
132
+ return np.concatenate(out, axis=1)
133
+
134
+ def visualize(self, driving, source, out):
135
+ images = []
136
+
137
+ # Source image with keypoints
138
+ source = source.data.cpu()
139
+ kp_source = out['kp_source']['value'].data.cpu().numpy()
140
+ source = np.transpose(source, [0, 2, 3, 1])
141
+ images.append((source, kp_source))
142
+
143
+ # Equivariance visualization
144
+ if 'transformed_frame' in out:
145
+ transformed = out['transformed_frame'].data.cpu().numpy()
146
+ transformed = np.transpose(transformed, [0, 2, 3, 1])
147
+ transformed_kp = out['transformed_kp']['value'].data.cpu().numpy()
148
+ images.append((transformed, transformed_kp))
149
+
150
+ # Driving image with keypoints
151
+ kp_driving = out['kp_driving']['value'].data.cpu().numpy()
152
+ driving = driving.data.cpu().numpy()
153
+ driving = np.transpose(driving, [0, 2, 3, 1])
154
+ images.append((driving, kp_driving))
155
+
156
+ # Deformed image
157
+ if 'deformed' in out:
158
+ deformed = out['deformed'].data.cpu().numpy()
159
+ deformed = np.transpose(deformed, [0, 2, 3, 1])
160
+ images.append(deformed)
161
+
162
+ # Result with and without keypoints
163
+ prediction = out['prediction'].data.cpu().numpy()
164
+ prediction = np.transpose(prediction, [0, 2, 3, 1])
165
+ if 'kp_norm' in out:
166
+ kp_norm = out['kp_norm']['value'].data.cpu().numpy()
167
+ images.append((prediction, kp_norm))
168
+ images.append(prediction)
169
+
170
+
171
+ ## Occlusion map
172
+ if 'occlusion_map' in out:
173
+ occlusion_map = out['occlusion_map'].data.cpu().repeat(1, 3, 1, 1)
174
+ occlusion_map = F.interpolate(occlusion_map, size=source.shape[1:3]).numpy()
175
+ occlusion_map = np.transpose(occlusion_map, [0, 2, 3, 1])
176
+ images.append(occlusion_map)
177
+
178
+ # Deformed images according to each individual transform
179
+ if 'sparse_deformed' in out:
180
+ full_mask = []
181
+ for i in range(out['sparse_deformed'].shape[1]):
182
+ image = out['sparse_deformed'][:, i].data.cpu()
183
+ image = F.interpolate(image, size=source.shape[1:3])
184
+ mask = out['mask'][:, i:(i+1)].data.cpu().repeat(1, 3, 1, 1)
185
+ mask = F.interpolate(mask, size=source.shape[1:3])
186
+ image = np.transpose(image.numpy(), (0, 2, 3, 1))
187
+ mask = np.transpose(mask.numpy(), (0, 2, 3, 1))
188
+
189
+ if i != 0:
190
+ color = np.array(self.colormap((i - 1) / (out['sparse_deformed'].shape[1] - 1)))[:3]
191
+ else:
192
+ color = np.array((0, 0, 0))
193
+
194
+ color = color.reshape((1, 1, 1, 3))
195
+
196
+ images.append(image)
197
+ if i != 0:
198
+ images.append(mask * color)
199
+ else:
200
+ images.append(mask)
201
+
202
+ full_mask.append(mask * color)
203
+
204
+ images.append(sum(full_mask))
205
+
206
+ image = self.create_image_grid(*images)
207
+ image = (255 * image).astype(np.uint8)
208
+ return image
old_demo.ipynb ADDED
The diff for this file is too large to render. See raw diff
 
reconstruction.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from tqdm import tqdm
3
+ import torch
4
+ from torch.utils.data import DataLoader
5
+ from logger import Logger, Visualizer
6
+ import numpy as np
7
+ import imageio
8
+ from sync_batchnorm import DataParallelWithCallback
9
+
10
+
11
+ def reconstruction(config, generator, kp_detector, checkpoint, log_dir, dataset):
12
+ png_dir = os.path.join(log_dir, 'reconstruction/png')
13
+ log_dir = os.path.join(log_dir, 'reconstruction')
14
+
15
+ if checkpoint is not None:
16
+ Logger.load_cpk(checkpoint, generator=generator, kp_detector=kp_detector)
17
+ else:
18
+ raise AttributeError("Checkpoint should be specified for mode='reconstruction'.")
19
+ dataloader = DataLoader(dataset, batch_size=1, shuffle=False, num_workers=1)
20
+
21
+ if not os.path.exists(log_dir):
22
+ os.makedirs(log_dir)
23
+
24
+ if not os.path.exists(png_dir):
25
+ os.makedirs(png_dir)
26
+
27
+ loss_list = []
28
+ if torch.cuda.is_available():
29
+ generator = DataParallelWithCallback(generator)
30
+ kp_detector = DataParallelWithCallback(kp_detector)
31
+
32
+ generator.eval()
33
+ kp_detector.eval()
34
+
35
+ for it, x in tqdm(enumerate(dataloader)):
36
+ if config['reconstruction_params']['num_videos'] is not None:
37
+ if it > config['reconstruction_params']['num_videos']:
38
+ break
39
+ with torch.no_grad():
40
+ predictions = []
41
+ visualizations = []
42
+ if torch.cuda.is_available():
43
+ x['video'] = x['video'].cuda()
44
+ kp_source = kp_detector(x['video'][:, :, 0])
45
+ for frame_idx in range(x['video'].shape[2]):
46
+ source = x['video'][:, :, 0]
47
+ driving = x['video'][:, :, frame_idx]
48
+ kp_driving = kp_detector(driving)
49
+ out = generator(source, kp_source=kp_source, kp_driving=kp_driving)
50
+ out['kp_source'] = kp_source
51
+ out['kp_driving'] = kp_driving
52
+ del out['sparse_deformed']
53
+ predictions.append(np.transpose(out['prediction'].data.cpu().numpy(), [0, 2, 3, 1])[0])
54
+
55
+ visualization = Visualizer(**config['visualizer_params']).visualize(source=source,
56
+ driving=driving, out=out)
57
+ visualizations.append(visualization)
58
+
59
+ loss_list.append(torch.abs(out['prediction'] - driving).mean().cpu().numpy())
60
+
61
+ predictions = np.concatenate(predictions, axis=1)
62
+ imageio.imsave(os.path.join(png_dir, x['name'][0] + '.png'), (255 * predictions).astype(np.uint8))
63
+
64
+ image_name = x['name'][0] + config['reconstruction_params']['format']
65
+ imageio.mimsave(os.path.join(log_dir, image_name), visualizations)
66
+
67
+ print("Reconstruction loss: %s" % np.mean(loss_list))
requirements.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ imageio==2.3.0
2
+ matplotlib==2.2.2
3
+ numpy==1.15.0
4
+ pandas==0.23.4
5
+ python-dateutil==2.7.3
6
+ pytz==2018.5
7
+ PyYAML==5.1
8
+ scikit-image==0.14.0
9
+ scikit-learn==0.19.2
10
+ scipy==1.1.0
11
+ torch==1.0.0
12
+ torchvision==0.2.1
13
+ tqdm==4.24.0
run.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib
2
+
3
+ matplotlib.use('Agg')
4
+
5
+ import os, sys
6
+ import yaml
7
+ from argparse import ArgumentParser
8
+ from time import gmtime, strftime
9
+ from shutil import copy
10
+
11
+ from frames_dataset import FramesDataset
12
+
13
+ from modules.generator import OcclusionAwareGenerator
14
+ from modules.discriminator import MultiScaleDiscriminator
15
+ from modules.keypoint_detector import KPDetector
16
+
17
+ import torch
18
+
19
+ from train import train
20
+ from reconstruction import reconstruction
21
+ from animate import animate
22
+
23
+ if __name__ == "__main__":
24
+
25
+ if sys.version_info[0] < 3:
26
+ raise Exception("You must use Python 3 or higher. Recommended version is Python 3.7")
27
+
28
+ parser = ArgumentParser()
29
+ parser.add_argument("--config", required=True, help="path to config")
30
+ parser.add_argument("--mode", default="train", choices=["train", "reconstruction", "animate"])
31
+ parser.add_argument("--log_dir", default='log', help="path to log into")
32
+ parser.add_argument("--checkpoint", default=None, help="path to checkpoint to restore")
33
+ parser.add_argument("--device_ids", default="0", type=lambda x: list(map(int, x.split(','))),
34
+ help="Names of the devices comma separated.")
35
+ parser.add_argument("--verbose", dest="verbose", action="store_true", help="Print model architecture")
36
+ parser.set_defaults(verbose=False)
37
+
38
+ opt = parser.parse_args()
39
+ with open(opt.config) as f:
40
+ config = yaml.load(f)
41
+
42
+ if opt.checkpoint is not None:
43
+ log_dir = os.path.join(*os.path.split(opt.checkpoint)[:-1])
44
+ else:
45
+ log_dir = os.path.join(opt.log_dir, os.path.basename(opt.config).split('.')[0])
46
+ log_dir += ' ' + strftime("%d_%m_%y_%H.%M.%S", gmtime())
47
+
48
+ generator = OcclusionAwareGenerator(**config['model_params']['generator_params'],
49
+ **config['model_params']['common_params'])
50
+
51
+ if torch.cuda.is_available():
52
+ generator.to(opt.device_ids[0])
53
+ if opt.verbose:
54
+ print(generator)
55
+
56
+ discriminator = MultiScaleDiscriminator(**config['model_params']['discriminator_params'],
57
+ **config['model_params']['common_params'])
58
+ if torch.cuda.is_available():
59
+ discriminator.to(opt.device_ids[0])
60
+ if opt.verbose:
61
+ print(discriminator)
62
+
63
+ kp_detector = KPDetector(**config['model_params']['kp_detector_params'],
64
+ **config['model_params']['common_params'])
65
+
66
+ if torch.cuda.is_available():
67
+ kp_detector.to(opt.device_ids[0])
68
+
69
+ if opt.verbose:
70
+ print(kp_detector)
71
+
72
+ dataset = FramesDataset(is_train=(opt.mode == 'train'), **config['dataset_params'])
73
+
74
+ if not os.path.exists(log_dir):
75
+ os.makedirs(log_dir)
76
+ if not os.path.exists(os.path.join(log_dir, os.path.basename(opt.config))):
77
+ copy(opt.config, log_dir)
78
+
79
+ if opt.mode == 'train':
80
+ print("Training...")
81
+ train(config, generator, discriminator, kp_detector, opt.checkpoint, log_dir, dataset, opt.device_ids)
82
+ elif opt.mode == 'reconstruction':
83
+ print("Reconstruction...")
84
+ reconstruction(config, generator, kp_detector, opt.checkpoint, log_dir, dataset)
85
+ elif opt.mode == 'animate':
86
+ print("Animate...")
87
+ animate(config, generator, kp_detector, opt.checkpoint, log_dir, dataset)
train.py ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tqdm import trange
2
+ import torch
3
+
4
+ from torch.utils.data import DataLoader
5
+
6
+ from logger import Logger
7
+ from modules.model import GeneratorFullModel, DiscriminatorFullModel
8
+
9
+ from torch.optim.lr_scheduler import MultiStepLR
10
+
11
+ from sync_batchnorm import DataParallelWithCallback
12
+
13
+ from frames_dataset import DatasetRepeater
14
+
15
+
16
+ def train(config, generator, discriminator, kp_detector, checkpoint, log_dir, dataset, device_ids):
17
+ train_params = config['train_params']
18
+
19
+ optimizer_generator = torch.optim.Adam(generator.parameters(), lr=train_params['lr_generator'], betas=(0.5, 0.999))
20
+ optimizer_discriminator = torch.optim.Adam(discriminator.parameters(), lr=train_params['lr_discriminator'], betas=(0.5, 0.999))
21
+ optimizer_kp_detector = torch.optim.Adam(kp_detector.parameters(), lr=train_params['lr_kp_detector'], betas=(0.5, 0.999))
22
+
23
+ if checkpoint is not None:
24
+ start_epoch = Logger.load_cpk(checkpoint, generator, discriminator, kp_detector,
25
+ optimizer_generator, optimizer_discriminator,
26
+ None if train_params['lr_kp_detector'] == 0 else optimizer_kp_detector)
27
+ else:
28
+ start_epoch = 0
29
+
30
+ scheduler_generator = MultiStepLR(optimizer_generator, train_params['epoch_milestones'], gamma=0.1,
31
+ last_epoch=start_epoch - 1)
32
+ scheduler_discriminator = MultiStepLR(optimizer_discriminator, train_params['epoch_milestones'], gamma=0.1,
33
+ last_epoch=start_epoch - 1)
34
+ scheduler_kp_detector = MultiStepLR(optimizer_kp_detector, train_params['epoch_milestones'], gamma=0.1,
35
+ last_epoch=-1 + start_epoch * (train_params['lr_kp_detector'] != 0))
36
+
37
+ if 'num_repeats' in train_params or train_params['num_repeats'] != 1:
38
+ dataset = DatasetRepeater(dataset, train_params['num_repeats'])
39
+ dataloader = DataLoader(dataset, batch_size=train_params['batch_size'], shuffle=True, num_workers=6, drop_last=True)
40
+
41
+ generator_full = GeneratorFullModel(kp_detector, generator, discriminator, train_params)
42
+ discriminator_full = DiscriminatorFullModel(kp_detector, generator, discriminator, train_params)
43
+
44
+ if torch.cuda.is_available():
45
+ generator_full = DataParallelWithCallback(generator_full, device_ids=device_ids)
46
+ discriminator_full = DataParallelWithCallback(discriminator_full, device_ids=device_ids)
47
+
48
+ with Logger(log_dir=log_dir, visualizer_params=config['visualizer_params'], checkpoint_freq=train_params['checkpoint_freq']) as logger:
49
+ for epoch in trange(start_epoch, train_params['num_epochs']):
50
+ for x in dataloader:
51
+ losses_generator, generated = generator_full(x)
52
+
53
+ loss_values = [val.mean() for val in losses_generator.values()]
54
+ loss = sum(loss_values)
55
+
56
+ loss.backward()
57
+ optimizer_generator.step()
58
+ optimizer_generator.zero_grad()
59
+ optimizer_kp_detector.step()
60
+ optimizer_kp_detector.zero_grad()
61
+
62
+ if train_params['loss_weights']['generator_gan'] != 0:
63
+ optimizer_discriminator.zero_grad()
64
+ losses_discriminator = discriminator_full(x, generated)
65
+ loss_values = [val.mean() for val in losses_discriminator.values()]
66
+ loss = sum(loss_values)
67
+
68
+ loss.backward()
69
+ optimizer_discriminator.step()
70
+ optimizer_discriminator.zero_grad()
71
+ else:
72
+ losses_discriminator = {}
73
+
74
+ losses_generator.update(losses_discriminator)
75
+ losses = {key: value.mean().detach().data.cpu().numpy() for key, value in losses_generator.items()}
76
+ logger.log_iter(losses=losses)
77
+
78
+ scheduler_generator.step()
79
+ scheduler_discriminator.step()
80
+ scheduler_kp_detector.step()
81
+
82
+ logger.log_epoch(epoch, {'generator': generator,
83
+ 'discriminator': discriminator,
84
+ 'kp_detector': kp_detector,
85
+ 'optimizer_generator': optimizer_generator,
86
+ 'optimizer_discriminator': optimizer_discriminator,
87
+ 'optimizer_kp_detector': optimizer_kp_detector}, inp=x, out=generated)