Upload 18 files
Browse files- .dockerignore +3 -0
- .gitignore +3 -0
- Dockerfile +13 -0
- LICENSE.md +21 -0
- README.md +180 -0
- animate.py +101 -0
- augmentation.py +345 -0
- crop-video.py +158 -0
- demo.ipynb +543 -0
- demo.py +168 -0
- demo_jupyter.ipynb +804 -0
- frames_dataset.py +197 -0
- logger.py +211 -0
- old_demo.ipynb +0 -0
- reconstruction.py +67 -0
- requirements.txt +15 -0
- run.py +87 -0
- train.py +87 -0
.dockerignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/venv
|
| 2 |
+
.git
|
| 3 |
+
__pycache__
|
.gitignore
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/.vscode
|
| 2 |
+
__pycache__
|
| 3 |
+
/venv
|
Dockerfile
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM nvcr.io/nvidia/pytorch:21.02-py3
|
| 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 |
+
git+https://github.com/1adrianb/face-alignment \
|
| 13 |
+
-r requirements.txt
|
LICENSE.md
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
MIT License
|
| 2 |
+
|
| 3 |
+
Copyright (c) 2019-2023 Aliaksandr Siarohin
|
| 4 |
+
|
| 5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
| 6 |
+
of this software and associated documentation files (the "Software"), to deal
|
| 7 |
+
in the Software without restriction, including without limitation the rights
|
| 8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
| 9 |
+
copies of the Software, and to permit persons to whom the Software is
|
| 10 |
+
furnished to do so, subject to the following conditions:
|
| 11 |
+
|
| 12 |
+
The above copyright notice and this permission notice shall be included in all
|
| 13 |
+
copies or substantial portions of the Software.
|
| 14 |
+
|
| 15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
| 16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
| 17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
| 18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
| 19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
| 20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
| 21 |
+
SOFTWARE.
|
README.md
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
[Hugging Face Spaces](https://huggingface.co/spaces/abhishek/first-order-motion-model)
|
| 8 |
+
|
| 9 |
+
## Example animations
|
| 10 |
+
|
| 11 |
+
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.
|
| 12 |
+
|
| 13 |
+
### VoxCeleb Dataset
|
| 14 |
+

|
| 15 |
+
### Fashion Dataset
|
| 16 |
+

|
| 17 |
+
### MGIF Dataset
|
| 18 |
+

|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
### Installation
|
| 22 |
+
|
| 23 |
+
We support ```python3```. To install the dependencies run:
|
| 24 |
+
```
|
| 25 |
+
pip install -r requirements.txt
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
### YAML configs
|
| 29 |
+
|
| 30 |
+
There are several configuration (```config/dataset_name.yaml```) files one for each `dataset`. See ```config/taichi-256.yaml``` to get description of each parameter.
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
### Pre-trained checkpoint
|
| 34 |
+
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).
|
| 35 |
+
|
| 36 |
+
### Animation Demo
|
| 37 |
+
To run a demo, download checkpoint and run the following command:
|
| 38 |
+
```
|
| 39 |
+
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
|
| 40 |
+
```
|
| 41 |
+
The result will be stored in ```result.mp4```.
|
| 42 |
+
|
| 43 |
+
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:
|
| 44 |
+
```
|
| 45 |
+
git clone https://github.com/1adrianb/face-alignment
|
| 46 |
+
cd face-alignment
|
| 47 |
+
pip install -r requirements.txt
|
| 48 |
+
python setup.py install
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
### Animation demo with Docker
|
| 52 |
+
|
| 53 |
+
If you are having trouble getting the demo to work because of library compatibility issues,
|
| 54 |
+
and you're running Linux, you might try running it inside a Docker container, which would
|
| 55 |
+
give you better control over the execution environment.
|
| 56 |
+
|
| 57 |
+
Requirements: Docker 19.03+ and [nvidia-docker](https://github.com/NVIDIA/nvidia-docker)
|
| 58 |
+
installed and able to successfully run the `nvidia-docker` usage tests.
|
| 59 |
+
|
| 60 |
+
We'll first build the container.
|
| 61 |
+
|
| 62 |
+
```
|
| 63 |
+
docker build -t first-order-model .
|
| 64 |
+
```
|
| 65 |
+
|
| 66 |
+
And now that we have the container available locally, we can use it to run the demo.
|
| 67 |
+
|
| 68 |
+
```
|
| 69 |
+
docker run -it --rm --gpus all \
|
| 70 |
+
-v $HOME/first-order-model:/app first-order-model \
|
| 71 |
+
python3 demo.py --config config/vox-256.yaml \
|
| 72 |
+
--driving_video driving.mp4 \
|
| 73 |
+
--source_image source.png \
|
| 74 |
+
--checkpoint vox-cpk.pth.tar \
|
| 75 |
+
--result_video result.mp4 \
|
| 76 |
+
--relative --adapt_scale
|
| 77 |
+
```
|
| 78 |
+
|
| 79 |
+
### Colab Demo
|
| 80 |
+
|
| 81 |
+
[](https://colab.research.google.com/github/AliaksandrSiarohin/first-order-model/blob/master/demo.ipynb) [](https://kaggle.com/kernels/welcome?src=https://github.com/AliaksandrSiarohin/first-order-model/blob/master/demo.ipynb)
|
| 82 |
+
|
| 83 |
+
@graphemecluster prepared a GUI demo for the Google Colab. It also works in Kaggle. For the source code, see [```demo.ipynb```](https://github.com/AliaksandrSiarohin/first-order-model/blob/master/demo.ipynb).
|
| 84 |
+
|
| 85 |
+
For the old demo, see [```old_demo.ipynb```](https://github.com/AliaksandrSiarohin/first-order-model/blob/master/old_demo.ipynb).
|
| 86 |
+
|
| 87 |
+
### Face-swap
|
| 88 |
+
It is possible to modify the method to perform face-swap using supervised segmentation masks.
|
| 89 |
+

|
| 90 |
+
For both unsupervised and supervised video editing, such as face-swap, please refer to [Motion Co-Segmentation](https://github.com/AliaksandrSiarohin/motion-cosegmentation).
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
### Training
|
| 94 |
+
|
| 95 |
+
To train a model on specific dataset run:
|
| 96 |
+
```
|
| 97 |
+
CUDA_VISIBLE_DEVICES=0,1,2,3 python run.py --config config/dataset_name.yaml --device_ids 0,1,2,3
|
| 98 |
+
```
|
| 99 |
+
The code will create a folder in the log directory (each run will create a time-stamped new directory).
|
| 100 |
+
Checkpoints will be saved to this folder.
|
| 101 |
+
To check the loss values during training see ```log.txt```.
|
| 102 |
+
You can also check training data reconstructions in the ```train-vis``` subfolder.
|
| 103 |
+
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.
|
| 104 |
+
|
| 105 |
+
### Evaluation on video reconstruction
|
| 106 |
+
|
| 107 |
+
To evaluate the reconstruction performance run:
|
| 108 |
+
```
|
| 109 |
+
CUDA_VISIBLE_DEVICES=0 python run.py --config config/dataset_name.yaml --mode reconstruction --checkpoint path/to/checkpoint
|
| 110 |
+
```
|
| 111 |
+
You will need to specify the path to the checkpoint,
|
| 112 |
+
the ```reconstruction``` subfolder will be created in the checkpoint folder.
|
| 113 |
+
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.
|
| 114 |
+
Instructions for computing metrics from the paper can be found: https://github.com/AliaksandrSiarohin/pose-evaluation.
|
| 115 |
+
|
| 116 |
+
### Image animation
|
| 117 |
+
|
| 118 |
+
In order to animate videos run:
|
| 119 |
+
```
|
| 120 |
+
CUDA_VISIBLE_DEVICES=0 python run.py --config config/dataset_name.yaml --mode animate --checkpoint path/to/checkpoint
|
| 121 |
+
```
|
| 122 |
+
You will need to specify the path to the checkpoint,
|
| 123 |
+
the ```animation``` subfolder will be created in the same folder as the checkpoint.
|
| 124 |
+
You can find the generated video there and its loss-less version in the ```png``` subfolder.
|
| 125 |
+
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.
|
| 126 |
+
|
| 127 |
+
There are 2 different ways of performing animation:
|
| 128 |
+
by using **absolute** keypoint locations or by using **relative** keypoint locations.
|
| 129 |
+
|
| 130 |
+
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.
|
| 131 |
+
In this way there are no specific requirements for the driving video and source appearance that is used.
|
| 132 |
+
However this usually leads to poor performance since unrelevant details such as shape is transfered.
|
| 133 |
+
Check animate parameters in ```taichi-256.yaml``` to enable this mode.
|
| 134 |
+
|
| 135 |
+
<img src="sup-mat/absolute-demo.gif" width="512">
|
| 136 |
+
|
| 137 |
+
2) <i>Animation using relative coordinates:</i> from the driving video we first estimate the relative movement of each keypoint,
|
| 138 |
+
then we add this movement to the absolute position of keypoints in the source image.
|
| 139 |
+
This keypoint along with source image is used for animation. This usually leads to better performance, however this requires
|
| 140 |
+
that the object in the first frame of the video and in the source image have the same pose
|
| 141 |
+
|
| 142 |
+
<img src="sup-mat/relative-demo.gif" width="512">
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
### Datasets
|
| 146 |
+
|
| 147 |
+
1) **Bair**. This dataset can be directly [downloaded](https://yadi.sk/d/Rr-fjn-PdmmqeA).
|
| 148 |
+
|
| 149 |
+
2) **Mgif**. This dataset can be directly [downloaded](https://yadi.sk/d/5VdqLARizmnj3Q).
|
| 150 |
+
|
| 151 |
+
3) **Fashion**. Follow the instruction on dataset downloading [from](https://vision.cs.ubc.ca/datasets/fashion/).
|
| 152 |
+
|
| 153 |
+
4) **Taichi**. Follow the instructions in [data/taichi-loading](data/taichi-loading/README.md) or instructions from https://github.com/AliaksandrSiarohin/video-preprocessing.
|
| 154 |
+
|
| 155 |
+
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.
|
| 156 |
+
|
| 157 |
+
6) **VoxCeleb**. Please follow the instruction from https://github.com/AliaksandrSiarohin/video-preprocessing.
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
### Training on your own dataset
|
| 161 |
+
1) Resize all the videos to the same size e.g 256x256, the videos can be in '.gif', '.mp4' or folder with images.
|
| 162 |
+
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.
|
| 163 |
+
|
| 164 |
+
2) Create a folder ```data/dataset_name``` with 2 subfolders ```train``` and ```test```, put training videos in the ```train``` and testing in the ```test```.
|
| 165 |
+
|
| 166 |
+
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.
|
| 167 |
+
|
| 168 |
+
#### Additional notes
|
| 169 |
+
|
| 170 |
+
Citation:
|
| 171 |
+
|
| 172 |
+
```
|
| 173 |
+
@InProceedings{Siarohin_2019_NeurIPS,
|
| 174 |
+
author={Siarohin, Aliaksandr and Lathuilière, Stéphane and Tulyakov, Sergey and Ricci, Elisa and Sebe, Nicu},
|
| 175 |
+
title={First Order Motion Model for Image Animation},
|
| 176 |
+
booktitle = {Conference on Neural Information Processing Systems (NeurIPS)},
|
| 177 |
+
month = {December},
|
| 178 |
+
year = {2019}
|
| 179 |
+
}
|
| 180 |
+
```
|
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
|
@@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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 numpy 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,543 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
"%%capture\n",
|
| 44 |
+
"%pip install ffmpeg-python imageio-ffmpeg\n",
|
| 45 |
+
"!git init .\n",
|
| 46 |
+
"!git remote add origin https://github.com/AliaksandrSiarohin/first-order-model\n",
|
| 47 |
+
"!git pull origin master\n",
|
| 48 |
+
"!git clone https://github.com/graphemecluster/first-order-model-demo demo"
|
| 49 |
+
],
|
| 50 |
+
"execution_count": null,
|
| 51 |
+
"outputs": []
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"cell_type": "code",
|
| 55 |
+
"metadata": {
|
| 56 |
+
"id": "Oxi6-riLOgnm"
|
| 57 |
+
},
|
| 58 |
+
"source": [
|
| 59 |
+
"import IPython.display\n",
|
| 60 |
+
"import PIL.Image\n",
|
| 61 |
+
"import cv2\n",
|
| 62 |
+
"import ffmpeg\n",
|
| 63 |
+
"import imageio\n",
|
| 64 |
+
"import io\n",
|
| 65 |
+
"import ipywidgets\n",
|
| 66 |
+
"import numpy\n",
|
| 67 |
+
"import os.path\n",
|
| 68 |
+
"import requests\n",
|
| 69 |
+
"import skimage.transform\n",
|
| 70 |
+
"import warnings\n",
|
| 71 |
+
"from base64 import b64encode\n",
|
| 72 |
+
"from demo import load_checkpoints, make_animation # type: ignore (local file)\n",
|
| 73 |
+
"from google.colab import files, output\n",
|
| 74 |
+
"from IPython.display import HTML, Javascript\n",
|
| 75 |
+
"from shutil import copyfileobj\n",
|
| 76 |
+
"from skimage import img_as_ubyte\n",
|
| 77 |
+
"from tempfile import NamedTemporaryFile\n",
|
| 78 |
+
"from tqdm.auto import tqdm\n",
|
| 79 |
+
"warnings.filterwarnings(\"ignore\")\n",
|
| 80 |
+
"os.makedirs(\"user\", exist_ok=True)\n",
|
| 81 |
+
"\n",
|
| 82 |
+
"display(HTML(\"\"\"\n",
|
| 83 |
+
"<style>\n",
|
| 84 |
+
".widget-box > * {\n",
|
| 85 |
+
"\tflex-shrink: 0;\n",
|
| 86 |
+
"}\n",
|
| 87 |
+
".widget-tab {\n",
|
| 88 |
+
"\tmin-width: 0;\n",
|
| 89 |
+
"\tflex: 1 1 auto;\n",
|
| 90 |
+
"}\n",
|
| 91 |
+
".widget-tab .p-TabBar-tabLabel {\n",
|
| 92 |
+
"\tfont-size: 15px;\n",
|
| 93 |
+
"}\n",
|
| 94 |
+
".widget-upload {\n",
|
| 95 |
+
"\tbackground-color: tan;\n",
|
| 96 |
+
"}\n",
|
| 97 |
+
".widget-button {\n",
|
| 98 |
+
"\tfont-size: 18px;\n",
|
| 99 |
+
"\twidth: 160px;\n",
|
| 100 |
+
"\theight: 34px;\n",
|
| 101 |
+
"\tline-height: 34px;\n",
|
| 102 |
+
"}\n",
|
| 103 |
+
".widget-dropdown {\n",
|
| 104 |
+
"\twidth: 250px;\n",
|
| 105 |
+
"}\n",
|
| 106 |
+
".widget-checkbox {\n",
|
| 107 |
+
"\twidth: 650px;\n",
|
| 108 |
+
"}\n",
|
| 109 |
+
".widget-checkbox + .widget-checkbox {\n",
|
| 110 |
+
"\tmargin-top: -6px;\n",
|
| 111 |
+
"}\n",
|
| 112 |
+
".input-widget .output_html {\n",
|
| 113 |
+
"\ttext-align: center;\n",
|
| 114 |
+
"\twidth: 266px;\n",
|
| 115 |
+
"\theight: 266px;\n",
|
| 116 |
+
"\tline-height: 266px;\n",
|
| 117 |
+
"\tcolor: lightgray;\n",
|
| 118 |
+
"\tfont-size: 72px;\n",
|
| 119 |
+
"}\n",
|
| 120 |
+
".title {\n",
|
| 121 |
+
"\tfont-size: 20px;\n",
|
| 122 |
+
"\tfont-weight: bold;\n",
|
| 123 |
+
"\tmargin: 12px 0 6px 0;\n",
|
| 124 |
+
"}\n",
|
| 125 |
+
".warning {\n",
|
| 126 |
+
"\tdisplay: none;\n",
|
| 127 |
+
"\tcolor: red;\n",
|
| 128 |
+
"\tmargin-left: 10px;\n",
|
| 129 |
+
"}\n",
|
| 130 |
+
".warn {\n",
|
| 131 |
+
"\tdisplay: initial;\n",
|
| 132 |
+
"}\n",
|
| 133 |
+
".resource {\n",
|
| 134 |
+
"\tcursor: pointer;\n",
|
| 135 |
+
"\tborder: 1px solid gray;\n",
|
| 136 |
+
"\tmargin: 5px;\n",
|
| 137 |
+
"\twidth: 160px;\n",
|
| 138 |
+
"\theight: 160px;\n",
|
| 139 |
+
"\tmin-width: 160px;\n",
|
| 140 |
+
"\tmin-height: 160px;\n",
|
| 141 |
+
"\tmax-width: 160px;\n",
|
| 142 |
+
"\tmax-height: 160px;\n",
|
| 143 |
+
"\t-webkit-box-sizing: initial;\n",
|
| 144 |
+
"\tbox-sizing: initial;\n",
|
| 145 |
+
"}\n",
|
| 146 |
+
".resource:hover {\n",
|
| 147 |
+
"\tborder: 6px solid crimson;\n",
|
| 148 |
+
"\tmargin: 0;\n",
|
| 149 |
+
"}\n",
|
| 150 |
+
".selected {\n",
|
| 151 |
+
"\tborder: 6px solid seagreen;\n",
|
| 152 |
+
"\tmargin: 0;\n",
|
| 153 |
+
"}\n",
|
| 154 |
+
".input-widget {\n",
|
| 155 |
+
"\twidth: 266px;\n",
|
| 156 |
+
"\theight: 266px;\n",
|
| 157 |
+
"\tborder: 1px solid gray;\n",
|
| 158 |
+
"}\n",
|
| 159 |
+
".input-button {\n",
|
| 160 |
+
"\twidth: 268px;\n",
|
| 161 |
+
"\tfont-size: 15px;\n",
|
| 162 |
+
"\tmargin: 2px 0 0;\n",
|
| 163 |
+
"}\n",
|
| 164 |
+
".output-widget {\n",
|
| 165 |
+
"\twidth: 256px;\n",
|
| 166 |
+
"\theight: 256px;\n",
|
| 167 |
+
"\tborder: 1px solid gray;\n",
|
| 168 |
+
"}\n",
|
| 169 |
+
".output-button {\n",
|
| 170 |
+
"\twidth: 258px;\n",
|
| 171 |
+
"\tfont-size: 15px;\n",
|
| 172 |
+
"\tmargin: 2px 0 0;\n",
|
| 173 |
+
"}\n",
|
| 174 |
+
".uploaded {\n",
|
| 175 |
+
"\twidth: 256px;\n",
|
| 176 |
+
"\theight: 256px;\n",
|
| 177 |
+
"\tborder: 6px solid seagreen;\n",
|
| 178 |
+
"\tmargin: 0;\n",
|
| 179 |
+
"}\n",
|
| 180 |
+
".label-or {\n",
|
| 181 |
+
"\talign-self: center;\n",
|
| 182 |
+
"\tfont-size: 20px;\n",
|
| 183 |
+
"\tmargin: 16px;\n",
|
| 184 |
+
"}\n",
|
| 185 |
+
".loading {\n",
|
| 186 |
+
"\talign-items: center;\n",
|
| 187 |
+
"\twidth: fit-content;\n",
|
| 188 |
+
"}\n",
|
| 189 |
+
".loader {\n",
|
| 190 |
+
"\tmargin: 32px 0 16px 0;\n",
|
| 191 |
+
"\twidth: 48px;\n",
|
| 192 |
+
"\theight: 48px;\n",
|
| 193 |
+
"\tmin-width: 48px;\n",
|
| 194 |
+
"\tmin-height: 48px;\n",
|
| 195 |
+
"\tmax-width: 48px;\n",
|
| 196 |
+
"\tmax-height: 48px;\n",
|
| 197 |
+
"\tborder: 4px solid whitesmoke;\n",
|
| 198 |
+
"\tborder-top-color: gray;\n",
|
| 199 |
+
"\tborder-radius: 50%;\n",
|
| 200 |
+
"\tanimation: spin 1.8s linear infinite;\n",
|
| 201 |
+
"}\n",
|
| 202 |
+
".loading-label {\n",
|
| 203 |
+
"\tcolor: gray;\n",
|
| 204 |
+
"}\n",
|
| 205 |
+
".video {\n",
|
| 206 |
+
"\tmargin: 0;\n",
|
| 207 |
+
"}\n",
|
| 208 |
+
".comparison-widget {\n",
|
| 209 |
+
"\twidth: 256px;\n",
|
| 210 |
+
"\theight: 256px;\n",
|
| 211 |
+
"\tborder: 1px solid gray;\n",
|
| 212 |
+
"\tmargin-left: 2px;\n",
|
| 213 |
+
"}\n",
|
| 214 |
+
".comparison-label {\n",
|
| 215 |
+
"\tcolor: gray;\n",
|
| 216 |
+
"\tfont-size: 14px;\n",
|
| 217 |
+
"\ttext-align: center;\n",
|
| 218 |
+
"\tposition: relative;\n",
|
| 219 |
+
"\tbottom: 3px;\n",
|
| 220 |
+
"}\n",
|
| 221 |
+
"@keyframes spin {\n",
|
| 222 |
+
"\tfrom { transform: rotate(0deg); }\n",
|
| 223 |
+
"\tto { transform: rotate(360deg); }\n",
|
| 224 |
+
"}\n",
|
| 225 |
+
"</style>\n",
|
| 226 |
+
"\"\"\"))\n",
|
| 227 |
+
"\n",
|
| 228 |
+
"def thumbnail(file):\n",
|
| 229 |
+
"\treturn imageio.get_reader(file, mode='I', format='FFMPEG').get_next_data()\n",
|
| 230 |
+
"\n",
|
| 231 |
+
"def create_image(i, j):\n",
|
| 232 |
+
"\timage_widget = ipywidgets.Image.from_file('demo/images/%d%d.png' % (i, j))\n",
|
| 233 |
+
"\timage_widget.add_class('resource')\n",
|
| 234 |
+
"\timage_widget.add_class('resource-image')\n",
|
| 235 |
+
"\timage_widget.add_class('resource-image%d%d' % (i, j))\n",
|
| 236 |
+
"\treturn image_widget\n",
|
| 237 |
+
"\n",
|
| 238 |
+
"def create_video(i):\n",
|
| 239 |
+
"\tvideo_widget = ipywidgets.Image(\n",
|
| 240 |
+
"\t\tvalue=cv2.imencode('.png', cv2.cvtColor(thumbnail('demo/videos/%d.mp4' % i), cv2.COLOR_RGB2BGR))[1].tostring(),\n",
|
| 241 |
+
"\t\tformat='png'\n",
|
| 242 |
+
"\t)\n",
|
| 243 |
+
"\tvideo_widget.add_class('resource')\n",
|
| 244 |
+
"\tvideo_widget.add_class('resource-video')\n",
|
| 245 |
+
"\tvideo_widget.add_class('resource-video%d' % i)\n",
|
| 246 |
+
"\treturn video_widget\n",
|
| 247 |
+
"\n",
|
| 248 |
+
"def create_title(title):\n",
|
| 249 |
+
"\ttitle_widget = ipywidgets.Label(title)\n",
|
| 250 |
+
"\ttitle_widget.add_class('title')\n",
|
| 251 |
+
"\treturn title_widget\n",
|
| 252 |
+
"\n",
|
| 253 |
+
"def download_output(button):\n",
|
| 254 |
+
"\tcomplete.layout.display = 'none'\n",
|
| 255 |
+
"\tloading.layout.display = ''\n",
|
| 256 |
+
"\tfiles.download('output.mp4')\n",
|
| 257 |
+
"\tloading.layout.display = 'none'\n",
|
| 258 |
+
"\tcomplete.layout.display = ''\n",
|
| 259 |
+
"\n",
|
| 260 |
+
"def convert_output(button):\n",
|
| 261 |
+
"\tcomplete.layout.display = 'none'\n",
|
| 262 |
+
"\tloading.layout.display = ''\n",
|
| 263 |
+
"\tffmpeg.input('output.mp4').output('scaled.mp4', vf='scale=1080x1080:flags=lanczos,pad=1920:1080:420:0').overwrite_output().run()\n",
|
| 264 |
+
"\tfiles.download('scaled.mp4')\n",
|
| 265 |
+
"\tloading.layout.display = 'none'\n",
|
| 266 |
+
"\tcomplete.layout.display = ''\n",
|
| 267 |
+
"\n",
|
| 268 |
+
"def back_to_main(button):\n",
|
| 269 |
+
"\tcomplete.layout.display = 'none'\n",
|
| 270 |
+
"\tmain.layout.display = ''\n",
|
| 271 |
+
"\n",
|
| 272 |
+
"label_or = ipywidgets.Label('or')\n",
|
| 273 |
+
"label_or.add_class('label-or')\n",
|
| 274 |
+
"\n",
|
| 275 |
+
"image_titles = ['Peoples', 'Cartoons', 'Dolls', 'Game of Thrones', 'Statues']\n",
|
| 276 |
+
"image_lengths = [8, 4, 8, 9, 4]\n",
|
| 277 |
+
"\n",
|
| 278 |
+
"image_tab = ipywidgets.Tab()\n",
|
| 279 |
+
"image_tab.children = [ipywidgets.HBox([create_image(i, j) for j in range(length)]) for i, length in enumerate(image_lengths)]\n",
|
| 280 |
+
"for i, title in enumerate(image_titles):\n",
|
| 281 |
+
"\timage_tab.set_title(i, title)\n",
|
| 282 |
+
"\n",
|
| 283 |
+
"input_image_widget = ipywidgets.Output()\n",
|
| 284 |
+
"input_image_widget.add_class('input-widget')\n",
|
| 285 |
+
"upload_input_image_button = ipywidgets.FileUpload(accept='image/*', button_style='primary')\n",
|
| 286 |
+
"upload_input_image_button.add_class('input-button')\n",
|
| 287 |
+
"image_part = ipywidgets.HBox([\n",
|
| 288 |
+
"\tipywidgets.VBox([input_image_widget, upload_input_image_button]),\n",
|
| 289 |
+
"\tlabel_or,\n",
|
| 290 |
+
"\timage_tab\n",
|
| 291 |
+
"])\n",
|
| 292 |
+
"\n",
|
| 293 |
+
"video_tab = ipywidgets.Tab()\n",
|
| 294 |
+
"video_tab.children = [ipywidgets.HBox([create_video(i) for i in range(5)])]\n",
|
| 295 |
+
"video_tab.set_title(0, 'All Videos')\n",
|
| 296 |
+
"\n",
|
| 297 |
+
"input_video_widget = ipywidgets.Output()\n",
|
| 298 |
+
"input_video_widget.add_class('input-widget')\n",
|
| 299 |
+
"upload_input_video_button = ipywidgets.FileUpload(accept='video/*', button_style='primary')\n",
|
| 300 |
+
"upload_input_video_button.add_class('input-button')\n",
|
| 301 |
+
"video_part = ipywidgets.HBox([\n",
|
| 302 |
+
"\tipywidgets.VBox([input_video_widget, upload_input_video_button]),\n",
|
| 303 |
+
"\tlabel_or,\n",
|
| 304 |
+
"\tvideo_tab\n",
|
| 305 |
+
"])\n",
|
| 306 |
+
"\n",
|
| 307 |
+
"model = ipywidgets.Dropdown(\n",
|
| 308 |
+
"\tdescription=\"Model:\",\n",
|
| 309 |
+
"\toptions=[\n",
|
| 310 |
+
"\t\t'vox',\n",
|
| 311 |
+
"\t\t'vox-adv',\n",
|
| 312 |
+
"\t\t'taichi',\n",
|
| 313 |
+
"\t\t'taichi-adv',\n",
|
| 314 |
+
"\t\t'nemo',\n",
|
| 315 |
+
"\t\t'mgif',\n",
|
| 316 |
+
"\t\t'fashion',\n",
|
| 317 |
+
"\t\t'bair'\n",
|
| 318 |
+
"\t]\n",
|
| 319 |
+
")\n",
|
| 320 |
+
"warning = ipywidgets.HTML('<b>Warning:</b> Upload your own images and videos (see README)')\n",
|
| 321 |
+
"warning.add_class('warning')\n",
|
| 322 |
+
"model_part = ipywidgets.HBox([model, warning])\n",
|
| 323 |
+
"\n",
|
| 324 |
+
"relative = ipywidgets.Checkbox(description=\"Relative keypoint displacement (Inherit object proporions from the video)\", value=True)\n",
|
| 325 |
+
"adapt_movement_scale = ipywidgets.Checkbox(description=\"Adapt movement scale (Don’t touch unless you know want you are doing)\", value=True)\n",
|
| 326 |
+
"generate_button = ipywidgets.Button(description=\"Generate\", button_style='primary')\n",
|
| 327 |
+
"main = ipywidgets.VBox([\n",
|
| 328 |
+
"\tcreate_title('Choose Image'),\n",
|
| 329 |
+
"\timage_part,\n",
|
| 330 |
+
"\tcreate_title('Choose Video'),\n",
|
| 331 |
+
"\tvideo_part,\n",
|
| 332 |
+
"\tcreate_title('Settings'),\n",
|
| 333 |
+
"\tmodel_part,\n",
|
| 334 |
+
"\trelative,\n",
|
| 335 |
+
"\tadapt_movement_scale,\n",
|
| 336 |
+
"\tgenerate_button\n",
|
| 337 |
+
"])\n",
|
| 338 |
+
"\n",
|
| 339 |
+
"loader = ipywidgets.Label()\n",
|
| 340 |
+
"loader.add_class(\"loader\")\n",
|
| 341 |
+
"loading_label = ipywidgets.Label(\"This may take several minutes to process…\")\n",
|
| 342 |
+
"loading_label.add_class(\"loading-label\")\n",
|
| 343 |
+
"progress_bar = ipywidgets.Output()\n",
|
| 344 |
+
"loading = ipywidgets.VBox([loader, loading_label, progress_bar])\n",
|
| 345 |
+
"loading.add_class('loading')\n",
|
| 346 |
+
"\n",
|
| 347 |
+
"output_widget = ipywidgets.Output()\n",
|
| 348 |
+
"output_widget.add_class('output-widget')\n",
|
| 349 |
+
"download = ipywidgets.Button(description='Download', button_style='primary')\n",
|
| 350 |
+
"download.add_class('output-button')\n",
|
| 351 |
+
"download.on_click(download_output)\n",
|
| 352 |
+
"convert = ipywidgets.Button(description='Convert to 1920×1080', button_style='primary')\n",
|
| 353 |
+
"convert.add_class('output-button')\n",
|
| 354 |
+
"convert.on_click(convert_output)\n",
|
| 355 |
+
"back = ipywidgets.Button(description='Back', button_style='primary')\n",
|
| 356 |
+
"back.add_class('output-button')\n",
|
| 357 |
+
"back.on_click(back_to_main)\n",
|
| 358 |
+
"\n",
|
| 359 |
+
"comparison_widget = ipywidgets.Output()\n",
|
| 360 |
+
"comparison_widget.add_class('comparison-widget')\n",
|
| 361 |
+
"comparison_label = ipywidgets.Label('Comparison')\n",
|
| 362 |
+
"comparison_label.add_class('comparison-label')\n",
|
| 363 |
+
"complete = ipywidgets.HBox([\n",
|
| 364 |
+
"\tipywidgets.VBox([output_widget, download, convert, back]),\n",
|
| 365 |
+
"\tipywidgets.VBox([comparison_widget, comparison_label])\n",
|
| 366 |
+
"])\n",
|
| 367 |
+
"\n",
|
| 368 |
+
"display(ipywidgets.VBox([main, loading, complete]))\n",
|
| 369 |
+
"display(Javascript(\"\"\"\n",
|
| 370 |
+
"var images, videos;\n",
|
| 371 |
+
"function deselectImages() {\n",
|
| 372 |
+
"\timages.forEach(function(item) {\n",
|
| 373 |
+
"\t\titem.classList.remove(\"selected\");\n",
|
| 374 |
+
"\t});\n",
|
| 375 |
+
"}\n",
|
| 376 |
+
"function deselectVideos() {\n",
|
| 377 |
+
"\tvideos.forEach(function(item) {\n",
|
| 378 |
+
"\t\titem.classList.remove(\"selected\");\n",
|
| 379 |
+
"\t});\n",
|
| 380 |
+
"}\n",
|
| 381 |
+
"function invokePython(func) {\n",
|
| 382 |
+
"\tgoogle.colab.kernel.invokeFunction(\"notebook.\" + func, [].slice.call(arguments, 1), {});\n",
|
| 383 |
+
"}\n",
|
| 384 |
+
"setTimeout(function() {\n",
|
| 385 |
+
"\t(images = [].slice.call(document.getElementsByClassName(\"resource-image\"))).forEach(function(item) {\n",
|
| 386 |
+
"\t\titem.addEventListener(\"click\", function() {\n",
|
| 387 |
+
"\t\t\tdeselectImages();\n",
|
| 388 |
+
"\t\t\titem.classList.add(\"selected\");\n",
|
| 389 |
+
"\t\t\tinvokePython(\"select_image\", item.className.match(/resource-image(\\d\\d)/)[1]);\n",
|
| 390 |
+
"\t\t});\n",
|
| 391 |
+
"\t});\n",
|
| 392 |
+
"\timages[0].classList.add(\"selected\");\n",
|
| 393 |
+
"\t(videos = [].slice.call(document.getElementsByClassName(\"resource-video\"))).forEach(function(item) {\n",
|
| 394 |
+
"\t\titem.addEventListener(\"click\", function() {\n",
|
| 395 |
+
"\t\t\tdeselectVideos();\n",
|
| 396 |
+
"\t\t\titem.classList.add(\"selected\");\n",
|
| 397 |
+
"\t\t\tinvokePython(\"select_video\", item.className.match(/resource-video(\\d)/)[1]);\n",
|
| 398 |
+
"\t\t});\n",
|
| 399 |
+
"\t});\n",
|
| 400 |
+
"\tvideos[0].classList.add(\"selected\");\n",
|
| 401 |
+
"}, 1000);\n",
|
| 402 |
+
"\"\"\"))\n",
|
| 403 |
+
"\n",
|
| 404 |
+
"selected_image = None\n",
|
| 405 |
+
"def select_image(filename):\n",
|
| 406 |
+
"\tglobal selected_image\n",
|
| 407 |
+
"\tselected_image = resize(PIL.Image.open('demo/images/%s.png' % filename).convert(\"RGB\"))\n",
|
| 408 |
+
"\tinput_image_widget.clear_output(wait=True)\n",
|
| 409 |
+
"\twith input_image_widget:\n",
|
| 410 |
+
"\t\tdisplay(HTML('Image'))\n",
|
| 411 |
+
"\tinput_image_widget.remove_class('uploaded')\n",
|
| 412 |
+
"output.register_callback(\"notebook.select_image\", select_image)\n",
|
| 413 |
+
"\n",
|
| 414 |
+
"selected_video = None\n",
|
| 415 |
+
"def select_video(filename):\n",
|
| 416 |
+
"\tglobal selected_video\n",
|
| 417 |
+
"\tselected_video = 'demo/videos/%s.mp4' % filename\n",
|
| 418 |
+
"\tinput_video_widget.clear_output(wait=True)\n",
|
| 419 |
+
"\twith input_video_widget:\n",
|
| 420 |
+
"\t\tdisplay(HTML('Video'))\n",
|
| 421 |
+
"\tinput_video_widget.remove_class('uploaded')\n",
|
| 422 |
+
"output.register_callback(\"notebook.select_video\", select_video)\n",
|
| 423 |
+
"\n",
|
| 424 |
+
"def resize(image, size=(256, 256)):\n",
|
| 425 |
+
"\tw, h = image.size\n",
|
| 426 |
+
"\td = min(w, h)\n",
|
| 427 |
+
"\tr = ((w - d) // 2, (h - d) // 2, (w + d) // 2, (h + d) // 2)\n",
|
| 428 |
+
"\treturn image.resize(size, resample=PIL.Image.LANCZOS, box=r)\n",
|
| 429 |
+
"\n",
|
| 430 |
+
"def upload_image(change):\n",
|
| 431 |
+
"\tglobal selected_image\n",
|
| 432 |
+
"\tfor name, file_info in upload_input_image_button.value.items():\n",
|
| 433 |
+
"\t\tcontent = file_info['content']\n",
|
| 434 |
+
"\tif content is not None:\n",
|
| 435 |
+
"\t\tselected_image = resize(PIL.Image.open(io.BytesIO(content)).convert(\"RGB\"))\n",
|
| 436 |
+
"\t\tinput_image_widget.clear_output(wait=True)\n",
|
| 437 |
+
"\t\twith input_image_widget:\n",
|
| 438 |
+
"\t\t\tdisplay(selected_image)\n",
|
| 439 |
+
"\t\tinput_image_widget.add_class('uploaded')\n",
|
| 440 |
+
"\t\tdisplay(Javascript('deselectImages()'))\n",
|
| 441 |
+
"upload_input_image_button.observe(upload_image, names='value')\n",
|
| 442 |
+
"\n",
|
| 443 |
+
"def upload_video(change):\n",
|
| 444 |
+
"\tglobal selected_video\n",
|
| 445 |
+
"\tfor name, file_info in upload_input_video_button.value.items():\n",
|
| 446 |
+
"\t\tcontent = file_info['content']\n",
|
| 447 |
+
"\tif content is not None:\n",
|
| 448 |
+
"\t\tselected_video = 'user/' + name\n",
|
| 449 |
+
"\t\twith open(selected_video, 'wb') as video:\n",
|
| 450 |
+
"\t\t\tvideo.write(content)\n",
|
| 451 |
+
"\t\tpreview = resize(PIL.Image.fromarray(thumbnail(selected_video)).convert(\"RGB\"))\n",
|
| 452 |
+
"\t\tinput_video_widget.clear_output(wait=True)\n",
|
| 453 |
+
"\t\twith input_video_widget:\n",
|
| 454 |
+
"\t\t\tdisplay(preview)\n",
|
| 455 |
+
"\t\tinput_video_widget.add_class('uploaded')\n",
|
| 456 |
+
"\t\tdisplay(Javascript('deselectVideos()'))\n",
|
| 457 |
+
"upload_input_video_button.observe(upload_video, names='value')\n",
|
| 458 |
+
"\n",
|
| 459 |
+
"def change_model(change):\n",
|
| 460 |
+
"\tif model.value.startswith('vox'):\n",
|
| 461 |
+
"\t\twarning.remove_class('warn')\n",
|
| 462 |
+
"\telse:\n",
|
| 463 |
+
"\t\twarning.add_class('warn')\n",
|
| 464 |
+
"model.observe(change_model, names='value')\n",
|
| 465 |
+
"\n",
|
| 466 |
+
"def generate(button):\n",
|
| 467 |
+
"\tmain.layout.display = 'none'\n",
|
| 468 |
+
"\tloading.layout.display = ''\n",
|
| 469 |
+
"\tfilename = model.value + ('' if model.value == 'fashion' else '-cpk') + '.pth.tar'\n",
|
| 470 |
+
"\tif not os.path.isfile(filename):\n",
|
| 471 |
+
"\t\tresponse = requests.get('https://github.com/graphemecluster/first-order-model-demo/releases/download/checkpoints/' + filename, stream=True)\n",
|
| 472 |
+
"\t\twith progress_bar:\n",
|
| 473 |
+
"\t\t\twith tqdm.wrapattr(response.raw, 'read', total=int(response.headers.get('Content-Length', 0)), unit='B', unit_scale=True, unit_divisor=1024) as raw:\n",
|
| 474 |
+
"\t\t\t\twith open(filename, 'wb') as file:\n",
|
| 475 |
+
"\t\t\t\t\tcopyfileobj(raw, file)\n",
|
| 476 |
+
"\t\tprogress_bar.clear_output()\n",
|
| 477 |
+
"\treader = imageio.get_reader(selected_video, mode='I', format='FFMPEG')\n",
|
| 478 |
+
"\tfps = reader.get_meta_data()['fps']\n",
|
| 479 |
+
"\tdriving_video = []\n",
|
| 480 |
+
"\tfor frame in reader:\n",
|
| 481 |
+
"\t\tdriving_video.append(frame)\n",
|
| 482 |
+
"\tgenerator, kp_detector = load_checkpoints(config_path='config/%s-256.yaml' % model.value, checkpoint_path=filename)\n",
|
| 483 |
+
"\twith progress_bar:\n",
|
| 484 |
+
"\t\tpredictions = make_animation(\n",
|
| 485 |
+
"\t\t\tskimage.transform.resize(numpy.asarray(selected_image), (256, 256)),\n",
|
| 486 |
+
"\t\t\t[skimage.transform.resize(frame, (256, 256)) for frame in driving_video],\n",
|
| 487 |
+
"\t\t\tgenerator,\n",
|
| 488 |
+
"\t\t\tkp_detector,\n",
|
| 489 |
+
"\t\t\trelative=relative.value,\n",
|
| 490 |
+
"\t\t\tadapt_movement_scale=adapt_movement_scale.value\n",
|
| 491 |
+
"\t\t)\n",
|
| 492 |
+
"\tprogress_bar.clear_output()\n",
|
| 493 |
+
"\timageio.mimsave('output.mp4', [img_as_ubyte(frame) for frame in predictions], fps=fps)\n",
|
| 494 |
+
"\ttry:\n",
|
| 495 |
+
"\t\twith NamedTemporaryFile(suffix='.mp4') as output:\n",
|
| 496 |
+
"\t\t\tffmpeg.output(ffmpeg.input('output.mp4').video, ffmpeg.input(selected_video).audio, output.name, c='copy').run()\n",
|
| 497 |
+
"\t\t\twith open('output.mp4', 'wb') as result:\n",
|
| 498 |
+
"\t\t\t\tcopyfileobj(output, result)\n",
|
| 499 |
+
"\texcept ffmpeg.Error:\n",
|
| 500 |
+
"\t\tpass\n",
|
| 501 |
+
"\toutput_widget.clear_output(True)\n",
|
| 502 |
+
"\twith output_widget:\n",
|
| 503 |
+
"\t\tvideo_widget = ipywidgets.Video.from_file('output.mp4', autoplay=False, loop=False)\n",
|
| 504 |
+
"\t\tvideo_widget.add_class('video')\n",
|
| 505 |
+
"\t\tvideo_widget.add_class('video-left')\n",
|
| 506 |
+
"\t\tdisplay(video_widget)\n",
|
| 507 |
+
"\tcomparison_widget.clear_output(True)\n",
|
| 508 |
+
"\twith comparison_widget:\n",
|
| 509 |
+
"\t\tvideo_widget = ipywidgets.Video.from_file(selected_video, autoplay=False, loop=False, controls=False)\n",
|
| 510 |
+
"\t\tvideo_widget.add_class('video')\n",
|
| 511 |
+
"\t\tvideo_widget.add_class('video-right')\n",
|
| 512 |
+
"\t\tdisplay(video_widget)\n",
|
| 513 |
+
"\tdisplay(Javascript(\"\"\"\n",
|
| 514 |
+
"\tsetTimeout(function() {\n",
|
| 515 |
+
"\t\t(function(left, right) {\n",
|
| 516 |
+
"\t\t\tleft.addEventListener(\"play\", function() {\n",
|
| 517 |
+
"\t\t\t\tright.play();\n",
|
| 518 |
+
"\t\t\t});\n",
|
| 519 |
+
"\t\t\tleft.addEventListener(\"pause\", function() {\n",
|
| 520 |
+
"\t\t\t\tright.pause();\n",
|
| 521 |
+
"\t\t\t});\n",
|
| 522 |
+
"\t\t\tleft.addEventListener(\"seeking\", function() {\n",
|
| 523 |
+
"\t\t\t\tright.currentTime = left.currentTime;\n",
|
| 524 |
+
"\t\t\t});\n",
|
| 525 |
+
"\t\t\tright.muted = true;\n",
|
| 526 |
+
"\t\t})(document.getElementsByClassName(\"video-left\")[0], document.getElementsByClassName(\"video-right\")[0]);\n",
|
| 527 |
+
"\t}, 1000);\n",
|
| 528 |
+
"\t\"\"\"))\n",
|
| 529 |
+
"\tloading.layout.display = 'none'\n",
|
| 530 |
+
"\tcomplete.layout.display = ''\n",
|
| 531 |
+
"\n",
|
| 532 |
+
"generate_button.on_click(generate)\n",
|
| 533 |
+
"\n",
|
| 534 |
+
"loading.layout.display = 'none'\n",
|
| 535 |
+
"complete.layout.display =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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
import yaml
|
| 3 |
+
from argparse import ArgumentParser
|
| 4 |
+
from tqdm.auto import tqdm
|
| 5 |
+
|
| 6 |
+
import imageio
|
| 7 |
+
import numpy as np
|
| 8 |
+
from skimage.transform import resize
|
| 9 |
+
from skimage import img_as_ubyte
|
| 10 |
+
import torch
|
| 11 |
+
from sync_batchnorm import DataParallelWithCallback
|
| 12 |
+
|
| 13 |
+
from modules.generator import OcclusionAwareGenerator
|
| 14 |
+
from modules.keypoint_detector import KPDetector
|
| 15 |
+
from animate import normalize_kp
|
| 16 |
+
|
| 17 |
+
import ffmpeg
|
| 18 |
+
from os.path import splitext
|
| 19 |
+
from shutil import copyfileobj
|
| 20 |
+
from tempfile import NamedTemporaryFile
|
| 21 |
+
|
| 22 |
+
if sys.version_info[0] < 3:
|
| 23 |
+
raise Exception("You must use Python 3 or higher. Recommended version is Python 3.7")
|
| 24 |
+
|
| 25 |
+
def load_checkpoints(config_path, checkpoint_path, cpu=False):
|
| 26 |
+
|
| 27 |
+
with open(config_path) as f:
|
| 28 |
+
config = yaml.full_load(f)
|
| 29 |
+
|
| 30 |
+
generator = OcclusionAwareGenerator(**config['model_params']['generator_params'],
|
| 31 |
+
**config['model_params']['common_params'])
|
| 32 |
+
if not cpu:
|
| 33 |
+
generator.cuda()
|
| 34 |
+
|
| 35 |
+
kp_detector = KPDetector(**config['model_params']['kp_detector_params'],
|
| 36 |
+
**config['model_params']['common_params'])
|
| 37 |
+
if not cpu:
|
| 38 |
+
kp_detector.cuda()
|
| 39 |
+
|
| 40 |
+
if cpu:
|
| 41 |
+
checkpoint = torch.load(checkpoint_path, map_location=torch.device('cpu'))
|
| 42 |
+
else:
|
| 43 |
+
checkpoint = torch.load(checkpoint_path)
|
| 44 |
+
|
| 45 |
+
generator.load_state_dict(checkpoint['generator'])
|
| 46 |
+
kp_detector.load_state_dict(checkpoint['kp_detector'])
|
| 47 |
+
|
| 48 |
+
if not cpu:
|
| 49 |
+
generator = DataParallelWithCallback(generator)
|
| 50 |
+
kp_detector = DataParallelWithCallback(kp_detector)
|
| 51 |
+
|
| 52 |
+
generator.eval()
|
| 53 |
+
kp_detector.eval()
|
| 54 |
+
|
| 55 |
+
return generator, kp_detector
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def make_animation(source_image, driving_video, generator, kp_detector, relative=True, adapt_movement_scale=True, cpu=False):
|
| 59 |
+
with torch.no_grad():
|
| 60 |
+
predictions = []
|
| 61 |
+
source = torch.tensor(source_image[np.newaxis].astype(np.float32)).permute(0, 3, 1, 2)
|
| 62 |
+
if not cpu:
|
| 63 |
+
source = source.cuda()
|
| 64 |
+
driving = torch.tensor(np.array(driving_video)[np.newaxis].astype(np.float32)).permute(0, 4, 1, 2, 3)
|
| 65 |
+
kp_source = kp_detector(source)
|
| 66 |
+
kp_driving_initial = kp_detector(driving[:, :, 0])
|
| 67 |
+
|
| 68 |
+
for frame_idx in tqdm(range(driving.shape[2])):
|
| 69 |
+
driving_frame = driving[:, :, frame_idx]
|
| 70 |
+
if not cpu:
|
| 71 |
+
driving_frame = driving_frame.cuda()
|
| 72 |
+
kp_driving = kp_detector(driving_frame)
|
| 73 |
+
kp_norm = normalize_kp(kp_source=kp_source, kp_driving=kp_driving,
|
| 74 |
+
kp_driving_initial=kp_driving_initial, use_relative_movement=relative,
|
| 75 |
+
use_relative_jacobian=relative, adapt_movement_scale=adapt_movement_scale)
|
| 76 |
+
out = generator(source, kp_source=kp_source, kp_driving=kp_norm)
|
| 77 |
+
|
| 78 |
+
predictions.append(np.transpose(out['prediction'].data.cpu().numpy(), [0, 2, 3, 1])[0])
|
| 79 |
+
return predictions
|
| 80 |
+
|
| 81 |
+
def find_best_frame(source, driving, cpu=False):
|
| 82 |
+
import face_alignment # type: ignore (local file)
|
| 83 |
+
from scipy.spatial import ConvexHull
|
| 84 |
+
|
| 85 |
+
def normalize_kp(kp):
|
| 86 |
+
kp = kp - kp.mean(axis=0, keepdims=True)
|
| 87 |
+
area = ConvexHull(kp[:, :2]).volume
|
| 88 |
+
area = np.sqrt(area)
|
| 89 |
+
kp[:, :2] = kp[:, :2] / area
|
| 90 |
+
return kp
|
| 91 |
+
|
| 92 |
+
fa = face_alignment.FaceAlignment(face_alignment.LandmarksType._2D, flip_input=True,
|
| 93 |
+
device='cpu' if cpu else 'cuda')
|
| 94 |
+
kp_source = fa.get_landmarks(255 * source)[0]
|
| 95 |
+
kp_source = normalize_kp(kp_source)
|
| 96 |
+
norm = float('inf')
|
| 97 |
+
frame_num = 0
|
| 98 |
+
for i, image in tqdm(enumerate(driving)):
|
| 99 |
+
kp_driving = fa.get_landmarks(255 * image)[0]
|
| 100 |
+
kp_driving = normalize_kp(kp_driving)
|
| 101 |
+
new_norm = (np.abs(kp_source - kp_driving) ** 2).sum()
|
| 102 |
+
if new_norm < norm:
|
| 103 |
+
norm = new_norm
|
| 104 |
+
frame_num = i
|
| 105 |
+
return frame_num
|
| 106 |
+
|
| 107 |
+
if __name__ == "__main__":
|
| 108 |
+
parser = ArgumentParser()
|
| 109 |
+
parser.add_argument("--config", required=True, help="path to config")
|
| 110 |
+
parser.add_argument("--checkpoint", default='vox-cpk.pth.tar', help="path to checkpoint to restore")
|
| 111 |
+
|
| 112 |
+
parser.add_argument("--source_image", default='sup-mat/source.png', help="path to source image")
|
| 113 |
+
parser.add_argument("--driving_video", default='driving.mp4', help="path to driving video")
|
| 114 |
+
parser.add_argument("--result_video", default='result.mp4', help="path to output")
|
| 115 |
+
|
| 116 |
+
parser.add_argument("--relative", dest="relative", action="store_true", help="use relative or absolute keypoint coordinates")
|
| 117 |
+
parser.add_argument("--adapt_scale", dest="adapt_scale", action="store_true", help="adapt movement scale based on convex hull of keypoints")
|
| 118 |
+
|
| 119 |
+
parser.add_argument("--find_best_frame", dest="find_best_frame", action="store_true",
|
| 120 |
+
help="Generate from the frame that is the most alligned with source. (Only for faces, requires face_aligment lib)")
|
| 121 |
+
|
| 122 |
+
parser.add_argument("--best_frame", dest="best_frame", type=int, default=None, help="Set frame to start from.")
|
| 123 |
+
|
| 124 |
+
parser.add_argument("--cpu", dest="cpu", action="store_true", help="cpu mode.")
|
| 125 |
+
|
| 126 |
+
parser.add_argument("--audio", dest="audio", action="store_true", help="copy audio to output from the driving video" )
|
| 127 |
+
|
| 128 |
+
parser.set_defaults(relative=False)
|
| 129 |
+
parser.set_defaults(adapt_scale=False)
|
| 130 |
+
parser.set_defaults(audio_on=False)
|
| 131 |
+
|
| 132 |
+
opt = parser.parse_args()
|
| 133 |
+
|
| 134 |
+
source_image = imageio.imread(opt.source_image)
|
| 135 |
+
reader = imageio.get_reader(opt.driving_video)
|
| 136 |
+
fps = reader.get_meta_data()['fps']
|
| 137 |
+
driving_video = []
|
| 138 |
+
try:
|
| 139 |
+
for im in reader:
|
| 140 |
+
driving_video.append(im)
|
| 141 |
+
except RuntimeError:
|
| 142 |
+
pass
|
| 143 |
+
reader.close()
|
| 144 |
+
|
| 145 |
+
source_image = resize(source_image, (256, 256))[..., :3]
|
| 146 |
+
driving_video = [resize(frame, (256, 256))[..., :3] for frame in driving_video]
|
| 147 |
+
generator, kp_detector = load_checkpoints(config_path=opt.config, checkpoint_path=opt.checkpoint, cpu=opt.cpu)
|
| 148 |
+
|
| 149 |
+
if opt.find_best_frame or opt.best_frame is not None:
|
| 150 |
+
i = opt.best_frame if opt.best_frame is not None else find_best_frame(source_image, driving_video, cpu=opt.cpu)
|
| 151 |
+
print("Best frame: " + str(i))
|
| 152 |
+
driving_forward = driving_video[i:]
|
| 153 |
+
driving_backward = driving_video[:(i+1)][::-1]
|
| 154 |
+
predictions_forward = make_animation(source_image, driving_forward, generator, kp_detector, relative=opt.relative, adapt_movement_scale=opt.adapt_scale, cpu=opt.cpu)
|
| 155 |
+
predictions_backward = make_animation(source_image, driving_backward, generator, kp_detector, relative=opt.relative, adapt_movement_scale=opt.adapt_scale, cpu=opt.cpu)
|
| 156 |
+
predictions = predictions_backward[::-1] + predictions_forward[1:]
|
| 157 |
+
else:
|
| 158 |
+
predictions = make_animation(source_image, driving_video, generator, kp_detector, relative=opt.relative, adapt_movement_scale=opt.adapt_scale, cpu=opt.cpu)
|
| 159 |
+
imageio.mimsave(opt.result_video, [img_as_ubyte(frame) for frame in predictions], fps=fps)
|
| 160 |
+
|
| 161 |
+
if opt.audio:
|
| 162 |
+
try:
|
| 163 |
+
with NamedTemporaryFile(suffix=splitext(opt.result_video)[1]) as output:
|
| 164 |
+
ffmpeg.output(ffmpeg.input(opt.result_video).video, ffmpeg.input(opt.driving_video).audio, output.name, c='copy').run()
|
| 165 |
+
with open(opt.result_video, 'wb') as result:
|
| 166 |
+
copyfileobj(output, result)
|
| 167 |
+
except ffmpeg.Error:
|
| 168 |
+
print("Failed to copy audio: the driving video may have no audio track or the audio format is invalid.")
|
demo_jupyter.ipynb
ADDED
|
@@ -0,0 +1,804 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"metadata": {
|
| 6 |
+
"colab_type": "text",
|
| 7 |
+
"id": "view-in-github"
|
| 8 |
+
},
|
| 9 |
+
"source": [
|
| 10 |
+
"<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><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>"
|
| 11 |
+
]
|
| 12 |
+
},
|
| 13 |
+
{
|
| 14 |
+
"cell_type": "markdown",
|
| 15 |
+
"metadata": {
|
| 16 |
+
"id": "cdO_RxQZLahB"
|
| 17 |
+
},
|
| 18 |
+
"source": [
|
| 19 |
+
"# Demo for paper \"First Order Motion Model for Image Animation\"\n",
|
| 20 |
+
"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."
|
| 21 |
+
]
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"cell_type": "code",
|
| 25 |
+
"execution_count": 4,
|
| 26 |
+
"metadata": {
|
| 27 |
+
"id": "UCMFMJV7K-ag"
|
| 28 |
+
},
|
| 29 |
+
"outputs": [],
|
| 30 |
+
"source": [
|
| 31 |
+
"%%capture\n",
|
| 32 |
+
"%pip install ffmpeg-python imageio-ffmpeg\n",
|
| 33 |
+
"!git init .\n",
|
| 34 |
+
"!git remote add origin https://github.com/AliaksandrSiarohin/first-order-model\n",
|
| 35 |
+
"!git pull origin master\n",
|
| 36 |
+
"!git clone https://github.com/graphemecluster/first-order-model-demo demo"
|
| 37 |
+
]
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"cell_type": "code",
|
| 41 |
+
"execution_count": 104,
|
| 42 |
+
"metadata": {
|
| 43 |
+
"id": "Oxi6-riLOgnm"
|
| 44 |
+
},
|
| 45 |
+
"outputs": [
|
| 46 |
+
{
|
| 47 |
+
"data": {
|
| 48 |
+
"text/html": [
|
| 49 |
+
"\n",
|
| 50 |
+
"<style>\n",
|
| 51 |
+
".widget-box > * {\n",
|
| 52 |
+
"\tflex-shrink: 0;\n",
|
| 53 |
+
"}\n",
|
| 54 |
+
".widget-tab {\n",
|
| 55 |
+
"\tmin-width: 0;\n",
|
| 56 |
+
"\tflex: 1 1 auto;\n",
|
| 57 |
+
"}\n",
|
| 58 |
+
".widget-tab .p-TabBar-tabLabel {\n",
|
| 59 |
+
"\tfont-size: 15px;\n",
|
| 60 |
+
"}\n",
|
| 61 |
+
".widget-upload {\n",
|
| 62 |
+
"\tbackground-color: tan;\n",
|
| 63 |
+
"}\n",
|
| 64 |
+
".widget-button {\n",
|
| 65 |
+
"\tfont-size: 18px;\n",
|
| 66 |
+
"\twidth: 160px;\n",
|
| 67 |
+
"\theight: 34px;\n",
|
| 68 |
+
"\tline-height: 34px;\n",
|
| 69 |
+
"}\n",
|
| 70 |
+
".widget-dropdown {\n",
|
| 71 |
+
"\twidth: 250px;\n",
|
| 72 |
+
"}\n",
|
| 73 |
+
".widget-checkbox {\n",
|
| 74 |
+
"\twidth: 650px;\n",
|
| 75 |
+
"}\n",
|
| 76 |
+
".widget-checkbox + .widget-checkbox {\n",
|
| 77 |
+
"\tmargin-top: -6px;\n",
|
| 78 |
+
"}\n",
|
| 79 |
+
".input-widget .output_html {\n",
|
| 80 |
+
"\ttext-align: center;\n",
|
| 81 |
+
"\twidth: 266px;\n",
|
| 82 |
+
"\theight: 266px;\n",
|
| 83 |
+
"\tline-height: 266px;\n",
|
| 84 |
+
"\tcolor: lightgray;\n",
|
| 85 |
+
"\tfont-size: 72px;\n",
|
| 86 |
+
"}\n",
|
| 87 |
+
".title {\n",
|
| 88 |
+
"\tfont-size: 20px;\n",
|
| 89 |
+
"\tfont-weight: bold;\n",
|
| 90 |
+
"\tmargin: 12px 0 6px 0;\n",
|
| 91 |
+
"}\n",
|
| 92 |
+
".warning {\n",
|
| 93 |
+
"\tdisplay: none;\n",
|
| 94 |
+
"\tcolor: red;\n",
|
| 95 |
+
"\tmargin-left: 10px;\n",
|
| 96 |
+
"}\n",
|
| 97 |
+
".warn {\n",
|
| 98 |
+
"\tdisplay: initial;\n",
|
| 99 |
+
"}\n",
|
| 100 |
+
".resource {\n",
|
| 101 |
+
"\tcursor: pointer;\n",
|
| 102 |
+
"\tborder: 1px solid gray;\n",
|
| 103 |
+
"\tmargin: 5px;\n",
|
| 104 |
+
"\twidth: 160px;\n",
|
| 105 |
+
"\theight: 160px;\n",
|
| 106 |
+
"\tmin-width: 160px;\n",
|
| 107 |
+
"\tmin-height: 160px;\n",
|
| 108 |
+
"\tmax-width: 160px;\n",
|
| 109 |
+
"\tmax-height: 160px;\n",
|
| 110 |
+
"\t-webkit-box-sizing: initial;\n",
|
| 111 |
+
"\tbox-sizing: initial;\n",
|
| 112 |
+
"}\n",
|
| 113 |
+
".resource:hover {\n",
|
| 114 |
+
"\tborder: 6px solid crimson;\n",
|
| 115 |
+
"\tmargin: 0;\n",
|
| 116 |
+
"}\n",
|
| 117 |
+
".selected {\n",
|
| 118 |
+
"\tborder: 6px solid seagreen;\n",
|
| 119 |
+
"\tmargin: 0;\n",
|
| 120 |
+
"}\n",
|
| 121 |
+
".input-widget {\n",
|
| 122 |
+
"\twidth: 266px;\n",
|
| 123 |
+
"\theight: 266px;\n",
|
| 124 |
+
"\tborder: 1px solid gray;\n",
|
| 125 |
+
"}\n",
|
| 126 |
+
".input-button {\n",
|
| 127 |
+
"\twidth: 268px;\n",
|
| 128 |
+
"\tfont-size: 15px;\n",
|
| 129 |
+
"\tmargin: 2px 0 0;\n",
|
| 130 |
+
"}\n",
|
| 131 |
+
".output-widget {\n",
|
| 132 |
+
"\twidth: 256px;\n",
|
| 133 |
+
"\theight: 256px;\n",
|
| 134 |
+
"\tborder: 1px solid gray;\n",
|
| 135 |
+
"}\n",
|
| 136 |
+
".output-button {\n",
|
| 137 |
+
"\twidth: 258px;\n",
|
| 138 |
+
"\tfont-size: 15px;\n",
|
| 139 |
+
"\tmargin: 2px 0 0;\n",
|
| 140 |
+
"}\n",
|
| 141 |
+
".uploaded {\n",
|
| 142 |
+
"\twidth: 256px;\n",
|
| 143 |
+
"\theight: 256px;\n",
|
| 144 |
+
"\tborder: 6px solid seagreen;\n",
|
| 145 |
+
"\tmargin: 0;\n",
|
| 146 |
+
"}\n",
|
| 147 |
+
".label-or {\n",
|
| 148 |
+
"\talign-self: center;\n",
|
| 149 |
+
"\tfont-size: 20px;\n",
|
| 150 |
+
"\tmargin: 16px;\n",
|
| 151 |
+
"}\n",
|
| 152 |
+
".loading {\n",
|
| 153 |
+
"\talign-items: center;\n",
|
| 154 |
+
"\twidth: fit-content;\n",
|
| 155 |
+
"}\n",
|
| 156 |
+
".loader {\n",
|
| 157 |
+
"\tmargin: 32px 0 16px 0;\n",
|
| 158 |
+
"\twidth: 48px;\n",
|
| 159 |
+
"\theight: 48px;\n",
|
| 160 |
+
"\tmin-width: 48px;\n",
|
| 161 |
+
"\tmin-height: 48px;\n",
|
| 162 |
+
"\tmax-width: 48px;\n",
|
| 163 |
+
"\tmax-height: 48px;\n",
|
| 164 |
+
"\tborder: 4px solid whitesmoke;\n",
|
| 165 |
+
"\tborder-top-color: gray;\n",
|
| 166 |
+
"\tborder-radius: 50%;\n",
|
| 167 |
+
"\tanimation: spin 1.8s linear infinite;\n",
|
| 168 |
+
"}\n",
|
| 169 |
+
".loading-label {\n",
|
| 170 |
+
"\tcolor: gray;\n",
|
| 171 |
+
"}\n",
|
| 172 |
+
".video {\n",
|
| 173 |
+
"\tmargin: 0;\n",
|
| 174 |
+
"}\n",
|
| 175 |
+
".comparison-widget {\n",
|
| 176 |
+
"\twidth: 256px;\n",
|
| 177 |
+
"\theight: 256px;\n",
|
| 178 |
+
"\tborder: 1px solid gray;\n",
|
| 179 |
+
"\tmargin-left: 2px;\n",
|
| 180 |
+
"}\n",
|
| 181 |
+
".comparison-label {\n",
|
| 182 |
+
"\tcolor: gray;\n",
|
| 183 |
+
"\tfont-size: 14px;\n",
|
| 184 |
+
"\ttext-align: center;\n",
|
| 185 |
+
"\tposition: relative;\n",
|
| 186 |
+
"\tbottom: 3px;\n",
|
| 187 |
+
"}\n",
|
| 188 |
+
"@keyframes spin {\n",
|
| 189 |
+
"\tfrom { transform: rotate(0deg); }\n",
|
| 190 |
+
"\tto { transform: rotate(360deg); }\n",
|
| 191 |
+
"}\n",
|
| 192 |
+
"</style>\n"
|
| 193 |
+
],
|
| 194 |
+
"text/plain": [
|
| 195 |
+
"<IPython.core.display.HTML object>"
|
| 196 |
+
]
|
| 197 |
+
},
|
| 198 |
+
"metadata": {},
|
| 199 |
+
"output_type": "display_data"
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"data": {
|
| 203 |
+
"application/vnd.jupyter.widget-view+json": {
|
| 204 |
+
"model_id": "f53c7ccd3ec34f7ea8491237d5bf03ff",
|
| 205 |
+
"version_major": 2,
|
| 206 |
+
"version_minor": 0
|
| 207 |
+
},
|
| 208 |
+
"text/plain": [
|
| 209 |
+
"VBox(children=(VBox(children=(Label(value='Choose Image', _dom_classes=('title',)), HBox(children=(VBox(childr…"
|
| 210 |
+
]
|
| 211 |
+
},
|
| 212 |
+
"metadata": {},
|
| 213 |
+
"output_type": "display_data"
|
| 214 |
+
},
|
| 215 |
+
{
|
| 216 |
+
"data": {
|
| 217 |
+
"application/javascript": [
|
| 218 |
+
"\n",
|
| 219 |
+
"var images, videos;\n",
|
| 220 |
+
"function deselectImages() {\n",
|
| 221 |
+
"\timages.forEach(function(item) {\n",
|
| 222 |
+
"\t\titem.classList.remove(\"selected\");\n",
|
| 223 |
+
"\t});\n",
|
| 224 |
+
"}\n",
|
| 225 |
+
"function deselectVideos() {\n",
|
| 226 |
+
"\tvideos.forEach(function(item) {\n",
|
| 227 |
+
"\t\titem.classList.remove(\"selected\");\n",
|
| 228 |
+
"\t});\n",
|
| 229 |
+
"}\n",
|
| 230 |
+
"function invokePython(func) {\n",
|
| 231 |
+
"\tgoogle.colab.kernel.invokeFunction(\"notebook.\" + func, [].slice.call(arguments, 1), {});\n",
|
| 232 |
+
"}\n",
|
| 233 |
+
"setTimeout(function() {\n",
|
| 234 |
+
"\t(images = [].slice.call(document.getElementsByClassName(\"resource-image\"))).forEach(function(item) {\n",
|
| 235 |
+
"\t\titem.addEventListener(\"click\", function() {\n",
|
| 236 |
+
"\t\t\tdeselectImages();\n",
|
| 237 |
+
"\t\t\titem.classList.add(\"selected\");\n",
|
| 238 |
+
"\t\t\tinvokePython(\"select_image\", item.className.match(/resource-image(\\d\\d)/)[1]);\n",
|
| 239 |
+
"\t\t});\n",
|
| 240 |
+
"\t});\n",
|
| 241 |
+
"\timages[0].classList.add(\"selected\");\n",
|
| 242 |
+
"\t(videos = [].slice.call(document.getElementsByClassName(\"resource-video\"))).forEach(function(item) {\n",
|
| 243 |
+
"\t\titem.addEventListener(\"click\", function() {\n",
|
| 244 |
+
"\t\t\tdeselectVideos();\n",
|
| 245 |
+
"\t\t\titem.classList.add(\"selected\");\n",
|
| 246 |
+
"\t\t\tinvokePython(\"select_video\", item.className.match(/resource-video(\\d)/)[1]);\n",
|
| 247 |
+
"\t\t});\n",
|
| 248 |
+
"\t});\n",
|
| 249 |
+
"\tvideos[0].classList.add(\"selected\");\n",
|
| 250 |
+
"}, 1000);\n"
|
| 251 |
+
],
|
| 252 |
+
"text/plain": [
|
| 253 |
+
"<IPython.core.display.Javascript object>"
|
| 254 |
+
]
|
| 255 |
+
},
|
| 256 |
+
"metadata": {},
|
| 257 |
+
"output_type": "display_data"
|
| 258 |
+
}
|
| 259 |
+
],
|
| 260 |
+
"source": [
|
| 261 |
+
"import IPython.display\n",
|
| 262 |
+
"import PIL.Image\n",
|
| 263 |
+
"import cv2\n",
|
| 264 |
+
"import ffmpeg\n",
|
| 265 |
+
"import imageio\n",
|
| 266 |
+
"import io\n",
|
| 267 |
+
"import ipywidgets\n",
|
| 268 |
+
"import numpy\n",
|
| 269 |
+
"import os.path\n",
|
| 270 |
+
"import requests\n",
|
| 271 |
+
"import skimage.transform\n",
|
| 272 |
+
"import warnings\n",
|
| 273 |
+
"from base64 import b64encode\n",
|
| 274 |
+
"from demo import load_checkpoints, make_animation # type: ignore (local file)\n",
|
| 275 |
+
"from IPython.display import HTML, Javascript\n",
|
| 276 |
+
"from shutil import copyfileobj\n",
|
| 277 |
+
"from skimage import img_as_ubyte\n",
|
| 278 |
+
"from tempfile import NamedTemporaryFile\n",
|
| 279 |
+
"import os\n",
|
| 280 |
+
"import ipywidgets as ipyw\n",
|
| 281 |
+
"from IPython.display import display, FileLink\n",
|
| 282 |
+
"warnings.filterwarnings(\"ignore\")\n",
|
| 283 |
+
"os.makedirs(\"user\", exist_ok=True)\n",
|
| 284 |
+
"\n",
|
| 285 |
+
"display(HTML(\"\"\"\n",
|
| 286 |
+
"<style>\n",
|
| 287 |
+
".widget-box > * {\n",
|
| 288 |
+
"\tflex-shrink: 0;\n",
|
| 289 |
+
"}\n",
|
| 290 |
+
".widget-tab {\n",
|
| 291 |
+
"\tmin-width: 0;\n",
|
| 292 |
+
"\tflex: 1 1 auto;\n",
|
| 293 |
+
"}\n",
|
| 294 |
+
".widget-tab .p-TabBar-tabLabel {\n",
|
| 295 |
+
"\tfont-size: 15px;\n",
|
| 296 |
+
"}\n",
|
| 297 |
+
".widget-upload {\n",
|
| 298 |
+
"\tbackground-color: tan;\n",
|
| 299 |
+
"}\n",
|
| 300 |
+
".widget-button {\n",
|
| 301 |
+
"\tfont-size: 18px;\n",
|
| 302 |
+
"\twidth: 160px;\n",
|
| 303 |
+
"\theight: 34px;\n",
|
| 304 |
+
"\tline-height: 34px;\n",
|
| 305 |
+
"}\n",
|
| 306 |
+
".widget-dropdown {\n",
|
| 307 |
+
"\twidth: 250px;\n",
|
| 308 |
+
"}\n",
|
| 309 |
+
".widget-checkbox {\n",
|
| 310 |
+
"\twidth: 650px;\n",
|
| 311 |
+
"}\n",
|
| 312 |
+
".widget-checkbox + .widget-checkbox {\n",
|
| 313 |
+
"\tmargin-top: -6px;\n",
|
| 314 |
+
"}\n",
|
| 315 |
+
".input-widget .output_html {\n",
|
| 316 |
+
"\ttext-align: center;\n",
|
| 317 |
+
"\twidth: 266px;\n",
|
| 318 |
+
"\theight: 266px;\n",
|
| 319 |
+
"\tline-height: 266px;\n",
|
| 320 |
+
"\tcolor: lightgray;\n",
|
| 321 |
+
"\tfont-size: 72px;\n",
|
| 322 |
+
"}\n",
|
| 323 |
+
".title {\n",
|
| 324 |
+
"\tfont-size: 20px;\n",
|
| 325 |
+
"\tfont-weight: bold;\n",
|
| 326 |
+
"\tmargin: 12px 0 6px 0;\n",
|
| 327 |
+
"}\n",
|
| 328 |
+
".warning {\n",
|
| 329 |
+
"\tdisplay: none;\n",
|
| 330 |
+
"\tcolor: red;\n",
|
| 331 |
+
"\tmargin-left: 10px;\n",
|
| 332 |
+
"}\n",
|
| 333 |
+
".warn {\n",
|
| 334 |
+
"\tdisplay: initial;\n",
|
| 335 |
+
"}\n",
|
| 336 |
+
".resource {\n",
|
| 337 |
+
"\tcursor: pointer;\n",
|
| 338 |
+
"\tborder: 1px solid gray;\n",
|
| 339 |
+
"\tmargin: 5px;\n",
|
| 340 |
+
"\twidth: 160px;\n",
|
| 341 |
+
"\theight: 160px;\n",
|
| 342 |
+
"\tmin-width: 160px;\n",
|
| 343 |
+
"\tmin-height: 160px;\n",
|
| 344 |
+
"\tmax-width: 160px;\n",
|
| 345 |
+
"\tmax-height: 160px;\n",
|
| 346 |
+
"\t-webkit-box-sizing: initial;\n",
|
| 347 |
+
"\tbox-sizing: initial;\n",
|
| 348 |
+
"}\n",
|
| 349 |
+
".resource:hover {\n",
|
| 350 |
+
"\tborder: 6px solid crimson;\n",
|
| 351 |
+
"\tmargin: 0;\n",
|
| 352 |
+
"}\n",
|
| 353 |
+
".selected {\n",
|
| 354 |
+
"\tborder: 6px solid seagreen;\n",
|
| 355 |
+
"\tmargin: 0;\n",
|
| 356 |
+
"}\n",
|
| 357 |
+
".input-widget {\n",
|
| 358 |
+
"\twidth: 266px;\n",
|
| 359 |
+
"\theight: 266px;\n",
|
| 360 |
+
"\tborder: 1px solid gray;\n",
|
| 361 |
+
"}\n",
|
| 362 |
+
".input-button {\n",
|
| 363 |
+
"\twidth: 268px;\n",
|
| 364 |
+
"\tfont-size: 15px;\n",
|
| 365 |
+
"\tmargin: 2px 0 0;\n",
|
| 366 |
+
"}\n",
|
| 367 |
+
".output-widget {\n",
|
| 368 |
+
"\twidth: 256px;\n",
|
| 369 |
+
"\theight: 256px;\n",
|
| 370 |
+
"\tborder: 1px solid gray;\n",
|
| 371 |
+
"}\n",
|
| 372 |
+
".output-button {\n",
|
| 373 |
+
"\twidth: 258px;\n",
|
| 374 |
+
"\tfont-size: 15px;\n",
|
| 375 |
+
"\tmargin: 2px 0 0;\n",
|
| 376 |
+
"}\n",
|
| 377 |
+
".uploaded {\n",
|
| 378 |
+
"\twidth: 256px;\n",
|
| 379 |
+
"\theight: 256px;\n",
|
| 380 |
+
"\tborder: 6px solid seagreen;\n",
|
| 381 |
+
"\tmargin: 0;\n",
|
| 382 |
+
"}\n",
|
| 383 |
+
".label-or {\n",
|
| 384 |
+
"\talign-self: center;\n",
|
| 385 |
+
"\tfont-size: 20px;\n",
|
| 386 |
+
"\tmargin: 16px;\n",
|
| 387 |
+
"}\n",
|
| 388 |
+
".loading {\n",
|
| 389 |
+
"\talign-items: center;\n",
|
| 390 |
+
"\twidth: fit-content;\n",
|
| 391 |
+
"}\n",
|
| 392 |
+
".loader {\n",
|
| 393 |
+
"\tmargin: 32px 0 16px 0;\n",
|
| 394 |
+
"\twidth: 48px;\n",
|
| 395 |
+
"\theight: 48px;\n",
|
| 396 |
+
"\tmin-width: 48px;\n",
|
| 397 |
+
"\tmin-height: 48px;\n",
|
| 398 |
+
"\tmax-width: 48px;\n",
|
| 399 |
+
"\tmax-height: 48px;\n",
|
| 400 |
+
"\tborder: 4px solid whitesmoke;\n",
|
| 401 |
+
"\tborder-top-color: gray;\n",
|
| 402 |
+
"\tborder-radius: 50%;\n",
|
| 403 |
+
"\tanimation: spin 1.8s linear infinite;\n",
|
| 404 |
+
"}\n",
|
| 405 |
+
".loading-label {\n",
|
| 406 |
+
"\tcolor: gray;\n",
|
| 407 |
+
"}\n",
|
| 408 |
+
".video {\n",
|
| 409 |
+
"\tmargin: 0;\n",
|
| 410 |
+
"}\n",
|
| 411 |
+
".comparison-widget {\n",
|
| 412 |
+
"\twidth: 256px;\n",
|
| 413 |
+
"\theight: 256px;\n",
|
| 414 |
+
"\tborder: 1px solid gray;\n",
|
| 415 |
+
"\tmargin-left: 2px;\n",
|
| 416 |
+
"}\n",
|
| 417 |
+
".comparison-label {\n",
|
| 418 |
+
"\tcolor: gray;\n",
|
| 419 |
+
"\tfont-size: 14px;\n",
|
| 420 |
+
"\ttext-align: center;\n",
|
| 421 |
+
"\tposition: relative;\n",
|
| 422 |
+
"\tbottom: 3px;\n",
|
| 423 |
+
"}\n",
|
| 424 |
+
"@keyframes spin {\n",
|
| 425 |
+
"\tfrom { transform: rotate(0deg); }\n",
|
| 426 |
+
"\tto { transform: rotate(360deg); }\n",
|
| 427 |
+
"}\n",
|
| 428 |
+
"</style>\n",
|
| 429 |
+
"\"\"\"))\n",
|
| 430 |
+
"\n",
|
| 431 |
+
"\n",
|
| 432 |
+
"def uploaded_file(change):\n",
|
| 433 |
+
" save_dir = 'uploads'\n",
|
| 434 |
+
" if not os.path.exists(save_dir): os.mkdir(save_dir)\n",
|
| 435 |
+
" \n",
|
| 436 |
+
" uploads = change['new']\n",
|
| 437 |
+
" for upload in uploads:\n",
|
| 438 |
+
" filename = upload['name']\n",
|
| 439 |
+
" content = upload['content']\n",
|
| 440 |
+
" with open(os.path.join(save_dir,filename), 'wb') as f:\n",
|
| 441 |
+
" f.write(content)\n",
|
| 442 |
+
" with out:\n",
|
| 443 |
+
" print(change)\n",
|
| 444 |
+
" \n",
|
| 445 |
+
"def create_uploader():\n",
|
| 446 |
+
" uploader = ipyw.FileUpload(multiple=True)\n",
|
| 447 |
+
" display(uploader)\n",
|
| 448 |
+
" uploader.description = '📂 Upload'\n",
|
| 449 |
+
" uploader.observe(uploaded_file, names='value')\n",
|
| 450 |
+
"\n",
|
| 451 |
+
"def download_file(filename='./face.mp4') -> HTML:\n",
|
| 452 |
+
" fl=FileLink(filename)\n",
|
| 453 |
+
" fl.html_link_str =\"<a href='%s' target='' class='downloadLink'>%s</a>\"\n",
|
| 454 |
+
" \n",
|
| 455 |
+
" display(fl)\n",
|
| 456 |
+
" display(HTML(f\"\"\"\n",
|
| 457 |
+
"<script>\n",
|
| 458 |
+
" var links = document.getElementsByClassName('downloadLink');\n",
|
| 459 |
+
" Array.from(links).map(e => e.setAttribute('download', ''))\n",
|
| 460 |
+
" var links = document.getElementsByClassName('downloadLink');\n",
|
| 461 |
+
" ['data-commandlinker-args','data-commandlinker-command'].map(e => {{ Array.from(links).map(i => {{ i.removeAttribute(e) }} ) }})\n",
|
| 462 |
+
" links[0].click()\n",
|
| 463 |
+
"</script>\n",
|
| 464 |
+
"\"\"\"))\n",
|
| 465 |
+
" \n",
|
| 466 |
+
"def thumbnail(file):\n",
|
| 467 |
+
"\treturn imageio.get_reader(file, mode='I', format='FFMPEG').get_next_data()\n",
|
| 468 |
+
"\n",
|
| 469 |
+
"def create_image(i, j):\n",
|
| 470 |
+
"\timage_widget = ipywidgets.Image.from_file('demo/images/%d%d.png' % (i, j))\n",
|
| 471 |
+
"\timage_widget.add_class('resource')\n",
|
| 472 |
+
"\timage_widget.add_class('resource-image')\n",
|
| 473 |
+
"\timage_widget.add_class('resource-image%d%d' % (i, j))\n",
|
| 474 |
+
"\treturn image_widget\n",
|
| 475 |
+
"\n",
|
| 476 |
+
"def create_video(i):\n",
|
| 477 |
+
"\tvideo_widget = ipywidgets.Image(\n",
|
| 478 |
+
"\t\tvalue=cv2.imencode('.png', cv2.cvtColor(thumbnail('demo/videos/%d.mp4' % i), cv2.COLOR_RGB2BGR))[1].tostring(),\n",
|
| 479 |
+
"\t\tformat='png'\n",
|
| 480 |
+
"\t)\n",
|
| 481 |
+
"\tvideo_widget.add_class('resource')\n",
|
| 482 |
+
"\tvideo_widget.add_class('resource-video')\n",
|
| 483 |
+
"\tvideo_widget.add_class('resource-video%d' % i)\n",
|
| 484 |
+
"\treturn video_widget\n",
|
| 485 |
+
"\n",
|
| 486 |
+
"def create_title(title):\n",
|
| 487 |
+
"\ttitle_widget = ipywidgets.Label(title)\n",
|
| 488 |
+
"\ttitle_widget.add_class('title')\n",
|
| 489 |
+
"\treturn title_widget\n",
|
| 490 |
+
"\n",
|
| 491 |
+
"def download_output(button):\n",
|
| 492 |
+
"\tcomplete.layout.display = 'none'\n",
|
| 493 |
+
"\tloading.layout.display = ''\n",
|
| 494 |
+
"\tdownload_file('./output.mp4')\n",
|
| 495 |
+
"\t# files.download('output.mp4')\n",
|
| 496 |
+
"\tloading.layout.display = 'none'\n",
|
| 497 |
+
"\tcomplete.layout.display = ''\n",
|
| 498 |
+
"\n",
|
| 499 |
+
"def convert_output(button):\n",
|
| 500 |
+
"\tcomplete.layout.display = 'none'\n",
|
| 501 |
+
"\tloading.layout.display = ''\n",
|
| 502 |
+
"\tffmpeg.input('output.mp4').output('scaled.mp4', vf='scale=1080x1080:flags=lanczos,pad=1920:1080:420:0').overwrite_output().run()\n",
|
| 503 |
+
"\tfiles.download('scaled.mp4')\n",
|
| 504 |
+
"\tloading.layout.display = 'none'\n",
|
| 505 |
+
"\tcomplete.layout.display = ''\n",
|
| 506 |
+
"\n",
|
| 507 |
+
"def back_to_main(button):\n",
|
| 508 |
+
"\tcomplete.layout.display = 'none'\n",
|
| 509 |
+
"\tmain.layout.display = ''\n",
|
| 510 |
+
"\n",
|
| 511 |
+
"label_or = ipywidgets.Label('or')\n",
|
| 512 |
+
"label_or.add_class('label-or')\n",
|
| 513 |
+
"\n",
|
| 514 |
+
"image_titles = ['Peoples', 'Cartoons', 'Dolls', 'Game of Thrones', 'Statues']\n",
|
| 515 |
+
"image_lengths = [8, 4, 8, 9, 4]\n",
|
| 516 |
+
"\n",
|
| 517 |
+
"image_tab = ipywidgets.Tab()\n",
|
| 518 |
+
"image_tab.children = [ipywidgets.HBox([create_image(i, j) for j in range(length)]) for i, length in enumerate(image_lengths)]\n",
|
| 519 |
+
"for i, title in enumerate(image_titles):\n",
|
| 520 |
+
"\timage_tab.set_title(i, title)\n",
|
| 521 |
+
"\n",
|
| 522 |
+
"input_image_widget = ipywidgets.Output()\n",
|
| 523 |
+
"input_image_widget.add_class('input-widget')\n",
|
| 524 |
+
"upload_input_image_button = ipywidgets.FileUpload(accept='image/*', button_style='primary')\n",
|
| 525 |
+
"upload_input_image_button.add_class('input-button')\n",
|
| 526 |
+
"image_part = ipywidgets.HBox([\n",
|
| 527 |
+
"\tipywidgets.VBox([input_image_widget, upload_input_image_button]),\n",
|
| 528 |
+
"\tlabel_or,\n",
|
| 529 |
+
"\timage_tab\n",
|
| 530 |
+
"])\n",
|
| 531 |
+
"\n",
|
| 532 |
+
"video_tab = ipywidgets.Tab()\n",
|
| 533 |
+
"video_tab.children = [ipywidgets.HBox([create_video(i) for i in range(5)])]\n",
|
| 534 |
+
"video_tab.set_title(0, 'All Videos')\n",
|
| 535 |
+
"\n",
|
| 536 |
+
"input_video_widget = ipywidgets.Output()\n",
|
| 537 |
+
"input_video_widget.add_class('input-widget')\n",
|
| 538 |
+
"upload_input_video_button = ipywidgets.FileUpload(accept='video/*', button_style='primary')\n",
|
| 539 |
+
"upload_input_video_button.add_class('input-button')\n",
|
| 540 |
+
"video_part = ipywidgets.HBox([\n",
|
| 541 |
+
"\tipywidgets.VBox([input_video_widget, upload_input_video_button]),\n",
|
| 542 |
+
"\tlabel_or,\n",
|
| 543 |
+
"\tvideo_tab\n",
|
| 544 |
+
"])\n",
|
| 545 |
+
"\n",
|
| 546 |
+
"model = ipywidgets.Dropdown(\n",
|
| 547 |
+
"\tdescription=\"Model:\",\n",
|
| 548 |
+
"\toptions=[\n",
|
| 549 |
+
"\t\t'vox',\n",
|
| 550 |
+
"\t\t'vox-adv',\n",
|
| 551 |
+
"\t\t'taichi',\n",
|
| 552 |
+
"\t\t'taichi-adv',\n",
|
| 553 |
+
"\t\t'nemo',\n",
|
| 554 |
+
"\t\t'mgif',\n",
|
| 555 |
+
"\t\t'fashion',\n",
|
| 556 |
+
"\t\t'bair'\n",
|
| 557 |
+
"\t]\n",
|
| 558 |
+
")\n",
|
| 559 |
+
"warning = ipywidgets.HTML('<b>Warning:</b> Upload your own images and videos (see README)')\n",
|
| 560 |
+
"warning.add_class('warning')\n",
|
| 561 |
+
"model_part = ipywidgets.HBox([model, warning])\n",
|
| 562 |
+
"\n",
|
| 563 |
+
"relative = ipywidgets.Checkbox(description=\"Relative keypoint displacement (Inherit object proporions from the video)\", value=True)\n",
|
| 564 |
+
"adapt_movement_scale = ipywidgets.Checkbox(description=\"Adapt movement scale (Don’t touch unless you know want you are doing)\", value=True)\n",
|
| 565 |
+
"generate_button = ipywidgets.Button(description=\"Generate\", button_style='primary')\n",
|
| 566 |
+
"main = ipywidgets.VBox([\n",
|
| 567 |
+
"\tcreate_title('Choose Image'),\n",
|
| 568 |
+
"\timage_part,\n",
|
| 569 |
+
"\tcreate_title('Choose Video'),\n",
|
| 570 |
+
"\tvideo_part,\n",
|
| 571 |
+
"\tcreate_title('Settings'),\n",
|
| 572 |
+
"\tmodel_part,\n",
|
| 573 |
+
"\trelative,\n",
|
| 574 |
+
"\tadapt_movement_scale,\n",
|
| 575 |
+
"\tgenerate_button\n",
|
| 576 |
+
"])\n",
|
| 577 |
+
"\n",
|
| 578 |
+
"loader = ipywidgets.Label()\n",
|
| 579 |
+
"loader.add_class(\"loader\")\n",
|
| 580 |
+
"loading_label = ipywidgets.Label(\"This may take several minutes to process…\")\n",
|
| 581 |
+
"loading_label.add_class(\"loading-label\")\n",
|
| 582 |
+
"progress_bar = ipywidgets.Output()\n",
|
| 583 |
+
"loading = ipywidgets.VBox([loader, loading_label, progress_bar])\n",
|
| 584 |
+
"loading.add_class('loading')\n",
|
| 585 |
+
"\n",
|
| 586 |
+
"output_widget = ipywidgets.Output()\n",
|
| 587 |
+
"output_widget.add_class('output-widget')\n",
|
| 588 |
+
"download = ipywidgets.Button(description='Download', button_style='primary')\n",
|
| 589 |
+
"download.add_class('output-button')\n",
|
| 590 |
+
"download.on_click(download_output)\n",
|
| 591 |
+
"convert = ipywidgets.Button(description='Convert to 1920×1080', button_style='primary')\n",
|
| 592 |
+
"convert.add_class('output-button')\n",
|
| 593 |
+
"convert.on_click(convert_output)\n",
|
| 594 |
+
"back = ipywidgets.Button(description='Back', button_style='primary')\n",
|
| 595 |
+
"back.add_class('output-button')\n",
|
| 596 |
+
"back.on_click(back_to_main)\n",
|
| 597 |
+
"\n",
|
| 598 |
+
"comparison_widget = ipywidgets.Output()\n",
|
| 599 |
+
"comparison_widget.add_class('comparison-widget')\n",
|
| 600 |
+
"comparison_label = ipywidgets.Label('Comparison')\n",
|
| 601 |
+
"comparison_label.add_class('comparison-label')\n",
|
| 602 |
+
"complete = ipywidgets.HBox([\n",
|
| 603 |
+
"\tipywidgets.VBox([output_widget, download, convert, back]),\n",
|
| 604 |
+
"\tipywidgets.VBox([comparison_widget, comparison_label])\n",
|
| 605 |
+
"])\n",
|
| 606 |
+
"\n",
|
| 607 |
+
"display(ipywidgets.VBox([main, loading, complete]))\n",
|
| 608 |
+
"display(Javascript(\"\"\"\n",
|
| 609 |
+
"var images, videos;\n",
|
| 610 |
+
"function deselectImages() {\n",
|
| 611 |
+
"\timages.forEach(function(item) {\n",
|
| 612 |
+
"\t\titem.classList.remove(\"selected\");\n",
|
| 613 |
+
"\t});\n",
|
| 614 |
+
"}\n",
|
| 615 |
+
"function deselectVideos() {\n",
|
| 616 |
+
"\tvideos.forEach(function(item) {\n",
|
| 617 |
+
"\t\titem.classList.remove(\"selected\");\n",
|
| 618 |
+
"\t});\n",
|
| 619 |
+
"}\n",
|
| 620 |
+
"function invokePython(func) {\n",
|
| 621 |
+
"\tgoogle.colab.kernel.invokeFunction(\"notebook.\" + func, [].slice.call(arguments, 1), {});\n",
|
| 622 |
+
"}\n",
|
| 623 |
+
"setTimeout(function() {\n",
|
| 624 |
+
"\t(images = [].slice.call(document.getElementsByClassName(\"resource-image\"))).forEach(function(item) {\n",
|
| 625 |
+
"\t\titem.addEventListener(\"click\", function() {\n",
|
| 626 |
+
"\t\t\tdeselectImages();\n",
|
| 627 |
+
"\t\t\titem.classList.add(\"selected\");\n",
|
| 628 |
+
"\t\t\tinvokePython(\"select_image\", item.className.match(/resource-image(\\d\\d)/)[1]);\n",
|
| 629 |
+
"\t\t});\n",
|
| 630 |
+
"\t});\n",
|
| 631 |
+
"\timages[0].classList.add(\"selected\");\n",
|
| 632 |
+
"\t(videos = [].slice.call(document.getElementsByClassName(\"resource-video\"))).forEach(function(item) {\n",
|
| 633 |
+
"\t\titem.addEventListener(\"click\", function() {\n",
|
| 634 |
+
"\t\t\tdeselectVideos();\n",
|
| 635 |
+
"\t\t\titem.classList.add(\"selected\");\n",
|
| 636 |
+
"\t\t\tinvokePython(\"select_video\", item.className.match(/resource-video(\\d)/)[1]);\n",
|
| 637 |
+
"\t\t});\n",
|
| 638 |
+
"\t});\n",
|
| 639 |
+
"\tvideos[0].classList.add(\"selected\");\n",
|
| 640 |
+
"}, 1000);\n",
|
| 641 |
+
"\"\"\"))\n",
|
| 642 |
+
"\n",
|
| 643 |
+
"selected_image = None\n",
|
| 644 |
+
"def select_image(filename):\n",
|
| 645 |
+
"\tglobal selected_image\n",
|
| 646 |
+
"\tselected_image = resize(PIL.Image.open('demo/images/%s.png' % filename).convert(\"RGB\"))\n",
|
| 647 |
+
"\tinput_image_widget.clear_output(wait=True)\n",
|
| 648 |
+
"\twith input_image_widget:\n",
|
| 649 |
+
"\t\tdisplay(HTML('Image'))\n",
|
| 650 |
+
"\tinput_image_widget.remove_class('uploaded')\n",
|
| 651 |
+
"# output.register_callback(\"notebook.select_image\", select_image)\n",
|
| 652 |
+
"\n",
|
| 653 |
+
"selected_video = None\n",
|
| 654 |
+
"def select_video(filename):\n",
|
| 655 |
+
"\tglobal selected_video\n",
|
| 656 |
+
"\tselected_video = 'demo/videos/%s.mp4' % filename\n",
|
| 657 |
+
"\tinput_video_widget.clear_output(wait=True)\n",
|
| 658 |
+
"\twith input_video_widget:\n",
|
| 659 |
+
"\t\tdisplay(HTML('Video'))\n",
|
| 660 |
+
"\tinput_video_widget.remove_class('uploaded')\n",
|
| 661 |
+
"# output.register_callback(\"notebook.select_video\", select_video)\n",
|
| 662 |
+
"\n",
|
| 663 |
+
"def resize(image, size=(256, 256)):\n",
|
| 664 |
+
"\tw, h = image.size\n",
|
| 665 |
+
"\td = min(w, h)\n",
|
| 666 |
+
"\tr = ((w - d) // 2, (h - d) // 2, (w + d) // 2, (h + d) // 2)\n",
|
| 667 |
+
"\treturn image.resize(size, resample=PIL.Image.LANCZOS, box=r)\n",
|
| 668 |
+
"\n",
|
| 669 |
+
"def upload_image(change):\n",
|
| 670 |
+
"\tglobal selected_image\n",
|
| 671 |
+
"\tcontent = upload_input_image_button.value[0]['content']\n",
|
| 672 |
+
"\tname = upload_input_image_button.value[0]['name']\n",
|
| 673 |
+
" \n",
|
| 674 |
+
"\t# for name, file_info in upload_input_image_button.value.items():\n",
|
| 675 |
+
"\t\t# content = file_info['content']\n",
|
| 676 |
+
"\tif content is not None:\n",
|
| 677 |
+
"\t\tselected_image = resize(PIL.Image.open(io.BytesIO(content)).convert(\"RGB\"))\n",
|
| 678 |
+
"\t\tinput_image_widget.clear_output(wait=True)\n",
|
| 679 |
+
"\t\twith input_image_widget:\n",
|
| 680 |
+
"\t\t\tdisplay(selected_image)\n",
|
| 681 |
+
"\t\tinput_image_widget.add_class('uploaded')\n",
|
| 682 |
+
"\t\tdisplay(Javascript('deselectImages()'))\n",
|
| 683 |
+
"upload_input_image_button.observe(upload_image, names='value')\n",
|
| 684 |
+
"\n",
|
| 685 |
+
"def upload_video(change):\n",
|
| 686 |
+
"\tglobal selected_video\n",
|
| 687 |
+
"\t# for name, file_info in upload_input_video_button.value.items():\n",
|
| 688 |
+
"\t\t# content = file_info['content']\n",
|
| 689 |
+
"\tcontent = upload_input_video_button.value[0]['content']\n",
|
| 690 |
+
"\tname = upload_input_video_button.value[0]['name']\n",
|
| 691 |
+
"\tif content is not None:\n",
|
| 692 |
+
"\t\tselected_video = 'user/' + name\n",
|
| 693 |
+
"\t\tpreview = resize(PIL.Image.fromarray(thumbnail(content)).convert(\"RGB\"))\n",
|
| 694 |
+
"\t\tinput_video_widget.clear_output(wait=True)\n",
|
| 695 |
+
"\t\twith input_video_widget:\n",
|
| 696 |
+
"\t\t\tdisplay(preview)\n",
|
| 697 |
+
"\t\tinput_video_widget.add_class('uploaded')\n",
|
| 698 |
+
"\t\tdisplay(Javascript('deselectVideos()'))\n",
|
| 699 |
+
"\t\twith open(selected_video, 'wb') as video:\n",
|
| 700 |
+
"\t\t\tvideo.write(content)\n",
|
| 701 |
+
"upload_input_video_button.observe(upload_video, names='value')\n",
|
| 702 |
+
"\n",
|
| 703 |
+
"def change_model(change):\n",
|
| 704 |
+
"\tif model.value.startswith('vox'):\n",
|
| 705 |
+
"\t\twarning.remove_class('warn')\n",
|
| 706 |
+
"\telse:\n",
|
| 707 |
+
"\t\twarning.add_class('warn')\n",
|
| 708 |
+
"model.observe(change_model, names='value')\n",
|
| 709 |
+
"\n",
|
| 710 |
+
"def generate(button):\n",
|
| 711 |
+
"\tmain.layout.display = 'none'\n",
|
| 712 |
+
"\tloading.layout.display = ''\n",
|
| 713 |
+
"\tfilename = model.value + ('' if model.value == 'fashion' else '-cpk') + '.pth.tar'\n",
|
| 714 |
+
"\tif not os.path.isfile(filename):\n",
|
| 715 |
+
"\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",
|
| 716 |
+
"\t\twith open(filename, 'wb') as checkpoint:\n",
|
| 717 |
+
"\t\t\tcheckpoint.write(download.content)\n",
|
| 718 |
+
"\treader = imageio.get_reader(selected_video, mode='I', format='FFMPEG')\n",
|
| 719 |
+
"\tfps = reader.get_meta_data()['fps']\n",
|
| 720 |
+
"\tdriving_video = []\n",
|
| 721 |
+
"\tfor frame in reader:\n",
|
| 722 |
+
"\t\tdriving_video.append(frame)\n",
|
| 723 |
+
"\tgenerator, kp_detector = load_checkpoints(config_path='config/%s-256.yaml' % model.value, checkpoint_path=filename)\n",
|
| 724 |
+
"\twith progress_bar:\n",
|
| 725 |
+
"\t\tpredictions = make_animation(\n",
|
| 726 |
+
"\t\t\tskimage.transform.resize(numpy.asarray(selected_image), (256, 256)),\n",
|
| 727 |
+
"\t\t\t[skimage.transform.resize(frame, (256, 256)) for frame in driving_video],\n",
|
| 728 |
+
"\t\t\tgenerator,\n",
|
| 729 |
+
"\t\t\tkp_detector,\n",
|
| 730 |
+
"\t\t\trelative=relative.value,\n",
|
| 731 |
+
"\t\t\tadapt_movement_scale=adapt_movement_scale.value\n",
|
| 732 |
+
"\t\t)\n",
|
| 733 |
+
"\tprogress_bar.clear_output()\n",
|
| 734 |
+
"\timageio.mimsave('output.mp4', [img_as_ubyte(frame) for frame in predictions], fps=fps)\n",
|
| 735 |
+
"\tif selected_video.startswith('user/') or selected_video == 'demo/videos/0.mp4':\n",
|
| 736 |
+
"\t\twith NamedTemporaryFile(suffix='.mp4') as output:\n",
|
| 737 |
+
"\t\t\tffmpeg.output(ffmpeg.input('output.mp4').video, ffmpeg.input(selected_video).audio, output.name, c='copy').overwrite_output().run()\n",
|
| 738 |
+
"\t\t\twith open('output.mp4', 'wb') as result:\n",
|
| 739 |
+
"\t\t\t\tcopyfileobj(output, result)\n",
|
| 740 |
+
"\twith output_widget:\n",
|
| 741 |
+
"\t\tvideo_widget = ipywidgets.Video.from_file('output.mp4', autoplay=False, loop=False)\n",
|
| 742 |
+
"\t\tvideo_widget.add_class('video')\n",
|
| 743 |
+
"\t\tvideo_widget.add_class('video-left')\n",
|
| 744 |
+
"\t\tdisplay(video_widget)\n",
|
| 745 |
+
"\twith comparison_widget:\n",
|
| 746 |
+
"\t\tvideo_widget = ipywidgets.Video.from_file(selected_video, autoplay=False, loop=False, controls=False)\n",
|
| 747 |
+
"\t\tvideo_widget.add_class('video')\n",
|
| 748 |
+
"\t\tvideo_widget.add_class('video-right')\n",
|
| 749 |
+
"\t\tdisplay(video_widget)\n",
|
| 750 |
+
"\tdisplay(Javascript(\"\"\"\n",
|
| 751 |
+
"\tsetTimeout(function() {\n",
|
| 752 |
+
"\t\t(function(left, right) {\n",
|
| 753 |
+
"\t\t\tleft.addEventListener(\"play\", function() {\n",
|
| 754 |
+
"\t\t\t\tright.play();\n",
|
| 755 |
+
"\t\t\t});\n",
|
| 756 |
+
"\t\t\tleft.addEventListener(\"pause\", function() {\n",
|
| 757 |
+
"\t\t\t\tright.pause();\n",
|
| 758 |
+
"\t\t\t});\n",
|
| 759 |
+
"\t\t\tleft.addEventListener(\"seeking\", function() {\n",
|
| 760 |
+
"\t\t\t\tright.currentTime = left.currentTime;\n",
|
| 761 |
+
"\t\t\t});\n",
|
| 762 |
+
"\t\t\tright.muted = true;\n",
|
| 763 |
+
"\t\t})(document.getElementsByClassName(\"video-left\")[0], document.getElementsByClassName(\"video-right\")[0]);\n",
|
| 764 |
+
"\t}, 1000);\n",
|
| 765 |
+
"\t\"\"\"))\n",
|
| 766 |
+
"\tloading.layout.display = 'none'\n",
|
| 767 |
+
"\tcomplete.layout.display = ''\n",
|
| 768 |
+
"\n",
|
| 769 |
+
"generate_button.on_click(generate)\n",
|
| 770 |
+
"\n",
|
| 771 |
+
"loading.layout.display = 'none'\n",
|
| 772 |
+
"complete.layout.display = 'none'\n",
|
| 773 |
+
"select_image('00')\n",
|
| 774 |
+
"select_video('0')"
|
| 775 |
+
]
|
| 776 |
+
}
|
| 777 |
+
],
|
| 778 |
+
"metadata": {
|
| 779 |
+
"accelerator": "GPU",
|
| 780 |
+
"colab": {
|
| 781 |
+
"name": "first-order-model-demo",
|
| 782 |
+
"provenance": []
|
| 783 |
+
},
|
| 784 |
+
"kernelspec": {
|
| 785 |
+
"display_name": "ldm",
|
| 786 |
+
"language": "python",
|
| 787 |
+
"name": "ldm"
|
| 788 |
+
},
|
| 789 |
+
"language_info": {
|
| 790 |
+
"codemirror_mode": {
|
| 791 |
+
"name": "ipython",
|
| 792 |
+
"version": 3
|
| 793 |
+
},
|
| 794 |
+
"file_extension": ".py",
|
| 795 |
+
"mimetype": "text/x-python",
|
| 796 |
+
"name": "python",
|
| 797 |
+
"nbconvert_exporter": "python",
|
| 798 |
+
"pygments_lexer": "ipython3",
|
| 799 |
+
"version": "3.8.5"
|
| 800 |
+
}
|
| 801 |
+
},
|
| 802 |
+
"nbformat": 4,
|
| 803 |
+
"nbformat_minor": 4
|
| 804 |
+
}
|
frames_dataset.py
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 disk
|
| 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 |
+
if torch.cuda.is_available():
|
| 54 |
+
map_location = None
|
| 55 |
+
else:
|
| 56 |
+
map_location = 'cpu'
|
| 57 |
+
checkpoint = torch.load(checkpoint_path, map_location)
|
| 58 |
+
if generator is not None:
|
| 59 |
+
generator.load_state_dict(checkpoint['generator'])
|
| 60 |
+
if kp_detector is not None:
|
| 61 |
+
kp_detector.load_state_dict(checkpoint['kp_detector'])
|
| 62 |
+
if discriminator is not None:
|
| 63 |
+
try:
|
| 64 |
+
discriminator.load_state_dict(checkpoint['discriminator'])
|
| 65 |
+
except:
|
| 66 |
+
print ('No discriminator in the state-dict. Dicriminator will be randomly initialized')
|
| 67 |
+
if optimizer_generator is not None:
|
| 68 |
+
optimizer_generator.load_state_dict(checkpoint['optimizer_generator'])
|
| 69 |
+
if optimizer_discriminator is not None:
|
| 70 |
+
try:
|
| 71 |
+
optimizer_discriminator.load_state_dict(checkpoint['optimizer_discriminator'])
|
| 72 |
+
except RuntimeError as e:
|
| 73 |
+
print ('No discriminator optimizer in the state-dict. Optimizer will be not initialized')
|
| 74 |
+
if optimizer_kp_detector is not None:
|
| 75 |
+
optimizer_kp_detector.load_state_dict(checkpoint['optimizer_kp_detector'])
|
| 76 |
+
|
| 77 |
+
return checkpoint['epoch']
|
| 78 |
+
|
| 79 |
+
def __enter__(self):
|
| 80 |
+
return self
|
| 81 |
+
|
| 82 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
| 83 |
+
if 'models' in self.__dict__:
|
| 84 |
+
self.save_cpk()
|
| 85 |
+
self.log_file.close()
|
| 86 |
+
|
| 87 |
+
def log_iter(self, losses):
|
| 88 |
+
losses = collections.OrderedDict(losses.items())
|
| 89 |
+
if self.names is None:
|
| 90 |
+
self.names = list(losses.keys())
|
| 91 |
+
self.loss_list.append(list(losses.values()))
|
| 92 |
+
|
| 93 |
+
def log_epoch(self, epoch, models, inp, out):
|
| 94 |
+
self.epoch = epoch
|
| 95 |
+
self.models = models
|
| 96 |
+
if (self.epoch + 1) % self.checkpoint_freq == 0:
|
| 97 |
+
self.save_cpk()
|
| 98 |
+
self.log_scores(self.names)
|
| 99 |
+
self.visualize_rec(inp, out)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class Visualizer:
|
| 103 |
+
def __init__(self, kp_size=5, draw_border=False, colormap='gist_rainbow'):
|
| 104 |
+
self.kp_size = kp_size
|
| 105 |
+
self.draw_border = draw_border
|
| 106 |
+
self.colormap = plt.get_cmap(colormap)
|
| 107 |
+
|
| 108 |
+
def draw_image_with_kp(self, image, kp_array):
|
| 109 |
+
image = np.copy(image)
|
| 110 |
+
spatial_size = np.array(image.shape[:2][::-1])[np.newaxis]
|
| 111 |
+
kp_array = spatial_size * (kp_array + 1) / 2
|
| 112 |
+
num_kp = kp_array.shape[0]
|
| 113 |
+
for kp_ind, kp in enumerate(kp_array):
|
| 114 |
+
rr, cc = disk(kp[1], kp[0], self.kp_size, shape=image.shape[:2])
|
| 115 |
+
image[rr, cc] = np.array(self.colormap(kp_ind / num_kp))[:3]
|
| 116 |
+
return image
|
| 117 |
+
|
| 118 |
+
def create_image_column_with_kp(self, images, kp):
|
| 119 |
+
image_array = np.array([self.draw_image_with_kp(v, k) for v, k in zip(images, kp)])
|
| 120 |
+
return self.create_image_column(image_array)
|
| 121 |
+
|
| 122 |
+
def create_image_column(self, images):
|
| 123 |
+
if self.draw_border:
|
| 124 |
+
images = np.copy(images)
|
| 125 |
+
images[:, :, [0, -1]] = (1, 1, 1)
|
| 126 |
+
return np.concatenate(list(images), axis=0)
|
| 127 |
+
|
| 128 |
+
def create_image_grid(self, *args):
|
| 129 |
+
out = []
|
| 130 |
+
for arg in args:
|
| 131 |
+
if type(arg) == tuple:
|
| 132 |
+
out.append(self.create_image_column_with_kp(arg[0], arg[1]))
|
| 133 |
+
else:
|
| 134 |
+
out.append(self.create_image_column(arg))
|
| 135 |
+
return np.concatenate(out, axis=1)
|
| 136 |
+
|
| 137 |
+
def visualize(self, driving, source, out):
|
| 138 |
+
images = []
|
| 139 |
+
|
| 140 |
+
# Source image with keypoints
|
| 141 |
+
source = source.data.cpu()
|
| 142 |
+
kp_source = out['kp_source']['value'].data.cpu().numpy()
|
| 143 |
+
source = np.transpose(source, [0, 2, 3, 1])
|
| 144 |
+
images.append((source, kp_source))
|
| 145 |
+
|
| 146 |
+
# Equivariance visualization
|
| 147 |
+
if 'transformed_frame' in out:
|
| 148 |
+
transformed = out['transformed_frame'].data.cpu().numpy()
|
| 149 |
+
transformed = np.transpose(transformed, [0, 2, 3, 1])
|
| 150 |
+
transformed_kp = out['transformed_kp']['value'].data.cpu().numpy()
|
| 151 |
+
images.append((transformed, transformed_kp))
|
| 152 |
+
|
| 153 |
+
# Driving image with keypoints
|
| 154 |
+
kp_driving = out['kp_driving']['value'].data.cpu().numpy()
|
| 155 |
+
driving = driving.data.cpu().numpy()
|
| 156 |
+
driving = np.transpose(driving, [0, 2, 3, 1])
|
| 157 |
+
images.append((driving, kp_driving))
|
| 158 |
+
|
| 159 |
+
# Deformed image
|
| 160 |
+
if 'deformed' in out:
|
| 161 |
+
deformed = out['deformed'].data.cpu().numpy()
|
| 162 |
+
deformed = np.transpose(deformed, [0, 2, 3, 1])
|
| 163 |
+
images.append(deformed)
|
| 164 |
+
|
| 165 |
+
# Result with and without keypoints
|
| 166 |
+
prediction = out['prediction'].data.cpu().numpy()
|
| 167 |
+
prediction = np.transpose(prediction, [0, 2, 3, 1])
|
| 168 |
+
if 'kp_norm' in out:
|
| 169 |
+
kp_norm = out['kp_norm']['value'].data.cpu().numpy()
|
| 170 |
+
images.append((prediction, kp_norm))
|
| 171 |
+
images.append(prediction)
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
## Occlusion map
|
| 175 |
+
if 'occlusion_map' in out:
|
| 176 |
+
occlusion_map = out['occlusion_map'].data.cpu().repeat(1, 3, 1, 1)
|
| 177 |
+
occlusion_map = F.interpolate(occlusion_map, size=source.shape[1:3]).numpy()
|
| 178 |
+
occlusion_map = np.transpose(occlusion_map, [0, 2, 3, 1])
|
| 179 |
+
images.append(occlusion_map)
|
| 180 |
+
|
| 181 |
+
# Deformed images according to each individual transform
|
| 182 |
+
if 'sparse_deformed' in out:
|
| 183 |
+
full_mask = []
|
| 184 |
+
for i in range(out['sparse_deformed'].shape[1]):
|
| 185 |
+
image = out['sparse_deformed'][:, i].data.cpu()
|
| 186 |
+
image = F.interpolate(image, size=source.shape[1:3])
|
| 187 |
+
mask = out['mask'][:, i:(i+1)].data.cpu().repeat(1, 3, 1, 1)
|
| 188 |
+
mask = F.interpolate(mask, size=source.shape[1:3])
|
| 189 |
+
image = np.transpose(image.numpy(), (0, 2, 3, 1))
|
| 190 |
+
mask = np.transpose(mask.numpy(), (0, 2, 3, 1))
|
| 191 |
+
|
| 192 |
+
if i != 0:
|
| 193 |
+
color = np.array(self.colormap((i - 1) / (out['sparse_deformed'].shape[1] - 1)))[:3]
|
| 194 |
+
else:
|
| 195 |
+
color = np.array((0, 0, 0))
|
| 196 |
+
|
| 197 |
+
color = color.reshape((1, 1, 1, 3))
|
| 198 |
+
|
| 199 |
+
images.append(image)
|
| 200 |
+
if i != 0:
|
| 201 |
+
images.append(mask * color)
|
| 202 |
+
else:
|
| 203 |
+
images.append(mask)
|
| 204 |
+
|
| 205 |
+
full_mask.append(mask * color)
|
| 206 |
+
|
| 207 |
+
images.append(sum(full_mask))
|
| 208 |
+
|
| 209 |
+
image = self.create_image_grid(*images)
|
| 210 |
+
image = (255 * image).astype(np.uint8)
|
| 211 |
+
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,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ffmpeg-python==0.2.0
|
| 2 |
+
imageio==2.22.0
|
| 3 |
+
imageio-ffmpeg==0.4.7
|
| 4 |
+
matplotlib==3.6.0
|
| 5 |
+
numpy==1.23.3
|
| 6 |
+
pandas==1.5.0
|
| 7 |
+
python-dateutil==2.8.2
|
| 8 |
+
pytz==2022.2.1
|
| 9 |
+
PyYAML==6.0
|
| 10 |
+
scikit-image==0.19.3
|
| 11 |
+
scikit-learn==1.1.2
|
| 12 |
+
scipy==1.9.1
|
| 13 |
+
torch==1.12.1
|
| 14 |
+
torchvision==0.13.1
|
| 15 |
+
tqdm==4.64.1
|
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)
|