Added vtoonify but not fully connected to project
This commit is contained in:
@@ -1,3 +1,6 @@
|
||||
yolo11m-pose.pt
|
||||
yolo11m-seg.pt
|
||||
vtoonify/*
|
||||
vtoonify/checkpoint/*
|
||||
vtoonify/data/*
|
||||
vtoonify/model/*
|
||||
vtoonify/image_cache/*
|
||||
@@ -0,0 +1,14 @@
|
||||
# S-Lab License 1.0
|
||||
|
||||
Copyright 2022 S-Lab
|
||||
|
||||
Redistribution and use for non-commercial purpose in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
4. In the event that redistribution and/or use for commercial purpose in source or binary forms, with or without modification is required, please contact the contributor(s) of the work.
|
||||
|
||||
|
||||
---
|
||||
For the commercial use of VToonify, please consult Prof. Chen Change Loy (ccloy@ntu.edu.sg)
|
||||
@@ -0,0 +1,315 @@
|
||||
# VToonify - Official PyTorch Implementation
|
||||
|
||||
https://user-images.githubusercontent.com/18130694/189483939-0fc4a358-fb34-43cc-811a-b22adb820d57.mp4
|
||||
|
||||
This repository provides the official PyTorch implementation for the following paper:
|
||||
|
||||
**VToonify: Controllable High-Resolution Portrait Video Style Transfer**<br>
|
||||
[Shuai Yang](https://williamyang1991.github.io/), [Liming Jiang](https://liming-jiang.com/), [Ziwei Liu](https://liuziwei7.github.io/) and [Chen Change Loy](https://www.mmlab-ntu.com/person/ccloy/)<br>
|
||||
In ACM TOG (Proceedings of SIGGRAPH Asia), 2022.<br>
|
||||
[**Project Page**](https://www.mmlab-ntu.com/project/vtoonify/) | [**Paper**](https://arxiv.org/abs/2209.11224) | [**Supplementary Video**](https://youtu.be/0_OmVhDgYuY) | [**Input Data and Video Results**](https://drive.google.com/file/d/1A2gC2PW1ZmU6VWQRvMN98njqRxfLjqbk/view?usp=sharing) <br>
|
||||
|
||||
<a href="http://colab.research.google.com/github/williamyang1991/VToonify/blob/master/notebooks/inference_playground.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="google colab logo"></a>
|
||||
[](https://huggingface.co/spaces/PKUWilliamYang/VToonify)
|
||||
[](https://deque.ai/experience/notebook/dbabc82a-ace4-11ed-84b5-0242ac110002)
|
||||

|
||||
<!---->
|
||||
|
||||
|
||||
> **Abstract:** *Generating high-quality artistic portrait videos is an important and desirable task in computer graphics and vision.
|
||||
Although a series of successful portrait image toonification models built upon the powerful StyleGAN have been proposed,
|
||||
these image-oriented methods have obvious limitations when applied to videos, such as the fixed frame size, the requirement of face alignment, missing non-facial details and temporal inconsistency.
|
||||
In this work, we investigate the challenging controllable high-resolution portrait video style transfer by introducing a novel **VToonify** framework.
|
||||
Specifically, VToonify leverages the mid- and high-resolution layers of StyleGAN to render high-quality artistic portraits based on the multi-scale content features extracted by an encoder to better preserve the frame details. The resulting fully convolutional architecture accepts non-aligned faces in videos of variable size as input, contributing to complete face regions with natural motions in the output.
|
||||
Our framework is compatible with existing StyleGAN-based image toonification models to extend them to video toonification, and inherits appealing features of these models for flexible style control on color and intensity.
|
||||
This work presents two instantiations of VToonify built upon Toonify and DualStyleGAN for collection-based and exemplar-based portrait video style transfer, respectively.
|
||||
Extensive experimental results demonstrate the effectiveness of our proposed VToonify framework over existing methods in generating high-quality and temporally-coherent artistic portrait videos with flexible style controls.*
|
||||
|
||||
**Features**:<br>
|
||||
**High-Resolution Video** (>1024, support unaligned faces) | **Data-Friendly** (no real training data) | **Style Control**
|
||||
|
||||

|
||||
|
||||
|
||||
## Updates
|
||||
|
||||
- [02/2023] Integrated to [Deque Notebook](https://deque.ai/experience/notebook/dbabc82a-ace4-11ed-84b5-0242ac110002).
|
||||
- [10/2022] Integrate [Gradio](https://gradio.app/) interface into [Colab notebook](http://colab.research.google.com/github/williamyang1991/VToonify/blob/master/notebooks/inference_playground.ipynb). Enjoy the web demo!
|
||||
- [10/2022] Integrated to 🤗 [Hugging Face](https://huggingface.co/spaces/PKUWilliamYang/VToonify). Enjoy the web demo!
|
||||
- [09/2022] Input videos and video results are released.
|
||||
- [09/2022] Paper is released.
|
||||
- [09/2022] Code is released.
|
||||
- [09/2022] This website is created.
|
||||
|
||||
## Web Demo
|
||||
|
||||
Integrated into [Huggingface Spaces 🤗](https://huggingface.co/spaces) using [Gradio](https://github.com/gradio-app/gradio). Try out the Web Demo [](https://huggingface.co/spaces/PKUWilliamYang/VToonify)
|
||||
|
||||
|
||||
## Installation
|
||||
**Clone this repo:**
|
||||
```bash
|
||||
git clone https://github.com/williamyang1991/VToonify.git
|
||||
cd VToonify
|
||||
```
|
||||
**Dependencies:**
|
||||
|
||||
We have tested on:
|
||||
- CUDA 10.1
|
||||
- PyTorch 1.7.0
|
||||
- Pillow 8.3.1; Matplotlib 3.3.4; opencv-python 4.5.3; Faiss 1.7.1; tqdm 4.61.2; Ninja 1.10.2
|
||||
|
||||
All dependencies for defining the environment are provided in `environment/vtoonify_env.yaml`.
|
||||
We recommend running this repository using [Anaconda](https://docs.anaconda.com/anaconda/install/) (you may need to modify `vtoonify_env.yaml` to install PyTorch that matches your own CUDA version following [https://pytorch.org/](https://pytorch.org/)):
|
||||
```bash
|
||||
conda env create -f ./environment/vtoonify_env.yaml
|
||||
```
|
||||
|
||||
☞ Install on Windows: https://github.com/williamyang1991/VToonify/issues/50#issuecomment-1443061101 and https://github.com/williamyang1991/VToonify/issues/38#issuecomment-1442146800
|
||||
|
||||
☞ If you have a problem regarding the cpp extention (fused and upfirdn2d), or no GPU is available, you may refer to [CPU compatible version](./model/stylegan/op_cpu#readme).
|
||||
|
||||
<br/>
|
||||
|
||||
## (1) Inference for Image/Video Toonification
|
||||
|
||||
### Inference Notebook
|
||||
<a href="http://colab.research.google.com/github/williamyang1991/VToonify/blob/master/notebooks/inference_playground.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="google colab logo"></a>
|
||||
[](https://deque.ai/experience/notebook/dbabc82a-ace4-11ed-84b5-0242ac110002)
|
||||
|
||||
To help users get started, we provide a Jupyter notebook found in `./notebooks/inference_playground.ipynb` that allows one to visualize the performance of VToonify.
|
||||
The notebook will download the necessary pretrained models and run inference on the images found in `./data/`.
|
||||
|
||||
### Pre-trained Models
|
||||
|
||||
Pre-trained models can be downloaded from [Google Drive](https://drive.google.com/drive/folders/1Nmbz9zBM78I1nRVokhHLuBKHleDmjDxv?usp=sharing), [Baidu Cloud](https://pan.baidu.com/s/1Io3PKNV1wD7ttxaVz-MPww?pwd=sigg) (access code: sigg) or [Hugging Face](https://huggingface.co/PKUWilliamYang/VToonify/tree/main/models):
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<th>Backbone</th><th>Model</th><th>Description</th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td rowspan="6">DualStyleGAN</td><td><a href="https://drive.google.com/drive/folders/1DuZfXt6b_xhTAQSN0D8m7N1np0Web0Ky">cartoon</a></td><td>pre-trained VToonify-D models and 317 cartoon style codes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="https://drive.google.com/drive/folders/12TzTQqwBedsYX3kE_420mdTbWl9lwv4Y">caricature</a></td><td>pre-trained VToonify-D models and 199 caricature style codes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="https://drive.google.com/drive/folders/1MpEqS26Q1ngTPeex_4MN9qOJxfXKH-k-">arcane</a></td><td>pre-trained VToonify-D models and 100 arcane style codes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="https://drive.google.com/drive/folders/15mxb7DxTzEBrKtx5aJ_I5WGDjSWBmcUi">comic</a></td><td>pre-trained VToonify-D models and 101 comic style codes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="https://drive.google.com/drive/folders/1Hld7OeZqYBrg6r35IA_x4sNtt1abHUMU">pixar</a></td><td>pre-trained VToonify-D models and 122 pixar style codes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="https://drive.google.com/drive/folders/1LQGNMDEHM70nOhm3-xY228YpJNlPnf_s">illustration</a></td><td>pre-trained VToonify-D models and 156 illustration style codes</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td rowspan="5">Toonify</td><td><a href="https://drive.google.com/drive/folders/1FFtTVgiDKZ_InnwUJLDuA1wfghZp41nX">cartoon</a></td><td>pre-trained VToonify-T model</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="https://drive.google.com/drive/folders/1ReRxttV-macgV3epC61qg4TQ3FGAhGqG">caricature</a></td><td>pre-trained VToonify-T model</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="https://drive.google.com/drive/folders/1OXU95BOCCT0f6pGbwQ4yQ1EHb2LPd2yb">arcane</td></a><td>pre-trained VToonify-T model</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="https://drive.google.com/drive/folders/1KvawsOXzKgwDM3Z27sagO_KGE_Kc5GZS">comic</td></a><td>pre-trained VToonify-T model</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td><a href="https://drive.google.com/drive/folders/19N4ddcTXhXbTEayTbrFc533EktbhOXMz">pixar</td></a><td>pre-trained VToonify-T model</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<th colspan="2">Supporting model</th><th> </th>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2"><a href="https://drive.google.com/file/d/1NgI4mPkboYvYw3MWcdUaQhkr0OWgs9ej/view?usp=sharing">encoder.pt</a></td><td>Pixel2style2pixel encoder to map real faces into Z+ space of StyleGAN</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td colspan="2"><a href="https://drive.google.com/file/d/1jY0mTjVB8njDh6e0LP_2UxuRK3MnjoIR/view">faceparsing.pth</a></td><td>BiSeNet for face parsing from <a href="https://github.com/zllrunning/face-parsing.PyTorch">face-parsing.PyTorch</a></td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
The downloaded models are suggested to be arranged in [this folder structure](./checkpoint/).
|
||||
|
||||
The VToonify-D models are named with suffixes to indicate the settings, where
|
||||
- `_sXXX`: supports only one fixed style with `XXX` the index of this style.
|
||||
- `_s` without `XXX` means the model supports examplar-based style transfer
|
||||
- `_dXXX`: supports only a fixed style degree of `XXX`.
|
||||
- `_d` without `XXX` means the model supports style degrees ranging from 0 to 1
|
||||
- `_c`: supports color transfer.
|
||||
|
||||
### Style Transfer with VToonify-D
|
||||
|
||||
**✔ A quick start [HERE](./output#readme)**
|
||||
|
||||
Transfer a default cartoon style onto a default face image `./data/077436.jpg`:
|
||||
```python
|
||||
python style_transfer.py --scale_image
|
||||
```
|
||||
The results are saved in the folder `./output/`, where `077436_input.jpg` is the rescaled input image to fit VToonify (this image can serve as the input without `--scale_image`) and `077436_vtoonify_d.jpg` is the result.
|
||||
|
||||

|
||||
|
||||
Specify the content image and the model, control the style with the following options:
|
||||
- `--content`: path to the target face image or video
|
||||
- `--style_id`: the index of the style image (find the mapping between index and the style image [here](https://github.com/williamyang1991/DualStyleGAN/tree/main/doc_images)).
|
||||
- `--style_degree` (default: 0.5): adjust the degree of style.
|
||||
- `--color_transfer`(default: False): perform color transfer if loading a VToonify-Dsdc model.
|
||||
- `--ckpt`: path of the VToonify-D model. By default, a VToonify-Dsd trained on cartoon style is loaded.
|
||||
- `--exstyle_path`: path of the extrinsic style code. By default, codes in the same directory as `--ckpt` are loaded.
|
||||
- `--scale_image`: rescale the input image/video to fit VToonify (highly recommend).
|
||||
- `--padding` (default: 200, 200, 200, 200): left, right, top, bottom paddings to the eye center.
|
||||
|
||||
Here is an example of arcane style transfer:
|
||||
```python
|
||||
python style_transfer.py --content ./data/038648.jpg \
|
||||
--scale_image --style_id 77 --style_degree 0.5 \
|
||||
--ckpt ./checkpoint/vtoonify_d_arcane/vtoonify_s_d.pt \
|
||||
--padding 600 600 600 600 # use large padding to avoid cropping the image
|
||||
```
|
||||

|
||||
|
||||
|
||||
Specify `--video` to perform video toonification:
|
||||
```python
|
||||
python style_transfer.py --scale_image --content ./data/YOUR_VIDEO.mp4 --video
|
||||
```
|
||||
The above style control options (`--style_id`, `--style_degree`, `--color_transfer`) also work for videos.
|
||||
|
||||
|
||||
|
||||
### Style Transfer with VToonify-T
|
||||
|
||||
Specify `--backbone` as ''toonify'' to load and use a VToonify-T model.
|
||||
```python
|
||||
python style_transfer.py --content ./data/038648.jpg \
|
||||
--scale_image --backbone toonify \
|
||||
--ckpt ./checkpoint/vtoonify_t_arcane/vtoonify.pt \
|
||||
--padding 600 600 600 600 # use large padding to avoid cropping the image
|
||||
```
|
||||

|
||||
|
||||
In VToonify-T, `--style_id`, `--style_degree`, `--color_transfer`, `--exstyle_path` are not used.
|
||||
|
||||
As with VToonify-D, specify `--video` to perform video toonification.
|
||||
|
||||
<br/>
|
||||
|
||||
## (2) Training VToonify
|
||||
|
||||
Download the supporting models to the `./checkpoint/` folder and arrange them in [this folder structure](./checkpoint/):
|
||||
|
||||
| Model | Description |
|
||||
| :--- | :--- |
|
||||
| [stylegan2-ffhq-config-f.pt](https://drive.google.com/file/d/1EM87UquaoQmk17Q8d5kYIAHqu0dkYqdT/view) | StyleGAN model trained on FFHQ taken from [rosinality](https://github.com/rosinality/stylegan2-pytorch) |
|
||||
| [encoder.pt](https://drive.google.com/file/d/1NgI4mPkboYvYw3MWcdUaQhkr0OWgs9ej/view) | Pixel2style2pixel encoder that embeds FFHQ images into StyleGAN2 Z+ latent code |
|
||||
| [faceparsing.pth](https://drive.google.com/file/d/1jY0mTjVB8njDh6e0LP_2UxuRK3MnjoIR/view) | BiSeNet for face parsing from [face-parsing.PyTorch](https://github.com/zllrunning/face-parsing.PyTorch) |
|
||||
| [directions.npy](https://drive.google.com/file/d/1HbjmOIOfxqTAVScZOI2m7_tPgMPnc0uM/view) | Editing vectors taken from [LowRankGAN](https://github.com/zhujiapeng/LowRankGAN) for editing face attributes |
|
||||
| [Toonify](https://drive.google.com/drive/folders/1GZQ6Gs5AzJq9lUL-ldIQexi0JYPKNy8b) \| [DualStyleGAN](https://drive.google.com/drive/folders/1GZQ6Gs5AzJq9lUL-ldIQexi0JYPKNy8b) | pre-trained stylegan-based toonification models|
|
||||
|
||||
To customize your own style, you may need to train a new Toonify/DualStyleGAN model following [here](https://github.com/williamyang1991/DualStyleGAN#3-training-dualstylegan).
|
||||
|
||||
### Train VToonify-D
|
||||
|
||||
Given the supporting models arranged in the [default folder structure](./checkpoint/), we can simply pre-train the encoder and train the whole VToonify-D by running
|
||||
```python
|
||||
# for pre-training the encoder
|
||||
python -m torch.distributed.launch --nproc_per_node=N_GPU --master_port=PORT train_vtoonify_d.py \
|
||||
--iter ITERATIONS --stylegan_path DUALSTYLEGAN_PATH --exstyle_path EXSTYLE_CODE_PATH \
|
||||
--batch BATCH_SIZE --name SAVE_NAME --pretrain
|
||||
# for training VToonify-D given the pre-trained encoder
|
||||
python -m torch.distributed.launch --nproc_per_node=N_GPU --master_port=PORT train_vtoonify_d.py \
|
||||
--iter ITERATIONS --stylegan_path DUALSTYLEGAN_PATH --exstyle_path EXSTYLE_CODE_PATH \
|
||||
--batch BATCH_SIZE --name SAVE_NAME # + ADDITIONAL STYLE CONTROL OPTIONS
|
||||
```
|
||||
The models and the intermediate results are saved in `./checkpoint/SAVE_NAME/` and `./log/SAVE_NAME/`, respectively.
|
||||
|
||||
VToonify-D provides the following STYLE CONTROL OPTIONS:
|
||||
- `--fix_degree`: if specified, model is trained with a fixed style degree (no degree adjustment)
|
||||
- `--fix_style`: if specified, model is trained with a fixed style image (no examplar-based style transfer)
|
||||
- `--fix_color`: if specified, model is trained with color preservation (no color transfer)
|
||||
- `--style_id`: the index of the style image (find the mapping between index and the style image [here](https://github.com/williamyang1991/DualStyleGAN/tree/main/doc_images)).
|
||||
- `--style_degree` (default: 0.5): the degree of style.
|
||||
|
||||
Here is an example to reproduce the VToonify-Dsd on Cartoon style and the VToonify-D specialized for a mild toonification on the 26th cartoon style:
|
||||
```python
|
||||
python -m torch.distributed.launch --nproc_per_node=8 --master_port=8765 train_vtoonify_d.py \
|
||||
--iter 30000 --stylegan_path ./checkpoint/cartoon/generator.pt --exstyle_path ./checkpoint/cartoon/refined_exstyle_code.npy \
|
||||
--batch 1 --name vtoonify_d_cartoon --pretrain
|
||||
python -m torch.distributed.launch --nproc_per_node=8 --master_port=8765 train_vtoonify_d.py \
|
||||
--iter 2000 --stylegan_path ./checkpoint/cartoon/generator.pt --exstyle_path ./checkpoint/cartoon/refined_exstyle_code.npy \
|
||||
--batch 4 --name vtoonify_d_cartoon --fix_color
|
||||
python -m torch.distributed.launch --nproc_per_node=8 --master_port=8765 train_vtoonify_d.py \
|
||||
--iter 2000 --stylegan_path ./checkpoint/cartoon/generator.pt --exstyle_path ./checkpoint/cartoon/refined_exstyle_code.npy \
|
||||
--batch 4 --name vtoonify_d_cartoon --fix_color --fix_degree --style_degree 0.5 --fix_style --style_id 26
|
||||
```
|
||||
Note that the pre-trained encoder is shared by different STYLE CONTROL OPTIONS. VToonify-D only needs to pre-train the encoder once for each DualStyleGAN model.
|
||||
Eight GPUs are not necessary, one can train the model with a single GPU with larger `--iter`.
|
||||
|
||||
**Tips**: [how to find an ideal model] we can first train a versatile model VToonify-Dsd,
|
||||
and navigate around different styles and degrees. After finding the ideal setting, we can then train the model specialized in that setting for high-quality stylization.
|
||||
|
||||
### Train VToonify-T
|
||||
|
||||
The training of VToonify-T is similar to VToonify-D,
|
||||
```python
|
||||
# for pre-training the encoder
|
||||
python -m torch.distributed.launch --nproc_per_node=N_GPU --master_port=PORT train_vtoonify_t.py \
|
||||
--iter ITERATIONS --finetunegan_path FINETUNED_MODEL_PATH \
|
||||
--batch BATCH_SIZE --name SAVE_NAME --pretrain # + ADDITIONAL STYLE CONTROL OPTION
|
||||
# for training VToonify-T given the pre-trained encoder
|
||||
python -m torch.distributed.launch --nproc_per_node=N_GPU --master_port=PORT train_vtoonify_t.py \
|
||||
--iter ITERATIONS --finetunegan_path FINETUNED_MODEL_PATH \
|
||||
--batch BATCH_SIZE --name SAVE_NAME # + ADDITIONAL STYLE CONTROL OPTION
|
||||
```
|
||||
VToonify-T only has one STYLE CONTROL OPTION:
|
||||
- `--weight` (default: 1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,0): 18 numbers indicate how the 18 layers of the ffhq stylegan model and the finetuned model are blended to obtain the final Toonify model. [Here](https://github.com/williamyang1991/VToonify/blob/edfd68e96eb0c0ab4c31628feef1b667e890a2cd/train_vtoonify_t.py#L30) is the `--weight` we use in the paper for different styles. Please refer to [toonify](https://github.com/justinpinkney/toonify) for the details.
|
||||
|
||||
Here is an example to reproduce the VToonify-T model on Arcane style:
|
||||
```python
|
||||
python -m torch.distributed.launch --nproc_per_node=8 --master_port=8765 train_vtoonify_t.py \
|
||||
--iter 30000 --finetunegan_path ./checkpoint/arcane/finetune-000600.pt \
|
||||
--batch 1 --name vtoonify_t_arcane --pretrain --weight 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 1 1 1 1 1 1 1 1 1 1
|
||||
python -m torch.distributed.launch --nproc_per_node=8 --master_port=8765 train_vtoonify_t.py \
|
||||
--iter 2000 --finetunegan_path ./checkpoint/arcane/finetune-000600.pt \
|
||||
--batch 4 --name vtoonify_t_arcane --weight 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 1 1 1 1 1 1 1 1 1 1
|
||||
```
|
||||
|
||||
|
||||
<br/>
|
||||
|
||||
## (3) Results
|
||||
|
||||
Our framework is compatible with existing StyleGAN-based image toonification models to extend them to video toonification, and inherits their appealing features for flexible style control. With DualStyleGAN as the backbone, our VToonify is able to transfer the style of various reference images and adjust the style degree in one model.
|
||||
|
||||
https://user-images.githubusercontent.com/18130694/189510094-4378caca-e8d9-48e1-9e5d-c8ec038e4bc5.mp4
|
||||
|
||||
Here are the color interpolated results of VToonify-D and VToonify-Dc on Arcane, Pixar and Comic styles.
|
||||
|
||||
https://user-images.githubusercontent.com/18130694/189510233-b4e3b4f7-5a37-4e0c-9821-a8049ce5f781.mp4
|
||||
|
||||
## Citation
|
||||
|
||||
If you find this work useful for your research, please consider citing our paper:
|
||||
|
||||
```bibtex
|
||||
@article{yang2022Vtoonify,
|
||||
title={VToonify: Controllable High-Resolution Portrait Video Style Transfer},
|
||||
author={Yang, Shuai and Jiang, Liming and Liu, Ziwei and Loy, Chen Change},
|
||||
journal={ACM Transactions on Graphics (TOG)},
|
||||
volume={41},
|
||||
number={6},
|
||||
articleno={203},
|
||||
pages={1--15},
|
||||
year={2022},
|
||||
publisher={ACM New York, NY, USA},
|
||||
doi={10.1145/3550454.3555437},
|
||||
}
|
||||
```
|
||||
|
||||
## Acknowledgments
|
||||
|
||||
The code is mainly developed based on [stylegan2-pytorch](https://github.com/rosinality/stylegan2-pytorch), [pixel2style2pixel](https://github.com/eladrich/pixel2style2pixel) and [DualStyleGAN](https://github.com/williamyang1991/DualStyleGAN).
|
||||
@@ -0,0 +1,13 @@
|
||||
numpy==1.21.0
|
||||
scipy==1.7.0
|
||||
tqdm==4.61.2
|
||||
certifi==2021.10.8
|
||||
setuptools>=49.6.0
|
||||
faiss-gpu==1.7.1
|
||||
scikit-image==0.18.1
|
||||
opencv-python==4.5.3.56
|
||||
dlib==19.21.0
|
||||
matplotlib==3.4.2
|
||||
pillow==8.3.1
|
||||
cmake==3.21.0
|
||||
ninja==1.10.2
|
||||
@@ -0,0 +1,36 @@
|
||||
name: obfuscation_platform_p38
|
||||
channels:
|
||||
- pytorch
|
||||
- conda-forge
|
||||
- defaults
|
||||
dependencies:
|
||||
- _libgcc_mutex=0.1=conda_forge
|
||||
- ca-certificates=2022.2.1=h06a4308_0
|
||||
- certifi=2021.10.8=py38h06a4308_2
|
||||
- faiss=1.7.1=py38h7b17aaf_0_cpu
|
||||
- libedit=3.1.20191231=he28a2e2_2
|
||||
- libfaiss=1.7.1=hb573701_0_cpu
|
||||
- libfaiss-avx2=1.7.1=h1234567_0_cpu
|
||||
- libffi=3.2.1=he1b5a44_1007
|
||||
- libgcc-ng=9.3.0=h2828fa1_19
|
||||
- libstdcxx-ng=9.3.0=h6de172a_19
|
||||
- matplotlib-base=3.3.4=py38h62a2d02_0
|
||||
- pillow=8.3.1=py38h2c7a002_0
|
||||
- pip=21.1.3=pyhd8ed1ab_0
|
||||
- python=3.8.3=cpython_he5300dc_0
|
||||
- python-lmdb=1.2.1=py38h2531618_1
|
||||
- pytorch=1.7.1=py3.8_cuda10.1.243_cudnn7.6.3_0
|
||||
- setuptools=49.6.0=py38h578d9bd_3
|
||||
- scikit-image=0.18.1=py38ha9443f7_0
|
||||
- torchaudio=0.7.2=py38
|
||||
- torchvision=0.8.2=py38_cu101
|
||||
- pip:
|
||||
- cmake==3.21.0
|
||||
- dlib==19.21.0
|
||||
- matplotlib==3.4.2
|
||||
- ninja==1.10.2
|
||||
- numpy==1.21.0
|
||||
- opencv-python==4.5.3.56
|
||||
- scipy==1.7.0
|
||||
- tqdm==4.61.2
|
||||
- wget==3.2
|
||||
@@ -0,0 +1,35 @@
|
||||
channels:
|
||||
- pytorch
|
||||
- conda-forge
|
||||
- defaults
|
||||
dependencies:
|
||||
- _libgcc_mutex=0.1=conda_forge
|
||||
- ca-certificates=2022.2.1=h06a4308_0
|
||||
- certifi=2021.10.8=py38h06a4308_2
|
||||
- faiss=1.7.1=py38h7b17aaf_0_cpu
|
||||
- libedit=3.1.20191231=he28a2e2_2
|
||||
- libfaiss=1.7.1=hb573701_0_cpu
|
||||
- libfaiss-avx2=1.7.1=h1234567_0_cpu
|
||||
- libffi=3.2.1=he1b5a44_1007
|
||||
- libgcc-ng=9.3.0=h2828fa1_19
|
||||
- libstdcxx-ng=9.3.0=h6de172a_19
|
||||
- matplotlib-base=3.3.4=py38h62a2d02_0
|
||||
- pillow=8.3.1=py38h2c7a002_0
|
||||
- pip=21.1.3=pyhd8ed1ab_0
|
||||
- python=3.8.3=cpython_he5300dc_0
|
||||
- python-lmdb=1.2.1=py38h2531618_1
|
||||
- pytorch=1.7.1=py3.8_cuda10.1.243_cudnn7.6.3_0
|
||||
- setuptools=49.6.0=py38h578d9bd_3
|
||||
- scikit-image=0.18.1=py38ha9443f7_0
|
||||
- torchaudio=0.7.2=py38
|
||||
- torchvision=0.8.2=py38_cu101
|
||||
- pip:
|
||||
- cmake==3.21.0
|
||||
- dlib==19.21.0
|
||||
- matplotlib==3.4.2
|
||||
- ninja==1.10.2
|
||||
- numpy==1.21.0
|
||||
- opencv-python==4.5.3.56
|
||||
- scipy==1.7.0
|
||||
- tqdm==4.61.2
|
||||
- wget==3.2
|
||||
@@ -0,0 +1,279 @@
|
||||
import os
|
||||
#os.environ['CUDA_VISIBLE_DEVICES'] = "0"
|
||||
import argparse
|
||||
import numpy as np
|
||||
import cv2
|
||||
import dlib
|
||||
import torch
|
||||
from torchvision import transforms
|
||||
import torch.nn.functional as F
|
||||
from tqdm import tqdm
|
||||
from model.vtoonify import VToonify
|
||||
from model.bisenet.model import BiSeNet
|
||||
from model.encoder.align_all_parallel import align_face
|
||||
from util import save_image, load_image, visualize, load_psp_standalone, get_video_crop_parameter, tensor2cv2
|
||||
|
||||
from fastapi import FastAPI, HTTPException
|
||||
|
||||
|
||||
class VTOONIFY:
|
||||
def __init__(self, checkpoint_path, config_path, fake_face_path):
|
||||
self.swap_indices = [2, 3, 9, 11, 15] #Indices of face regions to swap
|
||||
self.fake_face = resize(cv2.imread(fake_face_path), (256, 256))[..., :3]
|
||||
self.reconstruction_module, self.segmentation_module = load_checkpoints(config_path, checkpoint_path, blend_scale=1, cpu=False)
|
||||
|
||||
def obfuscate(self, face_roi_img_bgr: np.ndarray) -> np.ndarray:
|
||||
return obfuscate(swap_index=self.swap_indices,
|
||||
source_image=self.fake_face,
|
||||
target_image=face_roi_img_bgr,
|
||||
reconstruction_module=self.reconstruction_module,
|
||||
segmentation_module=self.segmentation_module)
|
||||
|
||||
|
||||
app = FastAPI()
|
||||
if torch.cuda.is_available():
|
||||
print("torch version: ", torch.__version__, "cuda: ", torch.version.cuda)
|
||||
vtoonify = None
|
||||
image_processing_path = "C:/Users/bijan/Desktop/obfuscation_platform/project/models/vtoonify/image_cache/"
|
||||
|
||||
@app.get("/init")
|
||||
def init():
|
||||
try:
|
||||
print("initiating vtoonify")
|
||||
|
||||
global vtoonify
|
||||
vtoonify = VTOONIFY()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
raise HTTPException(500, detail=str(e))
|
||||
|
||||
@app.get("/obfuscate")
|
||||
def obfuscate_api():
|
||||
img = cv2.imread(os.path.join(image_processing_path, "face.jpg"), cv2.IMREAD_UNCHANGED)
|
||||
if img is None:
|
||||
raise HTTPException(500, f"cv2 failed to read image at {image_processing_path}")
|
||||
global vtoonify
|
||||
obfusacted_img = vtoonify.obfuscate(img)
|
||||
cv2.imwrite(os.path.join(image_processing_path, "obfuscated_face.jpg"), obfusacted_img)
|
||||
|
||||
@app.get("/health")
|
||||
def health(): return {"ok": True}
|
||||
|
||||
|
||||
|
||||
class TestOptions():
|
||||
def __init__(self):
|
||||
|
||||
self.parser = argparse.ArgumentParser(description="Style Transfer")
|
||||
self.parser.add_argument("--content", type=str, default='./data/077436.jpg', help="path of the content image/video")
|
||||
self.parser.add_argument("--style_id", type=int, default=26, help="the id of the style image")
|
||||
self.parser.add_argument("--style_degree", type=float, default=0.5, help="style degree for VToonify-D")
|
||||
self.parser.add_argument("--color_transfer", action="store_true", help="transfer the color of the style")
|
||||
self.parser.add_argument("--ckpt", type=str, default='./checkpoint/vtoonify_d_cartoon/vtoonify_s_d.pt', help="path of the saved model")
|
||||
self.parser.add_argument("--output_path", type=str, default='./output/', help="path of the output images")
|
||||
self.parser.add_argument("--scale_image", action="store_true", help="resize and crop the image to best fit the model")
|
||||
self.parser.add_argument("--style_encoder_path", type=str, default='./checkpoint/encoder.pt', help="path of the style encoder")
|
||||
self.parser.add_argument("--exstyle_path", type=str, default=None, help="path of the extrinsic style code")
|
||||
self.parser.add_argument("--faceparsing_path", type=str, default='./checkpoint/faceparsing.pth', help="path of the face parsing model")
|
||||
self.parser.add_argument("--video", action="store_true", help="if true, video stylization; if false, image stylization")
|
||||
self.parser.add_argument("--cpu", action="store_true", help="if true, only use cpu")
|
||||
self.parser.add_argument("--backbone", type=str, default='dualstylegan', help="dualstylegan | toonify")
|
||||
self.parser.add_argument("--padding", type=int, nargs=4, default=[200,200,200,200], help="left, right, top, bottom paddings to the face center")
|
||||
self.parser.add_argument("--batch_size", type=int, default=4, help="batch size of frames when processing video")
|
||||
self.parser.add_argument("--parsing_map_path", type=str, default=None, help="path of the refined parsing map of the target video")
|
||||
|
||||
def parse(self):
|
||||
self.opt = self.parser.parse_args()
|
||||
if self.opt.exstyle_path is None:
|
||||
self.opt.exstyle_path = os.path.join(os.path.dirname(self.opt.ckpt), 'exstyle_code.npy')
|
||||
args = vars(self.opt)
|
||||
print('Load options')
|
||||
for name, value in sorted(args.items()):
|
||||
print('%s: %s' % (str(name), str(value)))
|
||||
return self.opt
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
parser = TestOptions()
|
||||
args = parser.parse()
|
||||
print('*'*98)
|
||||
|
||||
|
||||
device = "cpu" if args.cpu else "cuda"
|
||||
|
||||
transform = transforms.Compose([
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5,0.5,0.5]),
|
||||
])
|
||||
|
||||
vtoonify = VToonify(backbone = args.backbone)
|
||||
vtoonify.load_state_dict(torch.load(args.ckpt, map_location=lambda storage, loc: storage)['g_ema'])
|
||||
vtoonify.to(device)
|
||||
|
||||
parsingpredictor = BiSeNet(n_classes=19)
|
||||
parsingpredictor.load_state_dict(torch.load(args.faceparsing_path, map_location=lambda storage, loc: storage))
|
||||
parsingpredictor.to(device).eval()
|
||||
|
||||
modelname = './checkpoint/shape_predictor_68_face_landmarks.dat'
|
||||
if not os.path.exists(modelname):
|
||||
import wget, bz2
|
||||
wget.download('http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2', modelname+'.bz2')
|
||||
zipfile = bz2.BZ2File(modelname+'.bz2')
|
||||
data = zipfile.read()
|
||||
open(modelname, 'wb').write(data)
|
||||
landmarkpredictor = dlib.shape_predictor(modelname)
|
||||
|
||||
pspencoder = load_psp_standalone(args.style_encoder_path, device)
|
||||
|
||||
if args.backbone == 'dualstylegan':
|
||||
exstyles = np.load(args.exstyle_path, allow_pickle='TRUE').item()
|
||||
stylename = list(exstyles.keys())[args.style_id]
|
||||
exstyle = torch.tensor(exstyles[stylename]).to(device)
|
||||
with torch.no_grad():
|
||||
exstyle = vtoonify.zplus2wplus(exstyle)
|
||||
|
||||
if args.video and args.parsing_map_path is not None:
|
||||
x_p_hat = torch.tensor(np.load(args.parsing_map_path))
|
||||
|
||||
print('Load models successfully!')
|
||||
|
||||
|
||||
filename = args.content
|
||||
basename = os.path.basename(filename).split('.')[0]
|
||||
scale = 1
|
||||
kernel_1d = np.array([[0.125],[0.375],[0.375],[0.125]])
|
||||
print('Processing ' + os.path.basename(filename) + ' with vtoonify_' + args.backbone[0])
|
||||
if args.video:
|
||||
cropname = os.path.join(args.output_path, basename + '_input.mp4')
|
||||
savename = os.path.join(args.output_path, basename + '_vtoonify_' + args.backbone[0] + '.mp4')
|
||||
|
||||
video_cap = cv2.VideoCapture(filename)
|
||||
num = int(video_cap.get(7))
|
||||
|
||||
first_valid_frame = True
|
||||
batch_frames = []
|
||||
for i in tqdm(range(num)):
|
||||
success, frame = video_cap.read()
|
||||
if success == False:
|
||||
assert('load video frames error')
|
||||
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||
# We proprocess the video by detecting the face in the first frame,
|
||||
# and resizing the frame so that the eye distance is 64 pixels.
|
||||
# Centered on the eyes, we crop the first frame to almost 400x400 (based on args.padding).
|
||||
# All other frames use the same resizing and cropping parameters as the first frame.
|
||||
if first_valid_frame:
|
||||
if args.scale_image:
|
||||
paras = get_video_crop_parameter(frame, landmarkpredictor, args.padding)
|
||||
if paras is None:
|
||||
continue
|
||||
h,w,top,bottom,left,right,scale = paras
|
||||
H, W = int(bottom-top), int(right-left)
|
||||
# for HR video, we apply gaussian blur to the frames to avoid flickers caused by bilinear downsampling
|
||||
# this can also prevent over-sharp stylization results.
|
||||
if scale <= 0.75:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
if scale <= 0.375:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
|
||||
else:
|
||||
H, W = frame.shape[0], frame.shape[1]
|
||||
|
||||
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
||||
videoWriter = cv2.VideoWriter(cropname, fourcc, video_cap.get(5), (W, H))
|
||||
videoWriter2 = cv2.VideoWriter(savename, fourcc, video_cap.get(5), (4*W, 4*H))
|
||||
|
||||
# For each video, we detect and align the face in the first frame for pSp to obtain the style code.
|
||||
# This style code is used for all other frames.
|
||||
with torch.no_grad():
|
||||
I = align_face(frame, landmarkpredictor)
|
||||
I = transform(I).unsqueeze(dim=0).to(device)
|
||||
s_w = pspencoder(I)
|
||||
s_w = vtoonify.zplus2wplus(s_w)
|
||||
if vtoonify.backbone == 'dualstylegan':
|
||||
if args.color_transfer:
|
||||
s_w = exstyle
|
||||
else:
|
||||
s_w[:,:7] = exstyle[:,:7]
|
||||
first_valid_frame = False
|
||||
elif args.scale_image:
|
||||
if scale <= 0.75:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
if scale <= 0.375:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
|
||||
|
||||
videoWriter.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
|
||||
|
||||
batch_frames += [transform(frame).unsqueeze(dim=0).to(device)]
|
||||
|
||||
if len(batch_frames) == args.batch_size or (i+1) == num:
|
||||
x = torch.cat(batch_frames, dim=0)
|
||||
batch_frames = []
|
||||
with torch.no_grad():
|
||||
# parsing network works best on 512x512 images, so we predict parsing maps on upsmapled frames
|
||||
# followed by downsampling the parsing maps
|
||||
if args.video and args.parsing_map_path is not None:
|
||||
x_p = x_p_hat[i+1-x.size(0):i+1].to(device)
|
||||
else:
|
||||
x_p = F.interpolate(parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
|
||||
scale_factor=0.5, recompute_scale_factor=False).detach()
|
||||
# we give parsing maps lower weight (1/16)
|
||||
inputs = torch.cat((x, x_p/16.), dim=1)
|
||||
# d_s has no effect when backbone is toonify
|
||||
y_tilde = vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s = args.style_degree)
|
||||
y_tilde = torch.clamp(y_tilde, -1, 1)
|
||||
for k in range(y_tilde.size(0)):
|
||||
videoWriter2.write(tensor2cv2(y_tilde[k].cpu()))
|
||||
|
||||
videoWriter.release()
|
||||
videoWriter2.release()
|
||||
video_cap.release()
|
||||
|
||||
|
||||
else:
|
||||
cropname = os.path.join(args.output_path, basename + '_input.jpg')
|
||||
savename = os.path.join(args.output_path, basename + '_vtoonify_' + args.backbone[0] + '.jpg')
|
||||
|
||||
frame = cv2.imread(filename)
|
||||
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
|
||||
|
||||
# We detect the face in the image, and resize the image so that the eye distance is 64 pixels.
|
||||
# Centered on the eyes, we crop the image to almost 400x400 (based on args.padding).
|
||||
if args.scale_image:
|
||||
paras = get_video_crop_parameter(frame, landmarkpredictor, args.padding)
|
||||
if paras is not None:
|
||||
h,w,top,bottom,left,right,scale = paras
|
||||
H, W = int(bottom-top), int(right-left)
|
||||
# for HR image, we apply gaussian blur to it to avoid over-sharp stylization results
|
||||
if scale <= 0.75:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
if scale <= 0.375:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
|
||||
|
||||
with torch.no_grad():
|
||||
I = align_face(frame, landmarkpredictor)
|
||||
I = transform(I).unsqueeze(dim=0).to(device)
|
||||
s_w = pspencoder(I)
|
||||
s_w = vtoonify.zplus2wplus(s_w)
|
||||
if vtoonify.backbone == 'dualstylegan':
|
||||
if args.color_transfer:
|
||||
s_w = exstyle
|
||||
else:
|
||||
s_w[:,:7] = exstyle[:,:7]
|
||||
|
||||
x = transform(frame).unsqueeze(dim=0).to(device)
|
||||
# parsing network works best on 512x512 images, so we predict parsing maps on upsmapled frames
|
||||
# followed by downsampling the parsing maps
|
||||
x_p = F.interpolate(parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
|
||||
scale_factor=0.5, recompute_scale_factor=False).detach()
|
||||
# we give parsing maps lower weight (1/16)
|
||||
inputs = torch.cat((x, x_p/16.), dim=1)
|
||||
# d_s has no effect when backbone is toonify
|
||||
y_tilde = vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s = args.style_degree)
|
||||
y_tilde = torch.clamp(y_tilde, -1, 1)
|
||||
|
||||
cv2.imwrite(cropname, cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
|
||||
save_image(y_tilde[0].cpu(), savename)
|
||||
|
||||
print('Transfer style successfully!')
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
|
After Width: | Height: | Size: 31 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 252 KiB |
@@ -0,0 +1,65 @@
|
||||
Here are the examples to reproduce the toonification results in this folder.
|
||||
|
||||
#### 529_vtoonify_d.mp4
|
||||
https://user-images.githubusercontent.com/18130694/189574934-85954bd6-0e2d-4568-9687-df7a8776ace5.mp4
|
||||
|
||||
```python
|
||||
python style_transfer.py --scale_image --content ./data/529.mp4 --video
|
||||
```
|
||||
<br/>
|
||||
|
||||
#### 077436_vtoonify_d.jpg
|
||||
<img src="./077436_input.jpg" width=25%> <img src="./077436_vtoonify_d.jpg" width=25%>
|
||||
|
||||
```python
|
||||
python style_transfer.py --scale_image
|
||||
```
|
||||
<br/>
|
||||
|
||||
#### 081680_vtoonify_d.jpg
|
||||
<img src="./081680_input.jpg" width=25%> <img src="./081680_vtoonify_d.jpg" width=25%>
|
||||
|
||||
```python
|
||||
python style_transfer.py --scale_image --content ./data/081680.jpg \
|
||||
--ckpt ./checkpoint/vtoonify_d_cartoon/vtoonify_s026_d0.5.pt # specialized model has better performance
|
||||
```
|
||||
<br/>
|
||||
|
||||
#### 038648_vtoonify_d.jpg
|
||||
<img src="./038648_input.jpg" width=25%> <img src="./038648_vtoonify_d.jpg" width=25%>
|
||||
|
||||
```python
|
||||
python style_transfer.py --content ./data/038648.jpg \
|
||||
--scale_image --padding 600 600 600 600 --style_id 77 \
|
||||
--ckpt ./checkpoint/vtoonify_d_arcane/vtoonify_s_d.pt
|
||||
```
|
||||
<br/>
|
||||
|
||||
#### 038648_vtoonify_t.jpg
|
||||
<img src="./038648_input.jpg" width=25%> <img src="./038648_vtoonify_t.jpg" width=25%>
|
||||
|
||||
```python
|
||||
python style_transfer.py --content ./data/038648.jpg \
|
||||
--scale_image --padding 600 600 600 600 --backbone toonify \
|
||||
--ckpt ./checkpoint/vtoonify_t_arcane/vtoonify.pt
|
||||
```
|
||||
<br/>
|
||||
|
||||
#### 077559_vtoonify_d.jpg
|
||||
<img src="./077559_input.jpg" width=25%> <img src="./077559_vtoonify_d.jpg" width=25%>
|
||||
|
||||
```python
|
||||
python style_transfer.py --content ./data/077559.jpg \
|
||||
--scale_image --padding 600 600 600 600 --style_id 77 \
|
||||
--ckpt ./checkpoint/vtoonify_d_arcane/vtoonify_s_d.pt
|
||||
```
|
||||
<br/>
|
||||
|
||||
#### 077559_vtoonify_t.jpg
|
||||
<img src="./077559_input.jpg" width=25%> <img src="./077559_vtoonify_t.jpg" width=25%>
|
||||
|
||||
```python
|
||||
python style_transfer.py --content ./data/077559.jpg \
|
||||
--scale_image --padding 600 600 600 600 --backbone toonify \
|
||||
--ckpt ./checkpoint/vtoonify_t_arcane/vtoonify.pt
|
||||
```
|
||||
@@ -0,0 +1,172 @@
|
||||
import os
|
||||
#os.environ['CUDA_VISIBLE_DEVICES'] = "0"
|
||||
import numpy as np
|
||||
import cv2
|
||||
import math
|
||||
import argparse
|
||||
from tqdm import tqdm
|
||||
import torch
|
||||
from torch import nn
|
||||
from torchvision import transforms
|
||||
import torch.nn.functional as F
|
||||
from model.raft.core.raft import RAFT
|
||||
from model.raft.core.utils.utils import InputPadder
|
||||
from model.bisenet.model import BiSeNet
|
||||
from model.stylegan.model import Downsample
|
||||
|
||||
class Options():
|
||||
def __init__(self):
|
||||
|
||||
self.parser = argparse.ArgumentParser(description="Smooth Parsing Maps")
|
||||
self.parser.add_argument("--window_size", type=int, default=5, help="temporal window size")
|
||||
|
||||
self.parser.add_argument("--faceparsing_path", type=str, default='./checkpoint/faceparsing.pth', help="path of the face parsing model")
|
||||
self.parser.add_argument("--raft_path", type=str, default='./checkpoint/raft-things.pth', help="path of the RAFT model")
|
||||
|
||||
self.parser.add_argument("--video_path", type=str, help="path of the target video")
|
||||
self.parser.add_argument("--output_path", type=str, default='./output/', help="path of the output parsing maps")
|
||||
|
||||
def parse(self):
|
||||
self.opt = self.parser.parse_args()
|
||||
args = vars(self.opt)
|
||||
print('Load options')
|
||||
for name, value in sorted(args.items()):
|
||||
print('%s: %s' % (str(name), str(value)))
|
||||
return self.opt
|
||||
|
||||
# from RAFT
|
||||
def warp(x, flo):
|
||||
"""
|
||||
warp an image/tensor (im2) back to im1, according to the optical flow
|
||||
x: [B, C, H, W] (im2)
|
||||
flo: [B, 2, H, W] flow
|
||||
"""
|
||||
B, C, H, W = x.size()
|
||||
# mesh grid
|
||||
xx = torch.arange(0, W).view(1,-1).repeat(H,1)
|
||||
yy = torch.arange(0, H).view(-1,1).repeat(1,W)
|
||||
xx = xx.view(1,1,H,W).repeat(B,1,1,1)
|
||||
yy = yy.view(1,1,H,W).repeat(B,1,1,1)
|
||||
grid = torch.cat((xx,yy),1).float()
|
||||
|
||||
|
||||
#x = x.cuda()
|
||||
grid = grid.cuda()
|
||||
vgrid = grid + flo # B,2,H,W
|
||||
|
||||
# scale grid to [-1,1]
|
||||
##2019 code
|
||||
vgrid[:,0,:,:] = 2.0*vgrid[:,0,:,:].clone()/max(W-1,1)-1.0
|
||||
vgrid[:,1,:,:] = 2.0*vgrid[:,1,:,:].clone()/max(H-1,1)-1.0
|
||||
|
||||
vgrid = vgrid.permute(0,2,3,1)
|
||||
output = nn.functional.grid_sample(x, vgrid,align_corners=True)
|
||||
mask = torch.autograd.Variable(torch.ones(x.size())).cuda()
|
||||
mask = nn.functional.grid_sample(mask, vgrid,align_corners=True)
|
||||
|
||||
##2019 author
|
||||
mask[mask<0.9999] = 0
|
||||
mask[mask>0] = 1
|
||||
|
||||
##2019 code
|
||||
# mask = torch.floor(torch.clamp(mask, 0 ,1))
|
||||
|
||||
return output*mask, mask
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
parser = Options()
|
||||
args = parser.parse()
|
||||
print('*'*98)
|
||||
|
||||
|
||||
device = "cuda"
|
||||
|
||||
transform = transforms.Compose([
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5,0.5,0.5]),
|
||||
])
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--model', help="restore checkpoint")
|
||||
parser.add_argument('--small', action='store_true', help='use small model')
|
||||
parser.add_argument('--mixed_precision', action='store_true', help='use mixed precision')
|
||||
parser.add_argument('--alternate_corr', action='store_true', help='use efficent correlation implementation')
|
||||
|
||||
raft_model = torch.nn.DataParallel(RAFT(parser.parse_args(['--model', args.raft_path])))
|
||||
raft_model.load_state_dict(torch.load(args.raft_path))
|
||||
|
||||
raft_model = raft_model.module
|
||||
raft_model.to(device)
|
||||
raft_model.eval()
|
||||
|
||||
parsingpredictor = BiSeNet(n_classes=19)
|
||||
parsingpredictor.load_state_dict(torch.load(args.faceparsing_path, map_location=lambda storage, loc: storage))
|
||||
parsingpredictor.to(device).eval()
|
||||
|
||||
down = Downsample(kernel=[1, 3, 3, 1], factor=2).to(device).eval()
|
||||
|
||||
print('Load models successfully!')
|
||||
|
||||
window = args.window_size
|
||||
|
||||
video_cap = cv2.VideoCapture(args.video_path)
|
||||
num = int(video_cap.get(7))
|
||||
|
||||
Is = []
|
||||
for i in range(num):
|
||||
success, frame = video_cap.read()
|
||||
if success == False:
|
||||
break
|
||||
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||
with torch.no_grad():
|
||||
Is += [transform(frame).unsqueeze(dim=0).cpu()]
|
||||
video_cap.release()
|
||||
|
||||
# enlarge frames for more accurate parsing maps and optical flows
|
||||
Is = F.upsample(torch.cat(Is, dim=0), scale_factor=2, mode='bilinear')
|
||||
Is_ = torch.cat((Is[0:window], Is, Is[-window:]), dim=0)
|
||||
|
||||
print('Load video with %d frames successfully!'%(len(Is)))
|
||||
|
||||
Ps = []
|
||||
for i in tqdm(range(len(Is))):
|
||||
with torch.no_grad():
|
||||
Ps += [parsingpredictor(2*Is[i:i+1].to(device))[0].detach().cpu()]
|
||||
Ps = torch.cat(Ps, dim=0)
|
||||
Ps_ = torch.cat((Ps[0:window], Ps, Ps[-window:]), dim=0)
|
||||
|
||||
print('Predict parsing maps successfully!')
|
||||
|
||||
|
||||
# temporal weights of the (2*args.window_size+1) frames
|
||||
wt = torch.exp(-(torch.arange(2*window+1).float()-window)**2/(2*((window+0.5)**2))).reshape(2*window+1,1,1,1).to(device)
|
||||
|
||||
parse = []
|
||||
for ii in tqdm(range(len(Is))):
|
||||
i = ii + window
|
||||
image2 = Is_[i-window:i+window+1].to(device)
|
||||
image1 = Is_[i].repeat(2*window+1,1,1,1).to(device)
|
||||
padder = InputPadder(image1.shape)
|
||||
image1, image2 = padder.pad(image1, image2)
|
||||
with torch.no_grad():
|
||||
flow_low, flow_up = raft_model((image1+1)*255.0/2, (image2+1)*255.0/2, iters=20, test_mode=True)
|
||||
output, mask = warp(torch.cat((image2, Ps_[i-window:i+window+1].to(device)), dim=1), flow_up)
|
||||
aligned_Is = output[:,0:3].detach()
|
||||
aligned_Ps = output[:,3:].detach()
|
||||
# the spatial weight
|
||||
ws = torch.exp(-((aligned_Is-image1)**2).mean(dim=1, keepdims=True)/(2*(0.2**2))) * mask[:,0:1]
|
||||
aligned_Ps[window] = Ps_[i].to(device)
|
||||
# the weight between i and i shoud be 1.0
|
||||
ws[window,:,:,:] = 1.0
|
||||
weights = ws*wt
|
||||
weights = weights / weights.sum(dim=(0), keepdims=True)
|
||||
fused_Ps = (aligned_Ps * weights).sum(dim=0, keepdims=True)
|
||||
parse += [down(fused_Ps).detach().cpu()]
|
||||
parse = torch.cat(parse, dim=0)
|
||||
|
||||
basename = os.path.basename(args.video_path).split('.')[0]
|
||||
np.save(os.path.join(args.output_path, basename+'_parsingmap.npy'), parse.numpy())
|
||||
|
||||
print('Done!')
|
||||
@@ -0,0 +1,232 @@
|
||||
import os
|
||||
#os.environ['CUDA_VISIBLE_DEVICES'] = "0"
|
||||
import argparse
|
||||
import numpy as np
|
||||
import cv2
|
||||
import dlib
|
||||
import torch
|
||||
from torchvision import transforms
|
||||
import torch.nn.functional as F
|
||||
from tqdm import tqdm
|
||||
from model.vtoonify import VToonify
|
||||
from model.bisenet.model import BiSeNet
|
||||
from model.encoder.align_all_parallel import align_face
|
||||
from util import save_image, load_image, visualize, load_psp_standalone, get_video_crop_parameter, tensor2cv2
|
||||
|
||||
|
||||
class TestOptions():
|
||||
def __init__(self):
|
||||
|
||||
self.parser = argparse.ArgumentParser(description="Style Transfer")
|
||||
self.parser.add_argument("--content", type=str, default='./data/077436.jpg', help="path of the content image/video")
|
||||
self.parser.add_argument("--style_id", type=int, default=26, help="the id of the style image")
|
||||
self.parser.add_argument("--style_degree", type=float, default=0.5, help="style degree for VToonify-D")
|
||||
self.parser.add_argument("--color_transfer", action="store_true", help="transfer the color of the style")
|
||||
self.parser.add_argument("--ckpt", type=str, default='./checkpoint/vtoonify_d_cartoon/vtoonify_s_d.pt', help="path of the saved model")
|
||||
self.parser.add_argument("--output_path", type=str, default='./output/', help="path of the output images")
|
||||
self.parser.add_argument("--scale_image", action="store_true", help="resize and crop the image to best fit the model")
|
||||
self.parser.add_argument("--style_encoder_path", type=str, default='./checkpoint/encoder.pt', help="path of the style encoder")
|
||||
self.parser.add_argument("--exstyle_path", type=str, default=None, help="path of the extrinsic style code")
|
||||
self.parser.add_argument("--faceparsing_path", type=str, default='./checkpoint/faceparsing.pth', help="path of the face parsing model")
|
||||
self.parser.add_argument("--video", action="store_true", help="if true, video stylization; if false, image stylization")
|
||||
self.parser.add_argument("--cpu", action="store_true", help="if true, only use cpu")
|
||||
self.parser.add_argument("--backbone", type=str, default='dualstylegan', help="dualstylegan | toonify")
|
||||
self.parser.add_argument("--padding", type=int, nargs=4, default=[200,200,200,200], help="left, right, top, bottom paddings to the face center")
|
||||
self.parser.add_argument("--batch_size", type=int, default=4, help="batch size of frames when processing video")
|
||||
self.parser.add_argument("--parsing_map_path", type=str, default=None, help="path of the refined parsing map of the target video")
|
||||
|
||||
def parse(self):
|
||||
self.opt = self.parser.parse_args()
|
||||
if self.opt.exstyle_path is None:
|
||||
self.opt.exstyle_path = os.path.join(os.path.dirname(self.opt.ckpt), 'exstyle_code.npy')
|
||||
args = vars(self.opt)
|
||||
print('Load options')
|
||||
for name, value in sorted(args.items()):
|
||||
print('%s: %s' % (str(name), str(value)))
|
||||
return self.opt
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
parser = TestOptions()
|
||||
args = parser.parse()
|
||||
print('*'*98)
|
||||
|
||||
|
||||
device = "cpu" if args.cpu else "cuda"
|
||||
|
||||
transform = transforms.Compose([
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5,0.5,0.5]),
|
||||
])
|
||||
|
||||
vtoonify = VToonify(backbone = args.backbone)
|
||||
vtoonify.load_state_dict(torch.load(args.ckpt, map_location=lambda storage, loc: storage)['g_ema'])
|
||||
vtoonify.to(device)
|
||||
|
||||
parsingpredictor = BiSeNet(n_classes=19)
|
||||
parsingpredictor.load_state_dict(torch.load(args.faceparsing_path, map_location=lambda storage, loc: storage))
|
||||
parsingpredictor.to(device).eval()
|
||||
|
||||
modelname = './checkpoint/shape_predictor_68_face_landmarks.dat'
|
||||
if not os.path.exists(modelname):
|
||||
import wget, bz2
|
||||
wget.download('http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2', modelname+'.bz2')
|
||||
zipfile = bz2.BZ2File(modelname+'.bz2')
|
||||
data = zipfile.read()
|
||||
open(modelname, 'wb').write(data)
|
||||
landmarkpredictor = dlib.shape_predictor(modelname)
|
||||
|
||||
pspencoder = load_psp_standalone(args.style_encoder_path, device)
|
||||
|
||||
if args.backbone == 'dualstylegan':
|
||||
exstyles = np.load(args.exstyle_path, allow_pickle='TRUE').item()
|
||||
stylename = list(exstyles.keys())[args.style_id]
|
||||
exstyle = torch.tensor(exstyles[stylename]).to(device)
|
||||
with torch.no_grad():
|
||||
exstyle = vtoonify.zplus2wplus(exstyle)
|
||||
|
||||
if args.video and args.parsing_map_path is not None:
|
||||
x_p_hat = torch.tensor(np.load(args.parsing_map_path))
|
||||
|
||||
print('Load models successfully!')
|
||||
|
||||
|
||||
filename = args.content
|
||||
basename = os.path.basename(filename).split('.')[0]
|
||||
scale = 1
|
||||
kernel_1d = np.array([[0.125],[0.375],[0.375],[0.125]])
|
||||
print('Processing ' + os.path.basename(filename) + ' with vtoonify_' + args.backbone[0])
|
||||
if args.video:
|
||||
cropname = os.path.join(args.output_path, basename + '_input.mp4')
|
||||
savename = os.path.join(args.output_path, basename + '_vtoonify_' + args.backbone[0] + '.mp4')
|
||||
|
||||
video_cap = cv2.VideoCapture(filename)
|
||||
num = int(video_cap.get(7))
|
||||
|
||||
first_valid_frame = True
|
||||
batch_frames = []
|
||||
for i in tqdm(range(num)):
|
||||
success, frame = video_cap.read()
|
||||
if success == False:
|
||||
assert('load video frames error')
|
||||
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||
# We proprocess the video by detecting the face in the first frame,
|
||||
# and resizing the frame so that the eye distance is 64 pixels.
|
||||
# Centered on the eyes, we crop the first frame to almost 400x400 (based on args.padding).
|
||||
# All other frames use the same resizing and cropping parameters as the first frame.
|
||||
if first_valid_frame:
|
||||
if args.scale_image:
|
||||
paras = get_video_crop_parameter(frame, landmarkpredictor, args.padding)
|
||||
if paras is None:
|
||||
continue
|
||||
h,w,top,bottom,left,right,scale = paras
|
||||
H, W = int(bottom-top), int(right-left)
|
||||
# for HR video, we apply gaussian blur to the frames to avoid flickers caused by bilinear downsampling
|
||||
# this can also prevent over-sharp stylization results.
|
||||
if scale <= 0.75:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
if scale <= 0.375:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
|
||||
else:
|
||||
H, W = frame.shape[0], frame.shape[1]
|
||||
|
||||
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
||||
videoWriter = cv2.VideoWriter(cropname, fourcc, video_cap.get(5), (W, H))
|
||||
videoWriter2 = cv2.VideoWriter(savename, fourcc, video_cap.get(5), (4*W, 4*H))
|
||||
|
||||
# For each video, we detect and align the face in the first frame for pSp to obtain the style code.
|
||||
# This style code is used for all other frames.
|
||||
with torch.no_grad():
|
||||
I = align_face(frame, landmarkpredictor)
|
||||
I = transform(I).unsqueeze(dim=0).to(device)
|
||||
s_w = pspencoder(I)
|
||||
s_w = vtoonify.zplus2wplus(s_w)
|
||||
if vtoonify.backbone == 'dualstylegan':
|
||||
if args.color_transfer:
|
||||
s_w = exstyle
|
||||
else:
|
||||
s_w[:,:7] = exstyle[:,:7]
|
||||
first_valid_frame = False
|
||||
elif args.scale_image:
|
||||
if scale <= 0.75:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
if scale <= 0.375:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
|
||||
|
||||
videoWriter.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
|
||||
|
||||
batch_frames += [transform(frame).unsqueeze(dim=0).to(device)]
|
||||
|
||||
if len(batch_frames) == args.batch_size or (i+1) == num:
|
||||
x = torch.cat(batch_frames, dim=0)
|
||||
batch_frames = []
|
||||
with torch.no_grad():
|
||||
# parsing network works best on 512x512 images, so we predict parsing maps on upsmapled frames
|
||||
# followed by downsampling the parsing maps
|
||||
if args.video and args.parsing_map_path is not None:
|
||||
x_p = x_p_hat[i+1-x.size(0):i+1].to(device)
|
||||
else:
|
||||
x_p = F.interpolate(parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
|
||||
scale_factor=0.5, recompute_scale_factor=False).detach()
|
||||
# we give parsing maps lower weight (1/16)
|
||||
inputs = torch.cat((x, x_p/16.), dim=1)
|
||||
# d_s has no effect when backbone is toonify
|
||||
y_tilde = vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s = args.style_degree)
|
||||
y_tilde = torch.clamp(y_tilde, -1, 1)
|
||||
for k in range(y_tilde.size(0)):
|
||||
videoWriter2.write(tensor2cv2(y_tilde[k].cpu()))
|
||||
|
||||
videoWriter.release()
|
||||
videoWriter2.release()
|
||||
video_cap.release()
|
||||
|
||||
|
||||
else:
|
||||
cropname = os.path.join(args.output_path, basename + '_input.jpg')
|
||||
savename = os.path.join(args.output_path, basename + '_vtoonify_' + args.backbone[0] + '.jpg')
|
||||
|
||||
frame = cv2.imread(filename)
|
||||
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
|
||||
|
||||
# We detect the face in the image, and resize the image so that the eye distance is 64 pixels.
|
||||
# Centered on the eyes, we crop the image to almost 400x400 (based on args.padding).
|
||||
if args.scale_image:
|
||||
paras = get_video_crop_parameter(frame, landmarkpredictor, args.padding)
|
||||
if paras is not None:
|
||||
h,w,top,bottom,left,right,scale = paras
|
||||
H, W = int(bottom-top), int(right-left)
|
||||
# for HR image, we apply gaussian blur to it to avoid over-sharp stylization results
|
||||
if scale <= 0.75:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
if scale <= 0.375:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
|
||||
|
||||
with torch.no_grad():
|
||||
I = align_face(frame, landmarkpredictor)
|
||||
I = transform(I).unsqueeze(dim=0).to(device)
|
||||
s_w = pspencoder(I)
|
||||
s_w = vtoonify.zplus2wplus(s_w)
|
||||
if vtoonify.backbone == 'dualstylegan':
|
||||
if args.color_transfer:
|
||||
s_w = exstyle
|
||||
else:
|
||||
s_w[:,:7] = exstyle[:,:7]
|
||||
|
||||
x = transform(frame).unsqueeze(dim=0).to(device)
|
||||
# parsing network works best on 512x512 images, so we predict parsing maps on upsmapled frames
|
||||
# followed by downsampling the parsing maps
|
||||
x_p = F.interpolate(parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
|
||||
scale_factor=0.5, recompute_scale_factor=False).detach()
|
||||
# we give parsing maps lower weight (1/16)
|
||||
inputs = torch.cat((x, x_p/16.), dim=1)
|
||||
# d_s has no effect when backbone is toonify
|
||||
y_tilde = vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s = args.style_degree)
|
||||
y_tilde = torch.clamp(y_tilde, -1, 1)
|
||||
|
||||
cv2.imwrite(cropname, cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
|
||||
save_image(y_tilde[0].cpu(), savename)
|
||||
|
||||
print('Transfer style successfully!')
|
||||
@@ -0,0 +1,515 @@
|
||||
import os
|
||||
#os.environ['CUDA_VISIBLE_DEVICES'] = "0"
|
||||
import argparse
|
||||
import math
|
||||
import random
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch import nn, optim
|
||||
from torch.nn import functional as F
|
||||
from torch.utils import data
|
||||
import torch.distributed as dist
|
||||
from torchvision import transforms, utils
|
||||
from tqdm import tqdm
|
||||
from PIL import Image
|
||||
from util import *
|
||||
|
||||
from model.stylegan import lpips
|
||||
from model.stylegan.model import Generator, Downsample
|
||||
from model.vtoonify import VToonify, ConditionalDiscriminator
|
||||
from model.bisenet.model import BiSeNet
|
||||
from model.simple_augment import random_apply_affine
|
||||
from model.stylegan.distributed import (
|
||||
get_rank,
|
||||
synchronize,
|
||||
reduce_loss_dict,
|
||||
reduce_sum,
|
||||
get_world_size,
|
||||
)
|
||||
|
||||
class TrainOptions():
|
||||
def __init__(self):
|
||||
|
||||
self.parser = argparse.ArgumentParser(description="Train VToonify-D")
|
||||
self.parser.add_argument("--iter", type=int, default=2000, help="total training iterations")
|
||||
self.parser.add_argument("--batch", type=int, default=8, help="batch sizes for each gpus")
|
||||
self.parser.add_argument("--lr", type=float, default=0.0001, help="learning rate")
|
||||
self.parser.add_argument("--local_rank", type=int, default=0, help="local rank for distributed training")
|
||||
self.parser.add_argument("--start_iter", type=int, default=0, help="start iteration")
|
||||
self.parser.add_argument("--save_every", type=int, default=30000, help="interval of saving a checkpoint")
|
||||
self.parser.add_argument("--save_begin", type=int, default=30000, help="when to start saving a checkpoint")
|
||||
self.parser.add_argument("--log_every", type=int, default=200, help="interval of saving a checkpoint")
|
||||
|
||||
self.parser.add_argument("--adv_loss", type=float, default=0.01, help="the weight of adv loss")
|
||||
self.parser.add_argument("--grec_loss", type=float, default=0.1, help="the weight of mse recontruction loss")
|
||||
self.parser.add_argument("--perc_loss", type=float, default=0.01, help="the weight of perceptual loss")
|
||||
self.parser.add_argument("--tmp_loss", type=float, default=1.0, help="the weight of temporal consistency loss")
|
||||
self.parser.add_argument("--msk_loss", type=float, default=0.0005, help="the weight of attention mask loss")
|
||||
|
||||
self.parser.add_argument("--fix_degree", action="store_true", help="use a fixed style degree")
|
||||
self.parser.add_argument("--fix_style", action="store_true", help="use a fixed style image")
|
||||
self.parser.add_argument("--fix_color", action="store_true", help="use the original color (no color transfer)")
|
||||
self.parser.add_argument("--exstyle_path", type=str, default='./checkpoint/cartoon/refined_exstyle_code.npy', help="path of the extrinsic style code")
|
||||
self.parser.add_argument("--style_id", type=int, default=26, help="the id of the style image")
|
||||
self.parser.add_argument("--style_degree", type=float, default=0.5, help="style degree for VToonify-D")
|
||||
|
||||
self.parser.add_argument("--encoder_path", type=str, default=None, help="path to the pretrained encoder model")
|
||||
self.parser.add_argument("--direction_path", type=str, default='./checkpoint/directions.npy', help="path to the editing direction latents")
|
||||
self.parser.add_argument("--stylegan_path", type=str, default='./checkpoint/cartoon/generator.pt', help="path to the stylegan model")
|
||||
self.parser.add_argument("--faceparsing_path", type=str, default='./checkpoint/faceparsing.pth', help="path of the face parsing model")
|
||||
self.parser.add_argument("--style_encoder_path", type=str, default='./checkpoint/encoder.pt', help="path of the style encoder")
|
||||
|
||||
self.parser.add_argument("--name", type=str, default='vtoonify_d_cartoon', help="saved model name")
|
||||
self.parser.add_argument("--pretrain", action="store_true", help="if true, only pretrain the encoder")
|
||||
|
||||
def parse(self):
|
||||
self.opt = self.parser.parse_args()
|
||||
if self.opt.encoder_path is None:
|
||||
self.opt.encoder_path = os.path.join('./checkpoint/', self.opt.name, 'pretrain.pt')
|
||||
args = vars(self.opt)
|
||||
if self.opt.local_rank == 0:
|
||||
print('Load options')
|
||||
for name, value in sorted(args.items()):
|
||||
print('%s: %s' % (str(name), str(value)))
|
||||
return self.opt
|
||||
|
||||
|
||||
# pretrain E of vtoonify.
|
||||
# We train E so that its the last-layer feature matches the original 8-th-layer input feature of G1
|
||||
# See Model initialization in Sec. 4.2.2 for the detail
|
||||
def pretrain(args, generator, g_optim, g_ema, parsingpredictor, down, directions, styles, device):
|
||||
pbar = range(args.iter)
|
||||
|
||||
if get_rank() == 0:
|
||||
pbar = tqdm(pbar, initial=args.start_iter, dynamic_ncols=True, smoothing=0.01)
|
||||
|
||||
recon_loss = torch.tensor(0.0, device=device)
|
||||
loss_dict = {}
|
||||
|
||||
if args.distributed:
|
||||
g_module = generator.module
|
||||
else:
|
||||
g_module = generator
|
||||
|
||||
accum = 0.5 ** (32 / (10 * 1000))
|
||||
|
||||
requires_grad(g_module.encoder, True)
|
||||
|
||||
for idx in pbar:
|
||||
i = idx + args.start_iter
|
||||
|
||||
if i > args.iter:
|
||||
print("Done!")
|
||||
break
|
||||
|
||||
# during pretraining, the last 11 layers of DualStyleGAN (for color transfer) is not used.
|
||||
# so args.fix_color is not used. the last 11 elements in weight are not used.
|
||||
if args.fix_degree:
|
||||
d_s = args.style_degree
|
||||
else:
|
||||
d_s = 0 if i <= args.iter / 4.0 else np.random.rand(1)[0]
|
||||
weight = [d_s] * 18
|
||||
|
||||
# sample pre-saved w''=E_s(s)
|
||||
if args.fix_style:
|
||||
style = styles[args.style_id:args.style_id+1].repeat(args.batch,1,1)
|
||||
else:
|
||||
style = styles[torch.randint(0, styles.size(0), (args.batch,))]
|
||||
|
||||
with torch.no_grad():
|
||||
# during pretraining, no geometric transformations are applied.
|
||||
noise_sample = torch.randn(args.batch, 512).cuda()
|
||||
ws_ = g_ema.stylegan().style(noise_sample).unsqueeze(1).repeat(1,18,1) # random w
|
||||
ws_[:, 3:7] += directions[torch.randint(0, directions.shape[0], (args.batch,)), 3:7] # w'=w+n
|
||||
img_gen, _ = g_ema.stylegan()([ws_], input_is_latent=True, truncation=0.5, truncation_latent=0)
|
||||
img_gen = torch.clamp(img_gen, -1, 1).detach() # x''
|
||||
img_gen512 = down(img_gen.detach())
|
||||
img_gen256 = down(img_gen512.detach()) # image part of x''_down
|
||||
mask512 = parsingpredictor(2*torch.clamp(img_gen512, -1, 1))[0]
|
||||
real_input = torch.cat((img_gen256, down(mask512)/16.0), dim=1) # x''_down
|
||||
# f_G1^(8)(w', w'', d_s)
|
||||
real_feat, real_skip = g_ema.generator([ws_], style, input_is_latent=True, return_feat=True,
|
||||
truncation=0.5, truncation_latent=0, use_res=True, interp_weights=weight)
|
||||
|
||||
real_input = real_input.detach()
|
||||
real_feat = real_feat.detach()
|
||||
real_skip = real_skip.detach()
|
||||
|
||||
# f_E^(last)(x''_down, w'', d_s)
|
||||
fake_feat, fake_skip = generator(real_input, style, d_s, return_feat=True)
|
||||
|
||||
# L_E in Eq.(8)
|
||||
recon_loss = F.mse_loss(fake_feat, real_feat) + F.mse_loss(fake_skip, real_skip)
|
||||
|
||||
loss_dict["emse"] = recon_loss
|
||||
|
||||
generator.zero_grad()
|
||||
recon_loss.backward()
|
||||
g_optim.step()
|
||||
|
||||
accumulate(g_ema.encoder, g_module.encoder, accum)
|
||||
|
||||
loss_reduced = reduce_loss_dict(loss_dict)
|
||||
|
||||
emse_loss_val = loss_reduced["emse"].mean().item()
|
||||
|
||||
if get_rank() == 0:
|
||||
pbar.set_description(
|
||||
(
|
||||
f"iter: {i:d}; emse: {emse_loss_val:.3f}"
|
||||
)
|
||||
)
|
||||
|
||||
if ((i+1) >= args.save_begin and (i+1) % args.save_every == 0) or (i+1) == args.iter:
|
||||
if (i+1) == args.iter:
|
||||
savename = f"checkpoint/%s/pretrain.pt"%(args.name)
|
||||
else:
|
||||
savename = f"checkpoint/%s/pretrain-%05d.pt"%(args.name, i+1)
|
||||
torch.save(
|
||||
{
|
||||
#"g": g_module.encoder.state_dict(),
|
||||
"g_ema": g_ema.encoder.state_dict(),
|
||||
},
|
||||
savename,
|
||||
)
|
||||
|
||||
|
||||
# generate paired data and train vtoonify, see Sec. 4.2.2 for the detail
|
||||
def train(args, generator, discriminator, g_optim, d_optim, g_ema, percept, parsingpredictor, down, pspencoder, directions, styles, device):
|
||||
pbar = range(args.iter)
|
||||
|
||||
if get_rank() == 0:
|
||||
pbar = tqdm(pbar, initial=args.start_iter, smoothing=0.01, ncols=130, dynamic_ncols=False)
|
||||
|
||||
d_loss = torch.tensor(0.0, device=device)
|
||||
g_loss = torch.tensor(0.0, device=device)
|
||||
grec_loss = torch.tensor(0.0, device=device)
|
||||
gfeat_loss = torch.tensor(0.0, device=device)
|
||||
temporal_loss = torch.tensor(0.0, device=device)
|
||||
gmask_loss = torch.tensor(0.0, device=device)
|
||||
loss_dict = {}
|
||||
|
||||
surffix = '_s'
|
||||
if args.fix_style:
|
||||
surffix += '%03d'%(args.style_id)
|
||||
surffix += '_d'
|
||||
if args.fix_degree:
|
||||
surffix += '%1.1f'%(args.style_degree)
|
||||
if not args.fix_color:
|
||||
surffix += '_c'
|
||||
|
||||
if args.distributed:
|
||||
g_module = generator.module
|
||||
d_module = discriminator.module
|
||||
|
||||
else:
|
||||
g_module = generator
|
||||
d_module = discriminator
|
||||
|
||||
accum = 0.5 ** (32 / (10 * 1000))
|
||||
|
||||
for idx in pbar:
|
||||
i = idx + args.start_iter
|
||||
|
||||
if i > args.iter:
|
||||
print("Done!")
|
||||
break
|
||||
|
||||
# sample style degree
|
||||
if args.fix_degree or idx == 0 or i == 0:
|
||||
d_s = args.style_degree
|
||||
else:
|
||||
d_s = np.random.randint(0,6) / 5.0
|
||||
if args.fix_color:
|
||||
weight = [d_s] * 7 + [0] * 11
|
||||
else:
|
||||
weight = [d_s] * 7 + [1] * 11
|
||||
# style degree condition for discriminator
|
||||
degree_label = torch.zeros(args.batch, 1).to(device) + d_s
|
||||
|
||||
# style index condition for discriminator
|
||||
style_ind = torch.randint(0, styles.size(0), (args.batch,)).to(device)
|
||||
if args.fix_style or idx == 0 or i == 0:
|
||||
style_ind = style_ind * 0 + args.style_id
|
||||
# sample pre-saved E_s(s)
|
||||
style = styles[style_ind]
|
||||
|
||||
with torch.no_grad():
|
||||
noise_sample = torch.randn(args.batch, 512).cuda()
|
||||
wc = g_ema.stylegan().style(noise_sample).unsqueeze(1).repeat(1,18,1) # random w
|
||||
wc[:, 3:7] += directions[torch.randint(0, directions.shape[0], (args.batch,)), 3:7] # w'=w+n
|
||||
wc = wc.detach()
|
||||
xc, _ = g_ema.stylegan()([wc], input_is_latent=True, truncation=0.5, truncation_latent=0)
|
||||
xc = torch.clamp(xc, -1, 1).detach() # x''
|
||||
if not args.fix_color and args.fix_style: # only transfer this fixed style's color
|
||||
xl = style.clone()
|
||||
else:
|
||||
xl = pspencoder(F.adaptive_avg_pool2d(xc, 256))
|
||||
xl = g_ema.zplus2wplus(xl) # E_s(x''_down)
|
||||
xl = torch.cat((style[:,0:7], xl[:,7:18]), dim=1).detach() # w'' = concatenate E_s(s) and E_s(x''_down)
|
||||
xs, _ = g_ema.generator([wc], xl, input_is_latent=True,
|
||||
truncation=0.5, truncation_latent=0, use_res=True, interp_weights=weight)
|
||||
xs = torch.clamp(xs, -1, 1).detach() # y'=G1(w', w'', d_s, d_c)
|
||||
# apply color jitter to w'. we fuse w' of the current iteration with w' of the last iteration
|
||||
if idx > 0 and i >= (args.iter/2.0) and (not args.fix_color and not args.fix_style):
|
||||
wcfuse = wc.clone()
|
||||
wcfuse[:,7:] = wc_[:,7:] * (i/(args.iter/2.0)-1) + wcfuse[:,7:] * (2-i/(args.iter/2.0))
|
||||
xc, _ = g_ema.stylegan()([wcfuse], input_is_latent=True, truncation=0.5, truncation_latent=0)
|
||||
xc = torch.clamp(xc, -1, 1).detach() # x'
|
||||
wc_ = wc.clone() # wc_ is the w' in the last iteration
|
||||
# during training, random geometric transformations are applied.
|
||||
imgs, _ = random_apply_affine(torch.cat((xc.detach(),xs), dim=1), 0.2, None)
|
||||
real_input1024 = imgs[:,0:3].detach() # image part of x
|
||||
real_input512 = down(real_input1024).detach()
|
||||
real_input256 = down(real_input512).detach()
|
||||
mask512 = parsingpredictor(2*real_input512)[0]
|
||||
mask256 = down(mask512).detach()
|
||||
mask = F.adaptive_avg_pool2d(mask512, 1024).detach() # parsing part of x
|
||||
real_output = imgs[:,3:].detach() # y
|
||||
real_input = torch.cat((real_input256, mask256/16.0), dim=1) # x_down
|
||||
# for log, sample a fixed input-output pair (x_down, y, w'', d_s)
|
||||
if idx == 0 or i == 0:
|
||||
samplein = real_input.clone().detach()
|
||||
sampleout = real_output.clone().detach()
|
||||
samplexl = xl.clone().detach()
|
||||
sampleds = d_s
|
||||
|
||||
###### This part is for training discriminator
|
||||
|
||||
requires_grad(g_module.encoder, False)
|
||||
requires_grad(g_module.fusion_out, False)
|
||||
requires_grad(g_module.fusion_skip, False)
|
||||
requires_grad(discriminator, True)
|
||||
|
||||
fake_output = generator(real_input, xl, d_s)
|
||||
fake_pred = discriminator(F.adaptive_avg_pool2d(fake_output, 256), degree_label, style_ind)
|
||||
real_pred = discriminator(F.adaptive_avg_pool2d(real_output, 256), degree_label, style_ind)
|
||||
|
||||
# L_adv in Eq.(3)
|
||||
d_loss = d_logistic_loss(real_pred, fake_pred) * args.adv_loss
|
||||
loss_dict["d"] = d_loss
|
||||
|
||||
discriminator.zero_grad()
|
||||
d_loss.backward()
|
||||
d_optim.step()
|
||||
|
||||
###### This part is for training generator (encoder and fusion modules)
|
||||
|
||||
requires_grad(g_module.encoder, True)
|
||||
requires_grad(g_module.fusion_out, True)
|
||||
requires_grad(g_module.fusion_skip, True)
|
||||
requires_grad(discriminator, False)
|
||||
|
||||
fake_output, m_Es = generator(real_input, xl, d_s, return_mask=True)
|
||||
fake_pred = discriminator(F.adaptive_avg_pool2d(fake_output, 256), degree_label, style_ind)
|
||||
|
||||
# L_adv in Eq.(3)
|
||||
g_loss = g_nonsaturating_loss(fake_pred) * args.adv_loss
|
||||
# L_rec in Eq.(2)
|
||||
grec_loss = F.mse_loss(fake_output, real_output) * args.grec_loss
|
||||
gfeat_loss = percept(F.adaptive_avg_pool2d(fake_output, 512), # 1024 will out of memory
|
||||
F.adaptive_avg_pool2d(real_output, 512)).sum() * args.perc_loss # 256 will get blurry output
|
||||
|
||||
# L_msk in Eq.(9)
|
||||
gmask_loss = torch.tensor(0.0, device=device)
|
||||
if not args.fix_degree or args.msk_loss > 0:
|
||||
for jj, m_E in enumerate(m_Es):
|
||||
gd_s = (1 - d_s) ** 2 * 0.9 + 0.1
|
||||
gmask_loss += F.relu(torch.mean(m_E)-gd_s) * args.msk_loss
|
||||
|
||||
loss_dict["g"] = g_loss
|
||||
loss_dict["gr"] = grec_loss
|
||||
loss_dict["gf"] = gfeat_loss
|
||||
loss_dict["msk"] = gmask_loss
|
||||
|
||||
w = random.randint(0,1024-896)
|
||||
h = random.randint(0,1024-896)
|
||||
crop_input = torch.cat((real_input1024[:,:,w:w+896,h:h+896], mask[:,:,w:w+896,h:h+896]/16.0), dim=1).detach()
|
||||
crop_input = down(down(crop_input))
|
||||
crop_fake_output = fake_output[:,:,w:w+896,h:h+896]
|
||||
fake_crop_output = generator(crop_input, xl, d_s)
|
||||
# L_tmp in Eq.(4), gradually increase the weight of L_tmp
|
||||
temporal_loss = ((fake_crop_output-crop_fake_output)**2).mean() * max(idx/(args.iter/2.0)-1, 0) * args.tmp_loss
|
||||
loss_dict["tp"] = temporal_loss
|
||||
|
||||
generator.zero_grad()
|
||||
(g_loss + grec_loss + gfeat_loss + temporal_loss + gmask_loss).backward()
|
||||
g_optim.step()
|
||||
|
||||
accumulate(g_ema.encoder, g_module.encoder, accum)
|
||||
accumulate(g_ema.fusion_out, g_module.fusion_out, accum)
|
||||
accumulate(g_ema.fusion_skip, g_module.fusion_skip, accum)
|
||||
|
||||
loss_reduced = reduce_loss_dict(loss_dict)
|
||||
|
||||
d_loss_val = loss_reduced["d"].mean().item()
|
||||
g_loss_val = loss_reduced["g"].mean().item()
|
||||
gr_loss_val = loss_reduced["gr"].mean().item()
|
||||
gf_loss_val = loss_reduced["gf"].mean().item()
|
||||
tmp_loss_val = loss_reduced["tp"].mean().item()
|
||||
msk_loss_val = loss_reduced["msk"].mean().item()
|
||||
|
||||
if get_rank() == 0:
|
||||
pbar.set_description(
|
||||
(
|
||||
f"iter: {i:d}; advd: {d_loss_val:.3f}; advg: {g_loss_val:.3f}; mse: {gr_loss_val:.3f}; "
|
||||
f"perc: {gf_loss_val:.3f}; tmp: {tmp_loss_val:.3f}; msk: {msk_loss_val:.3f}"
|
||||
)
|
||||
)
|
||||
|
||||
if i == 0 or (i+1) % args.log_every == 0 or (i+1) == args.iter:
|
||||
with torch.no_grad():
|
||||
g_ema.eval()
|
||||
sample1 = g_ema(samplein, samplexl, sampleds)
|
||||
if args.fix_degree:
|
||||
sample = F.interpolate(torch.cat((sampleout, sample1), dim=0), 256)
|
||||
else:
|
||||
sample2 = g_ema(samplein, samplexl, d_s)
|
||||
sample = F.interpolate(torch.cat((sampleout, sample1, sample2), dim=0), 256)
|
||||
utils.save_image(
|
||||
sample,
|
||||
f"log/%s/%05d.jpg"%(args.name, (i+1)),
|
||||
nrow=int(args.batch),
|
||||
normalize=True,
|
||||
range=(-1, 1),
|
||||
)
|
||||
|
||||
if ((i+1) >= args.save_begin and (i+1) % args.save_every == 0) or (i+1) == args.iter:
|
||||
if (i+1) == args.iter:
|
||||
savename = f"checkpoint/%s/vtoonify%s.pt"%(args.name, surffix)
|
||||
else:
|
||||
savename = f"checkpoint/%s/vtoonify%s_%05d.pt"%(args.name, surffix, i+1)
|
||||
torch.save(
|
||||
{
|
||||
#"g": g_module.state_dict(),
|
||||
#"d": d_module.state_dict(),
|
||||
"g_ema": g_ema.state_dict(),
|
||||
},
|
||||
savename,
|
||||
)
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
device = "cuda"
|
||||
parser = TrainOptions()
|
||||
args = parser.parse()
|
||||
if args.local_rank == 0:
|
||||
print('*'*98)
|
||||
if not os.path.exists("log/%s/"%(args.name)):
|
||||
os.makedirs("log/%s/"%(args.name))
|
||||
if not os.path.exists("checkpoint/%s/"%(args.name)):
|
||||
os.makedirs("checkpoint/%s/"%(args.name))
|
||||
|
||||
n_gpu = int(os.environ["WORLD_SIZE"]) if "WORLD_SIZE" in os.environ else 1
|
||||
args.distributed = n_gpu > 1
|
||||
|
||||
if args.distributed:
|
||||
torch.cuda.set_device(args.local_rank)
|
||||
torch.distributed.init_process_group(backend="nccl", init_method="env://")
|
||||
synchronize()
|
||||
|
||||
generator = VToonify(backbone = 'dualstylegan').to(device)
|
||||
generator.apply(weights_init)
|
||||
g_ema = VToonify(backbone = 'dualstylegan').to(device)
|
||||
g_ema.eval()
|
||||
|
||||
ckpt = torch.load(args.stylegan_path, map_location=lambda storage, loc: storage)
|
||||
generator.generator.load_state_dict(ckpt["g_ema"], strict=False)
|
||||
# load ModRes blocks of DualStyleGAN into the modified ModRes blocks (with dilation)
|
||||
generator.res.load_state_dict(generator.generator.res.state_dict(), strict=False)
|
||||
g_ema.generator.load_state_dict(ckpt["g_ema"], strict=False)
|
||||
g_ema.res.load_state_dict(g_ema.generator.res.state_dict(), strict=False)
|
||||
requires_grad(generator.generator, False)
|
||||
requires_grad(generator.res, False)
|
||||
requires_grad(g_ema.generator, False)
|
||||
requires_grad(g_ema.res, False)
|
||||
|
||||
if not args.pretrain:
|
||||
generator.encoder.load_state_dict(torch.load(args.encoder_path, map_location=lambda storage, loc: storage)["g_ema"])
|
||||
# we initialize the fusion modules to map f_G \otimes f_E to f_G.
|
||||
for k in generator.fusion_out:
|
||||
k.conv.weight.data *= 0.01
|
||||
k.conv.weight[:,0:k.conv.weight.shape[0],1,1].data += torch.eye(k.conv.weight.shape[0]).cuda()
|
||||
for k in generator.fusion_skip:
|
||||
k.weight.data *= 0.01
|
||||
k.weight[:,0:k.weight.shape[0],1,1].data += torch.eye(k.weight.shape[0]).cuda()
|
||||
|
||||
accumulate(g_ema.encoder, generator.encoder, 0)
|
||||
accumulate(g_ema.fusion_out, generator.fusion_out, 0)
|
||||
accumulate(g_ema.fusion_skip, generator.fusion_skip, 0)
|
||||
|
||||
g_parameters = list(generator.encoder.parameters())
|
||||
if not args.pretrain:
|
||||
g_parameters = g_parameters + list(generator.fusion_out.parameters()) + list(generator.fusion_skip.parameters())
|
||||
|
||||
g_optim = optim.Adam(
|
||||
g_parameters,
|
||||
lr=args.lr,
|
||||
betas=(0.9, 0.99),
|
||||
)
|
||||
|
||||
if args.distributed:
|
||||
generator = nn.parallel.DistributedDataParallel(
|
||||
generator,
|
||||
device_ids=[args.local_rank],
|
||||
output_device=args.local_rank,
|
||||
broadcast_buffers=False,
|
||||
find_unused_parameters=True,
|
||||
)
|
||||
|
||||
parsingpredictor = BiSeNet(n_classes=19)
|
||||
parsingpredictor.load_state_dict(torch.load(args.faceparsing_path, map_location=lambda storage, loc: storage))
|
||||
parsingpredictor.to(device).eval()
|
||||
requires_grad(parsingpredictor, False)
|
||||
|
||||
# we apply gaussian blur to the images to avoid flickers caused during downsampling
|
||||
down = Downsample(kernel=[1, 3, 3, 1], factor=2).to(device)
|
||||
requires_grad(down, False)
|
||||
|
||||
directions = torch.tensor(np.load(args.direction_path)).to(device)
|
||||
|
||||
# load style codes of DualStyleGAN
|
||||
exstyles = np.load(args.exstyle_path, allow_pickle='TRUE').item()
|
||||
if args.local_rank == 0 and not os.path.exists('checkpoint/%s/exstyle_code.npy'%(args.name)):
|
||||
np.save('checkpoint/%s/exstyle_code.npy'%(args.name), exstyles, allow_pickle=True)
|
||||
styles = []
|
||||
with torch.no_grad():
|
||||
for stylename in exstyles.keys():
|
||||
exstyle = torch.tensor(exstyles[stylename]).to(device)
|
||||
exstyle = g_ema.zplus2wplus(exstyle)
|
||||
styles += [exstyle]
|
||||
styles = torch.cat(styles, dim=0)
|
||||
|
||||
if not args.pretrain:
|
||||
discriminator = ConditionalDiscriminator(256, use_condition=True, style_num = styles.size(0)).to(device)
|
||||
|
||||
d_optim = optim.Adam(
|
||||
discriminator.parameters(),
|
||||
lr=args.lr,
|
||||
betas=(0.9, 0.99),
|
||||
)
|
||||
|
||||
if args.distributed:
|
||||
discriminator = nn.parallel.DistributedDataParallel(
|
||||
discriminator,
|
||||
device_ids=[args.local_rank],
|
||||
output_device=args.local_rank,
|
||||
broadcast_buffers=False,
|
||||
find_unused_parameters=True,
|
||||
)
|
||||
|
||||
percept = lpips.PerceptualLoss(model="net-lin", net="vgg", use_gpu=device.startswith("cuda"), gpu_ids=[args.local_rank])
|
||||
requires_grad(percept.model.net, False)
|
||||
|
||||
pspencoder = load_psp_standalone(args.style_encoder_path, device)
|
||||
|
||||
if args.local_rank == 0:
|
||||
print('Load models and data successfully loaded!')
|
||||
|
||||
if args.pretrain:
|
||||
pretrain(args, generator, g_optim, g_ema, parsingpredictor, down, directions, styles, device)
|
||||
else:
|
||||
train(args, generator, discriminator, g_optim, d_optim, g_ema, percept, parsingpredictor, down, pspencoder, directions, styles, device)
|
||||
@@ -0,0 +1,432 @@
|
||||
import os
|
||||
#os.environ['CUDA_VISIBLE_DEVICES'] = "0"
|
||||
import argparse
|
||||
import math
|
||||
import random
|
||||
|
||||
import numpy as np
|
||||
import torch
|
||||
from torch import nn, optim
|
||||
from torch.nn import functional as F
|
||||
from torch.utils import data
|
||||
import torch.distributed as dist
|
||||
from torchvision import transforms, utils
|
||||
from tqdm import tqdm
|
||||
from PIL import Image
|
||||
from util import *
|
||||
from model.stylegan import lpips
|
||||
from model.stylegan.model import Generator, Downsample
|
||||
from model.vtoonify import VToonify, ConditionalDiscriminator
|
||||
from model.bisenet.model import BiSeNet
|
||||
from model.simple_augment import random_apply_affine
|
||||
from model.stylegan.distributed import (
|
||||
get_rank,
|
||||
synchronize,
|
||||
reduce_loss_dict,
|
||||
reduce_sum,
|
||||
get_world_size,
|
||||
)
|
||||
|
||||
# In the paper, --weight for each style is set as follows,
|
||||
# cartoon: default
|
||||
# caricature: default
|
||||
# pixar: 1 1 1 1 1 1 1 1 1 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5
|
||||
# comic: 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 1 1 1 1 1 1 1 1 1 1
|
||||
# arcane: 0.5 0.5 0.5 0.5 0.5 0.5 0.5 1 1 1 1 1 1 1 1 1 1 1
|
||||
|
||||
class TrainOptions():
|
||||
def __init__(self):
|
||||
|
||||
self.parser = argparse.ArgumentParser(description="Train VToonify-T")
|
||||
self.parser.add_argument("--iter", type=int, default=2000, help="total training iterations")
|
||||
self.parser.add_argument("--batch", type=int, default=8, help="batch sizes for each gpus")
|
||||
self.parser.add_argument("--lr", type=float, default=0.0001, help="learning rate")
|
||||
self.parser.add_argument("--local_rank", type=int, default=0, help="local rank for distributed training")
|
||||
self.parser.add_argument("--start_iter", type=int, default=0, help="start iteration")
|
||||
self.parser.add_argument("--save_every", type=int, default=30000, help="interval of saving a checkpoint")
|
||||
self.parser.add_argument("--save_begin", type=int, default=30000, help="when to start saving a checkpoint")
|
||||
self.parser.add_argument("--log_every", type=int, default=200, help="interval of saving an intermediate image result")
|
||||
|
||||
self.parser.add_argument("--adv_loss", type=float, default=0.01, help="the weight of adv loss")
|
||||
self.parser.add_argument("--grec_loss", type=float, default=0.1, help="the weight of mse recontruction loss")
|
||||
self.parser.add_argument("--perc_loss", type=float, default=0.01, help="the weight of perceptual loss")
|
||||
self.parser.add_argument("--tmp_loss", type=float, default=1.0, help="the weight of temporal consistency loss")
|
||||
|
||||
self.parser.add_argument("--encoder_path", type=str, default=None, help="path to the pretrained encoder model")
|
||||
self.parser.add_argument("--direction_path", type=str, default='./checkpoint/directions.npy', help="path to the editing direction latents")
|
||||
self.parser.add_argument("--stylegan_path", type=str, default='./checkpoint/stylegan2-ffhq-config-f.pt', help="path to the stylegan model")
|
||||
self.parser.add_argument("--finetunegan_path", type=str, default='./checkpoint/cartoon/finetune-000600.pt', help="path to the finetuned stylegan model")
|
||||
self.parser.add_argument("--weight", type=float, nargs=18, default=[1]*9+[0]*9, help="the weight for blending two models")
|
||||
self.parser.add_argument("--faceparsing_path", type=str, default='./checkpoint/faceparsing.pth', help="path of the face parsing model")
|
||||
self.parser.add_argument("--style_encoder_path", type=str, default='./checkpoint/encoder.pt', help="path of the style encoder")
|
||||
|
||||
self.parser.add_argument("--name", type=str, default='vtoonify_t_cartoon', help="saved model name")
|
||||
self.parser.add_argument("--pretrain", action="store_true", help="if true, only pretrain the encoder")
|
||||
|
||||
def parse(self):
|
||||
self.opt = self.parser.parse_args()
|
||||
if self.opt.encoder_path is None:
|
||||
self.opt.encoder_path = os.path.join('./checkpoint/', self.opt.name, 'pretrain.pt')
|
||||
args = vars(self.opt)
|
||||
if self.opt.local_rank == 0:
|
||||
print('Load options')
|
||||
for name, value in sorted(args.items()):
|
||||
print('%s: %s' % (str(name), str(value)))
|
||||
return self.opt
|
||||
|
||||
|
||||
# pretrain E of vtoonify.
|
||||
# We train E so that its the last-layer feature matches the original 8-th-layer input feature of G1
|
||||
# See Model initialization in Sec. 4.1.2 for the detail
|
||||
def pretrain(args, generator, g_optim, g_ema, parsingpredictor, down, directions, basemodel, device):
|
||||
pbar = range(args.iter)
|
||||
|
||||
if get_rank() == 0:
|
||||
pbar = tqdm(pbar, initial=args.start_iter, dynamic_ncols=True, smoothing=0.01)
|
||||
|
||||
recon_loss = torch.tensor(0.0, device=device)
|
||||
loss_dict = {}
|
||||
|
||||
if args.distributed:
|
||||
g_module = generator.module
|
||||
else:
|
||||
g_module = generator
|
||||
|
||||
accum = 0.5 ** (32 / (10 * 1000))
|
||||
|
||||
requires_grad(g_module.encoder, True)
|
||||
|
||||
for idx in pbar:
|
||||
i = idx + args.start_iter
|
||||
|
||||
if i > args.iter:
|
||||
print("Done!")
|
||||
break
|
||||
|
||||
with torch.no_grad():
|
||||
# during pretraining, no geometric transformations are applied.
|
||||
noise_sample = torch.randn(args.batch, 512).cuda()
|
||||
ws_ = basemodel.style(noise_sample).unsqueeze(1).repeat(1,18,1) # random w
|
||||
ws_[:, 3:7] += directions[torch.randint(0, directions.shape[0], (args.batch,)), 3:7] # w''=w'=w+n
|
||||
img_gen, _ = basemodel([ws_], input_is_latent=True, truncation=0.5, truncation_latent=0) # image part of x'
|
||||
img_gen = torch.clamp(img_gen, -1, 1).detach()
|
||||
img_gen512 = down(img_gen.detach())
|
||||
img_gen256 = down(img_gen512.detach()) # image part of x'_down
|
||||
mask512 = parsingpredictor(2*torch.clamp(img_gen512, -1, 1))[0]
|
||||
real_input = torch.cat((img_gen256, down(mask512)/16.0), dim=1).detach() # x'_down
|
||||
# f_G1^(8)(w'')
|
||||
real_feat, real_skip = g_ema.generator([ws_], input_is_latent=True, return_feature_ind = 6, truncation=0.5, truncation_latent=0)
|
||||
real_feat = real_feat.detach()
|
||||
real_skip = real_skip.detach()
|
||||
|
||||
# f_E^(last)(x'_down)
|
||||
fake_feat, fake_skip = generator(real_input, style=None, return_feat=True)
|
||||
|
||||
# L_E in Eq.(1)
|
||||
recon_loss = F.mse_loss(fake_feat, real_feat) + F.mse_loss(fake_skip, real_skip)
|
||||
|
||||
loss_dict["emse"] = recon_loss
|
||||
|
||||
generator.zero_grad()
|
||||
recon_loss.backward()
|
||||
g_optim.step()
|
||||
|
||||
accumulate(g_ema.encoder, g_module.encoder, accum)
|
||||
|
||||
loss_reduced = reduce_loss_dict(loss_dict)
|
||||
|
||||
emse_loss_val = loss_reduced["emse"].mean().item()
|
||||
|
||||
if get_rank() == 0:
|
||||
pbar.set_description(
|
||||
(
|
||||
f"iter: {i:d}; emse: {emse_loss_val:.3f}"
|
||||
)
|
||||
)
|
||||
|
||||
if ((i+1) >= args.save_begin and (i+1) % args.save_every == 0) or (i+1) == args.iter:
|
||||
if (i+1) == args.iter:
|
||||
savename = f"checkpoint/%s/pretrain.pt"%(args.name)
|
||||
else:
|
||||
savename = f"checkpoint/%s/pretrain-%05d.pt"%(args.name, i+1)
|
||||
torch.save(
|
||||
{
|
||||
#"g": g_module.encoder.state_dict(),
|
||||
"g_ema": g_ema.encoder.state_dict(),
|
||||
},
|
||||
savename,
|
||||
)
|
||||
|
||||
|
||||
# generate paired data and train vtoonify, see Sec. 4.1.2 for the detail
|
||||
def train(args, generator, discriminator, g_optim, d_optim, g_ema, percept, parsingpredictor, down, pspencoder, directions, basemodel, device):
|
||||
pbar = range(args.iter)
|
||||
|
||||
if get_rank() == 0:
|
||||
pbar = tqdm(pbar, initial=args.start_iter, smoothing=0.01, ncols=120, dynamic_ncols=False)
|
||||
|
||||
d_loss = torch.tensor(0.0, device=device)
|
||||
g_loss = torch.tensor(0.0, device=device)
|
||||
grec_loss = torch.tensor(0.0, device=device)
|
||||
gfeat_loss = torch.tensor(0.0, device=device)
|
||||
temporal_loss = torch.tensor(0.0, device=device)
|
||||
loss_dict = {}
|
||||
|
||||
if args.distributed:
|
||||
g_module = generator.module
|
||||
d_module = discriminator.module
|
||||
|
||||
else:
|
||||
g_module = generator
|
||||
d_module = discriminator
|
||||
|
||||
accum = 0.5 ** (32 / (10 * 1000))
|
||||
|
||||
for idx in pbar:
|
||||
i = idx + args.start_iter
|
||||
|
||||
if i > args.iter:
|
||||
print("Done!")
|
||||
break
|
||||
|
||||
###### This part is for data generation. Generate pair (x, y, w'') as in Fig. 5 of the paper
|
||||
with torch.no_grad():
|
||||
noise_sample = torch.randn(args.batch, 512).cuda()
|
||||
wc = basemodel.style(noise_sample).unsqueeze(1).repeat(1,18,1) # random w
|
||||
wc[:, 3:7] += directions[torch.randint(0, directions.shape[0], (args.batch,)), 3:7] # w'=w+n
|
||||
wc = wc.detach()
|
||||
xc, _ = basemodel([wc], input_is_latent=True, truncation=0.5, truncation_latent=0)
|
||||
xc = torch.clamp(xc, -1, 1).detach() # x'
|
||||
xl = pspencoder(F.adaptive_avg_pool2d(xc, 256))
|
||||
xl = basemodel.style(xl.reshape(xl.shape[0]*xl.shape[1], xl.shape[2])).reshape(xl.shape) # E_s(x'_down)
|
||||
xl = torch.cat((wc[:,0:7]*0.5, xl[:,7:18]), dim=1).detach() # w'' = concatenate w' and E_s(x'_down)
|
||||
xs, _ = g_ema.generator([xl], input_is_latent=True)
|
||||
xs = torch.clamp(xs, -1, 1).detach() # y'
|
||||
# during training, random geometric transformations are applied.
|
||||
imgs, _ = random_apply_affine(torch.cat((xc.detach(),xs), dim=1), 0.2, None)
|
||||
real_input1024 = imgs[:,0:3].detach() # image part of x
|
||||
real_input512 = down(real_input1024).detach()
|
||||
real_input256 = down(real_input512).detach()
|
||||
mask512 = parsingpredictor(2*real_input512)[0]
|
||||
mask256 = down(mask512).detach()
|
||||
mask = F.adaptive_avg_pool2d(mask512, 1024).detach() # parsing part of x
|
||||
real_output = imgs[:,3:].detach() # y
|
||||
real_input = torch.cat((real_input256, mask256/16.0), dim=1) # x_down
|
||||
# for log, sample a fixed input-output pair (x_down, y, w'')
|
||||
if idx == 0 or i == 0:
|
||||
samplein = real_input.clone().detach()
|
||||
sampleout = real_output.clone().detach()
|
||||
samplexl = xl.clone().detach()
|
||||
|
||||
###### This part is for training discriminator
|
||||
|
||||
requires_grad(g_module.encoder, False)
|
||||
requires_grad(g_module.fusion_out, False)
|
||||
requires_grad(g_module.fusion_skip, False)
|
||||
requires_grad(discriminator, True)
|
||||
|
||||
fake_output = generator(real_input, xl)
|
||||
fake_pred = discriminator(F.adaptive_avg_pool2d(fake_output, 256))
|
||||
real_pred = discriminator(F.adaptive_avg_pool2d(real_output, 256))
|
||||
|
||||
# L_adv in Eq.(3)
|
||||
d_loss = d_logistic_loss(real_pred, fake_pred) * args.adv_loss
|
||||
loss_dict["d"] = d_loss
|
||||
|
||||
discriminator.zero_grad()
|
||||
d_loss.backward()
|
||||
d_optim.step()
|
||||
|
||||
###### This part is for training generator (encoder and fusion modules)
|
||||
|
||||
requires_grad(g_module.encoder, True)
|
||||
requires_grad(g_module.fusion_out, True)
|
||||
requires_grad(g_module.fusion_skip, True)
|
||||
requires_grad(discriminator, False)
|
||||
|
||||
fake_output = generator(real_input, xl)
|
||||
fake_pred = discriminator(F.adaptive_avg_pool2d(fake_output, 256))
|
||||
# L_adv in Eq.(3)
|
||||
g_loss = g_nonsaturating_loss(fake_pred) * args.adv_loss
|
||||
# L_rec in Eq.(2)
|
||||
grec_loss = F.mse_loss(fake_output, real_output) * args.grec_loss
|
||||
gfeat_loss = percept(F.adaptive_avg_pool2d(fake_output, 512), # 1024 will out of memory
|
||||
F.adaptive_avg_pool2d(real_output, 512)).sum() * args.perc_loss # 256 will get blurry output
|
||||
|
||||
loss_dict["g"] = g_loss
|
||||
loss_dict["gr"] = grec_loss
|
||||
loss_dict["gf"] = gfeat_loss
|
||||
|
||||
w = random.randint(0,1024-896)
|
||||
h = random.randint(0,1024-896)
|
||||
crop_input = torch.cat((real_input1024[:,:,w:w+896,h:h+896], mask[:,:,w:w+896,h:h+896]/16.0), dim=1).detach()
|
||||
crop_input = down(down(crop_input))
|
||||
crop_fake_output = fake_output[:,:,w:w+896,h:h+896]
|
||||
fake_crop_output = generator(crop_input, xl)
|
||||
# L_tmp in Eq.(4), gradually increase the weight of L_tmp
|
||||
temporal_loss = ((fake_crop_output-crop_fake_output)**2).mean() * max(idx/(args.iter/2.0)-1, 0) * args.tmp_loss
|
||||
loss_dict["tp"] = temporal_loss
|
||||
|
||||
generator.zero_grad()
|
||||
(g_loss + grec_loss + gfeat_loss + temporal_loss).backward()
|
||||
g_optim.step()
|
||||
|
||||
accumulate(g_ema.encoder, g_module.encoder, accum)
|
||||
accumulate(g_ema.fusion_out, g_module.fusion_out, accum)
|
||||
accumulate(g_ema.fusion_skip, g_module.fusion_skip, accum)
|
||||
|
||||
loss_reduced = reduce_loss_dict(loss_dict)
|
||||
|
||||
d_loss_val = loss_reduced["d"].mean().item()
|
||||
g_loss_val = loss_reduced["g"].mean().item()
|
||||
gr_loss_val = loss_reduced["gr"].mean().item()
|
||||
gf_loss_val = loss_reduced["gf"].mean().item()
|
||||
tmp_loss_val = loss_reduced["tp"].mean().item()
|
||||
|
||||
if get_rank() == 0:
|
||||
pbar.set_description(
|
||||
(
|
||||
f"iter: {i:d}; advd: {d_loss_val:.3f}; advg: {g_loss_val:.3f}; mse: {gr_loss_val:.3f}; "
|
||||
f"perc: {gf_loss_val:.3f}; tmp: {tmp_loss_val:.3f}"
|
||||
)
|
||||
)
|
||||
|
||||
if i % args.log_every == 0 or (i+1) == args.iter:
|
||||
with torch.no_grad():
|
||||
g_ema.eval()
|
||||
sample = g_ema(samplein, samplexl)
|
||||
sample = F.interpolate(torch.cat((sampleout, sample), dim=0), 256)
|
||||
utils.save_image(
|
||||
sample,
|
||||
f"log/%s/%05d.jpg"%(args.name, i),
|
||||
nrow=int(args.batch),
|
||||
normalize=True,
|
||||
range=(-1, 1),
|
||||
)
|
||||
|
||||
if ((i+1) >= args.save_begin and (i+1) % args.save_every == 0) or (i+1) == args.iter:
|
||||
if (i+1) == args.iter:
|
||||
savename = f"checkpoint/%s/vtoonify.pt"%(args.name)
|
||||
else:
|
||||
savename = f"checkpoint/%s/vtoonify_%05d.pt"%(args.name, i+1)
|
||||
torch.save(
|
||||
{
|
||||
#"g": g_module.state_dict(),
|
||||
#"d": d_module.state_dict(),
|
||||
"g_ema": g_ema.state_dict(),
|
||||
},
|
||||
savename,
|
||||
)
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
device = "cuda"
|
||||
parser = TrainOptions()
|
||||
args = parser.parse()
|
||||
if args.local_rank == 0:
|
||||
print('*'*98)
|
||||
if not os.path.exists("log/%s/"%(args.name)):
|
||||
os.makedirs("log/%s/"%(args.name))
|
||||
if not os.path.exists("checkpoint/%s/"%(args.name)):
|
||||
os.makedirs("checkpoint/%s/"%(args.name))
|
||||
|
||||
n_gpu = int(os.environ["WORLD_SIZE"]) if "WORLD_SIZE" in os.environ else 1
|
||||
args.distributed = n_gpu > 1
|
||||
|
||||
if args.distributed:
|
||||
torch.cuda.set_device(args.local_rank)
|
||||
torch.distributed.init_process_group(backend="nccl", init_method="env://")
|
||||
synchronize()
|
||||
|
||||
generator = VToonify(backbone = 'toonify').to(device)
|
||||
generator.apply(weights_init)
|
||||
g_ema = VToonify(backbone = 'toonify').to(device)
|
||||
g_ema.eval()
|
||||
|
||||
basemodel = Generator(1024, 512, 8, 2).to(device) # G0
|
||||
finetunemodel = Generator(1024, 512, 8, 2).to(device)
|
||||
basemodel.load_state_dict(torch.load(args.stylegan_path, map_location=lambda storage, loc: storage)['g_ema'])
|
||||
finetunemodel.load_state_dict(torch.load(args.finetunegan_path, map_location=lambda storage, loc: storage)['g_ema'])
|
||||
fused_state_dict = blend_models(finetunemodel, basemodel, args.weight) # G1
|
||||
generator.generator.load_state_dict(fused_state_dict) # load G1
|
||||
g_ema.generator.load_state_dict(fused_state_dict)
|
||||
requires_grad(basemodel, False)
|
||||
requires_grad(generator.generator, False)
|
||||
requires_grad(g_ema.generator, False)
|
||||
|
||||
if not args.pretrain:
|
||||
generator.encoder.load_state_dict(torch.load(args.encoder_path, map_location=lambda storage, loc: storage)["g_ema"])
|
||||
# we initialize the fusion modules to map f_G \otimes f_E to f_G.
|
||||
for k in generator.fusion_out:
|
||||
k.weight.data *= 0.01
|
||||
k.weight[:,0:k.weight.shape[0],1,1].data += torch.eye(k.weight.shape[0]).cuda()
|
||||
for k in generator.fusion_skip:
|
||||
k.weight.data *= 0.01
|
||||
k.weight[:,0:k.weight.shape[0],1,1].data += torch.eye(k.weight.shape[0]).cuda()
|
||||
|
||||
accumulate(g_ema.encoder, generator.encoder, 0)
|
||||
accumulate(g_ema.fusion_out, generator.fusion_out, 0)
|
||||
accumulate(g_ema.fusion_skip, generator.fusion_skip, 0)
|
||||
|
||||
g_parameters = list(generator.encoder.parameters())
|
||||
if not args.pretrain:
|
||||
g_parameters = g_parameters + list(generator.fusion_out.parameters()) + list(generator.fusion_skip.parameters())
|
||||
|
||||
g_optim = optim.Adam(
|
||||
g_parameters,
|
||||
lr=args.lr,
|
||||
betas=(0.9, 0.99),
|
||||
)
|
||||
|
||||
if args.distributed:
|
||||
generator = nn.parallel.DistributedDataParallel(
|
||||
generator,
|
||||
device_ids=[args.local_rank],
|
||||
output_device=args.local_rank,
|
||||
broadcast_buffers=False,
|
||||
find_unused_parameters=True,
|
||||
)
|
||||
|
||||
parsingpredictor = BiSeNet(n_classes=19)
|
||||
parsingpredictor.load_state_dict(torch.load(args.faceparsing_path, map_location=lambda storage, loc: storage))
|
||||
parsingpredictor.to(device).eval()
|
||||
requires_grad(parsingpredictor, False)
|
||||
|
||||
# we apply gaussian blur to the images to avoid flickers caused during downsampling
|
||||
down = Downsample(kernel=[1, 3, 3, 1], factor=2).to(device)
|
||||
requires_grad(down, False)
|
||||
|
||||
directions = torch.tensor(np.load(args.direction_path)).to(device)
|
||||
|
||||
if not args.pretrain:
|
||||
discriminator = ConditionalDiscriminator(256).to(device)
|
||||
|
||||
d_optim = optim.Adam(
|
||||
discriminator.parameters(),
|
||||
lr=args.lr,
|
||||
betas=(0.9, 0.99),
|
||||
)
|
||||
|
||||
if args.distributed:
|
||||
discriminator = nn.parallel.DistributedDataParallel(
|
||||
discriminator,
|
||||
device_ids=[args.local_rank],
|
||||
output_device=args.local_rank,
|
||||
broadcast_buffers=False,
|
||||
find_unused_parameters=True,
|
||||
)
|
||||
|
||||
percept = lpips.PerceptualLoss(model="net-lin", net="vgg", use_gpu=device.startswith("cuda"), gpu_ids=[args.local_rank])
|
||||
requires_grad(percept.model.net, False)
|
||||
|
||||
pspencoder = load_psp_standalone(args.style_encoder_path, device)
|
||||
|
||||
if args.local_rank == 0:
|
||||
print('Load models and data successfully loaded!')
|
||||
|
||||
if args.pretrain:
|
||||
pretrain(args, generator, g_optim, g_ema, parsingpredictor, down, directions, basemodel, device)
|
||||
else:
|
||||
train(args, generator, discriminator, g_optim, d_optim, g_ema, percept, parsingpredictor, down, pspencoder, directions, basemodel, device)
|
||||
@@ -0,0 +1,229 @@
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from PIL import Image
|
||||
import cv2
|
||||
import random
|
||||
import math
|
||||
import argparse
|
||||
import torch
|
||||
from torch.utils import data
|
||||
from torch.nn import functional as F
|
||||
from torch import autograd
|
||||
from torch.nn import init
|
||||
import torchvision.transforms as transforms
|
||||
from model.stylegan.op_cpu import conv2d_gradfix
|
||||
from model.encoder.encoders.psp_encoders import GradualStyleEncoder
|
||||
from model.encoder.align_all_parallel import get_landmark
|
||||
|
||||
def visualize(img_arr, dpi):
|
||||
plt.figure(figsize=(10,10),dpi=dpi)
|
||||
plt.imshow(((img_arr.detach().cpu().numpy().transpose(1, 2, 0) + 1.0) * 127.5).astype(np.uint8))
|
||||
plt.axis('off')
|
||||
plt.show()
|
||||
|
||||
def save_image(img, filename):
|
||||
tmp = ((img.detach().cpu().numpy().transpose(1, 2, 0) + 1.0) * 127.5).astype(np.uint8)
|
||||
cv2.imwrite(filename, cv2.cvtColor(tmp, cv2.COLOR_RGB2BGR))
|
||||
|
||||
def load_image(filename):
|
||||
transform = transforms.Compose([
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5,0.5,0.5]),
|
||||
])
|
||||
|
||||
img = Image.open(filename)
|
||||
img = transform(img)
|
||||
return img.unsqueeze(dim=0)
|
||||
|
||||
def data_sampler(dataset, shuffle, distributed):
|
||||
if distributed:
|
||||
return data.distributed.DistributedSampler(dataset, shuffle=shuffle)
|
||||
|
||||
if shuffle:
|
||||
return data.RandomSampler(dataset)
|
||||
|
||||
else:
|
||||
return data.SequentialSampler(dataset)
|
||||
|
||||
|
||||
def requires_grad(model, flag=True):
|
||||
for p in model.parameters():
|
||||
p.requires_grad = flag
|
||||
|
||||
|
||||
def accumulate(model1, model2, decay=0.999):
|
||||
par1 = dict(model1.named_parameters())
|
||||
par2 = dict(model2.named_parameters())
|
||||
|
||||
for k in par1.keys():
|
||||
par1[k].data.mul_(decay).add_(par2[k].data, alpha=1 - decay)
|
||||
|
||||
|
||||
def sample_data(loader):
|
||||
while True:
|
||||
for batch in loader:
|
||||
yield batch
|
||||
|
||||
|
||||
def d_logistic_loss(real_pred, fake_pred):
|
||||
real_loss = F.softplus(-real_pred)
|
||||
fake_loss = F.softplus(fake_pred)
|
||||
|
||||
return real_loss.mean() + fake_loss.mean()
|
||||
|
||||
|
||||
def d_r1_loss(real_pred, real_img):
|
||||
with conv2d_gradfix.no_weight_gradients():
|
||||
grad_real, = autograd.grad(
|
||||
outputs=real_pred.sum(), inputs=real_img, create_graph=True
|
||||
)
|
||||
grad_penalty = grad_real.pow(2).reshape(grad_real.shape[0], -1).sum(1).mean()
|
||||
|
||||
return grad_penalty
|
||||
|
||||
|
||||
def g_nonsaturating_loss(fake_pred):
|
||||
loss = F.softplus(-fake_pred).mean()
|
||||
|
||||
return loss
|
||||
|
||||
|
||||
def g_path_regularize(fake_img, latents, mean_path_length, decay=0.01):
|
||||
noise = torch.randn_like(fake_img) / math.sqrt(
|
||||
fake_img.shape[2] * fake_img.shape[3]
|
||||
)
|
||||
grad, = autograd.grad(
|
||||
outputs=(fake_img * noise).sum(), inputs=latents, create_graph=True
|
||||
)
|
||||
path_lengths = torch.sqrt(grad.pow(2).sum(2).mean(1))
|
||||
|
||||
path_mean = mean_path_length + decay * (path_lengths.mean() - mean_path_length)
|
||||
|
||||
path_penalty = (path_lengths - path_mean).pow(2).mean()
|
||||
|
||||
return path_penalty, path_mean.detach(), path_lengths
|
||||
|
||||
|
||||
def make_noise(batch, latent_dim, n_noise, device):
|
||||
if n_noise == 1:
|
||||
return torch.randn(batch, latent_dim, device=device)
|
||||
|
||||
noises = torch.randn(n_noise, batch, latent_dim, device=device).unbind(0)
|
||||
|
||||
return noises
|
||||
|
||||
|
||||
def mixing_noise(batch, latent_dim, prob, device):
|
||||
if prob > 0 and random.random() < prob:
|
||||
return make_noise(batch, latent_dim, 2, device)
|
||||
|
||||
else:
|
||||
return [make_noise(batch, latent_dim, 1, device)]
|
||||
|
||||
|
||||
def set_grad_none(model, targets):
|
||||
for n, p in model.named_parameters():
|
||||
if n in targets:
|
||||
p.grad = None
|
||||
|
||||
|
||||
def weights_init(m):
|
||||
classname = m.__class__.__name__
|
||||
if classname.find('BatchNorm2d') != -1:
|
||||
if hasattr(m, 'weight') and m.weight is not None:
|
||||
init.normal_(m.weight.data, 1.0, 0.02)
|
||||
if hasattr(m, 'bias') and m.bias is not None:
|
||||
init.constant_(m.bias.data, 0.0)
|
||||
elif hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
|
||||
init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
|
||||
if hasattr(m, 'bias') and m.bias is not None:
|
||||
init.constant_(m.bias.data, 0.0)
|
||||
|
||||
|
||||
def load_psp_standalone(checkpoint_path, device='cuda'):
|
||||
ckpt = torch.load(checkpoint_path, map_location='cpu')
|
||||
opts = ckpt['opts']
|
||||
if 'output_size' not in opts:
|
||||
opts['output_size'] = 1024
|
||||
opts['n_styles'] = int(math.log(opts['output_size'], 2)) * 2 - 2
|
||||
opts = argparse.Namespace(**opts)
|
||||
psp = GradualStyleEncoder(50, 'ir_se', opts)
|
||||
psp_dict = {k.replace('encoder.', ''): v for k, v in ckpt['state_dict'].items() if k.startswith('encoder.')}
|
||||
psp.load_state_dict(psp_dict)
|
||||
psp.eval()
|
||||
psp = psp.to(device)
|
||||
latent_avg = ckpt['latent_avg'].to(device)
|
||||
|
||||
def add_latent_avg(model, inputs, outputs):
|
||||
return outputs + latent_avg.repeat(outputs.shape[0], 1, 1)
|
||||
|
||||
psp.register_forward_hook(add_latent_avg)
|
||||
return psp
|
||||
|
||||
def get_video_crop_parameter(filepath, predictor, padding=[200,200,200,200]):
|
||||
if type(filepath) == str:
|
||||
img = dlib.load_rgb_image(filepath)
|
||||
else:
|
||||
img = filepath
|
||||
lm = get_landmark(img, predictor)
|
||||
if lm is None:
|
||||
return None
|
||||
lm_chin = lm[0 : 17] # left-right
|
||||
lm_eyebrow_left = lm[17 : 22] # left-right
|
||||
lm_eyebrow_right = lm[22 : 27] # left-right
|
||||
lm_nose = lm[27 : 31] # top-down
|
||||
lm_nostrils = lm[31 : 36] # top-down
|
||||
lm_eye_left = lm[36 : 42] # left-clockwise
|
||||
lm_eye_right = lm[42 : 48] # left-clockwise
|
||||
lm_mouth_outer = lm[48 : 60] # left-clockwise
|
||||
lm_mouth_inner = lm[60 : 68] # left-clockwise
|
||||
|
||||
scale = 64. / (np.mean(lm_eye_right[:,0])-np.mean(lm_eye_left[:,0]))
|
||||
center = ((np.mean(lm_eye_right, axis=0)+np.mean(lm_eye_left, axis=0)) / 2) * scale
|
||||
h, w = round(img.shape[0] * scale), round(img.shape[1] * scale)
|
||||
left = max(round(center[0] - padding[0]), 0) // 8 * 8
|
||||
right = min(round(center[0] + padding[1]), w) // 8 * 8
|
||||
top = max(round(center[1] - padding[2]), 0) // 8 * 8
|
||||
bottom = min(round(center[1] + padding[3]), h) // 8 * 8
|
||||
return h,w,top,bottom,left,right,scale
|
||||
|
||||
def tensor2cv2(img):
|
||||
tmp = ((img.cpu().numpy().transpose(1, 2, 0) + 1.0) * 127.5).astype(np.uint8)
|
||||
return cv2.cvtColor(tmp, cv2.COLOR_RGB2BGR)
|
||||
|
||||
# get parameters from the stylegan and mark them with their layers
|
||||
def gather_params(G):
|
||||
params = dict(
|
||||
[(res, {}) for res in range(18)] + [("others", {})]
|
||||
)
|
||||
for n, p in sorted(list(G.named_buffers()) + list(G.named_parameters())):
|
||||
if n.startswith("convs"):
|
||||
layer = int(n.split(".")[1]) + 1
|
||||
params[layer][n] = p
|
||||
elif n.startswith("to_rgbs"):
|
||||
layer = int(n.split(".")[1]) * 2 + 3
|
||||
params[layer][n] = p
|
||||
elif n.startswith("conv1"):
|
||||
params[0][n] = p
|
||||
elif n.startswith("to_rgb1"):
|
||||
params[1][n] = p
|
||||
else:
|
||||
params["others"][n] = p
|
||||
return params
|
||||
|
||||
# blend the ffhq stylegan model and the finetuned model for toonify
|
||||
# see ``Resolution Dependent GAN Interpolation for Controllable Image Synthesis Between Domains''
|
||||
def blend_models(G_low, G_high, weight=[1]*7+[0]*11):
|
||||
params_low = gather_params(G_low)
|
||||
params_high = gather_params(G_high)
|
||||
|
||||
for res in range(18):
|
||||
for n, p in params_high[res].items():
|
||||
params_high[res][n] = params_high[res][n] * (1-weight[res]) + params_low[res][n] * weight[res]
|
||||
|
||||
state_dict = {}
|
||||
for _, p in params_high.items():
|
||||
state_dict.update(p)
|
||||
|
||||
return state_dict
|
||||
|
||||
@@ -0,0 +1,280 @@
|
||||
# this code is for web demo in colab notebook
|
||||
|
||||
from __future__ import annotations
|
||||
import gradio as gr
|
||||
import pathlib
|
||||
import sys
|
||||
|
||||
from util import load_psp_standalone, get_video_crop_parameter, tensor2cv2
|
||||
import torch
|
||||
import torch.nn as nn
|
||||
import numpy as np
|
||||
import dlib
|
||||
import cv2
|
||||
from model.vtoonify import VToonify
|
||||
from model.bisenet.model import BiSeNet
|
||||
import torch.nn.functional as F
|
||||
from torchvision import transforms
|
||||
from model.encoder.align_all_parallel import align_face
|
||||
import gc
|
||||
import huggingface_hub
|
||||
import os
|
||||
|
||||
MODEL_REPO = 'PKUWilliamYang/VToonify'
|
||||
|
||||
class Model():
|
||||
def __init__(self, device):
|
||||
super().__init__()
|
||||
|
||||
self.device = device
|
||||
self.style_types = {
|
||||
'cartoon1': ['vtoonify_d_cartoon/vtoonify_s026_d0.5.pt', 26],
|
||||
'cartoon1-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 26],
|
||||
'cartoon2-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 64],
|
||||
'cartoon3-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 153],
|
||||
'cartoon4': ['vtoonify_d_cartoon/vtoonify_s299_d0.5.pt', 299],
|
||||
'cartoon4-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 299],
|
||||
'cartoon5-d': ['vtoonify_d_cartoon/vtoonify_s_d.pt', 8],
|
||||
'comic1-d': ['vtoonify_d_comic/vtoonify_s_d.pt', 28],
|
||||
'comic2-d': ['vtoonify_d_comic/vtoonify_s_d.pt', 18],
|
||||
'arcane1': ['vtoonify_d_arcane/vtoonify_s000_d0.5.pt', 0],
|
||||
'arcane1-d': ['vtoonify_d_arcane/vtoonify_s_d.pt', 0],
|
||||
'arcane2': ['vtoonify_d_arcane/vtoonify_s077_d0.5.pt', 77],
|
||||
'arcane2-d': ['vtoonify_d_arcane/vtoonify_s_d.pt', 77],
|
||||
'caricature1': ['vtoonify_d_caricature/vtoonify_s039_d0.5.pt', 39],
|
||||
'caricature2': ['vtoonify_d_caricature/vtoonify_s068_d0.5.pt', 68],
|
||||
'pixar': ['vtoonify_d_pixar/vtoonify_s052_d0.5.pt', 52],
|
||||
'pixar-d': ['vtoonify_d_pixar/vtoonify_s_d.pt', 52],
|
||||
'illustration1-d': ['vtoonify_d_illustration/vtoonify_s054_d_c.pt', 54],
|
||||
'illustration2-d': ['vtoonify_d_illustration/vtoonify_s004_d_c.pt', 4],
|
||||
'illustration3-d': ['vtoonify_d_illustration/vtoonify_s009_d_c.pt', 9],
|
||||
'illustration4-d': ['vtoonify_d_illustration/vtoonify_s043_d_c.pt', 43],
|
||||
'illustration5-d': ['vtoonify_d_illustration/vtoonify_s086_d_c.pt', 86],
|
||||
}
|
||||
|
||||
self.landmarkpredictor = self._create_dlib_landmark_model()
|
||||
self.parsingpredictor = self._create_parsing_model()
|
||||
self.pspencoder = self._load_encoder()
|
||||
self.transform = transforms.Compose([
|
||||
transforms.ToTensor(),
|
||||
transforms.Normalize(mean=[0.5, 0.5, 0.5],std=[0.5,0.5,0.5]),
|
||||
])
|
||||
|
||||
self.vtoonify, self.exstyle = self._load_default_model()
|
||||
self.color_transfer = False
|
||||
self.style_name = 'cartoon1'
|
||||
self.video_limit_cpu = 100
|
||||
self.video_limit_gpu = 300
|
||||
|
||||
@staticmethod
|
||||
def _create_dlib_landmark_model():
|
||||
return dlib.shape_predictor(huggingface_hub.hf_hub_download(MODEL_REPO,
|
||||
'models/shape_predictor_68_face_landmarks.dat'))
|
||||
|
||||
def _create_parsing_model(self):
|
||||
parsingpredictor = BiSeNet(n_classes=19)
|
||||
parsingpredictor.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO, 'models/faceparsing.pth'),
|
||||
map_location=lambda storage, loc: storage))
|
||||
parsingpredictor.to(self.device).eval()
|
||||
return parsingpredictor
|
||||
|
||||
def _load_encoder(self) -> nn.Module:
|
||||
style_encoder_path = huggingface_hub.hf_hub_download(MODEL_REPO,'models/encoder.pt')
|
||||
return load_psp_standalone(style_encoder_path, self.device)
|
||||
|
||||
def _load_default_model(self) -> tuple[torch.Tensor, str]:
|
||||
vtoonify = VToonify(backbone = 'dualstylegan')
|
||||
vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,
|
||||
'models/vtoonify_d_cartoon/vtoonify_s026_d0.5.pt'),
|
||||
map_location=lambda storage, loc: storage)['g_ema'])
|
||||
vtoonify.to(self.device)
|
||||
tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO,'models/vtoonify_d_cartoon/exstyle_code.npy'), allow_pickle=True).item()
|
||||
exstyle = torch.tensor(tmp[list(tmp.keys())[26]]).to(self.device)
|
||||
with torch.no_grad():
|
||||
exstyle = vtoonify.zplus2wplus(exstyle)
|
||||
return vtoonify, exstyle
|
||||
|
||||
def load_model(self, style_type: str) -> tuple[torch.Tensor, str]:
|
||||
if 'illustration' in style_type:
|
||||
self.color_transfer = True
|
||||
else:
|
||||
self.color_transfer = False
|
||||
if style_type not in self.style_types.keys():
|
||||
return None, 'Oops, wrong Style Type. Please select a valid model.'
|
||||
self.style_name = style_type
|
||||
model_path, ind = self.style_types[style_type]
|
||||
style_path = os.path.join('models',os.path.dirname(model_path),'exstyle_code.npy')
|
||||
self.vtoonify.load_state_dict(torch.load(huggingface_hub.hf_hub_download(MODEL_REPO,'models/'+model_path),
|
||||
map_location=lambda storage, loc: storage)['g_ema'])
|
||||
tmp = np.load(huggingface_hub.hf_hub_download(MODEL_REPO, style_path), allow_pickle=True).item()
|
||||
exstyle = torch.tensor(tmp[list(tmp.keys())[ind]]).to(self.device)
|
||||
with torch.no_grad():
|
||||
exstyle = self.vtoonify.zplus2wplus(exstyle)
|
||||
return exstyle, 'Model of %s loaded.'%(style_type)
|
||||
|
||||
def detect_and_align(self, frame, top, bottom, left, right, return_para=False):
|
||||
message = 'Error: no face detected! Please retry or change the photo.'
|
||||
paras = get_video_crop_parameter(frame, self.landmarkpredictor, [left, right, top, bottom])
|
||||
instyle = None
|
||||
h, w, scale = 0, 0, 0
|
||||
if paras is not None:
|
||||
h,w,top,bottom,left,right,scale = paras
|
||||
H, W = int(bottom-top), int(right-left)
|
||||
# for HR image, we apply gaussian blur to it to avoid over-sharp stylization results
|
||||
kernel_1d = np.array([[0.125],[0.375],[0.375],[0.125]])
|
||||
if scale <= 0.75:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
if scale <= 0.375:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
|
||||
with torch.no_grad():
|
||||
I = align_face(frame, self.landmarkpredictor)
|
||||
if I is not None:
|
||||
I = self.transform(I).unsqueeze(dim=0).to(self.device)
|
||||
instyle = self.pspencoder(I)
|
||||
instyle = self.vtoonify.zplus2wplus(instyle)
|
||||
message = 'Successfully rescale the frame to (%d, %d)'%(bottom-top, right-left)
|
||||
else:
|
||||
frame = np.zeros((256,256,3), np.uint8)
|
||||
else:
|
||||
frame = np.zeros((256,256,3), np.uint8)
|
||||
if return_para:
|
||||
return frame, instyle, message, w, h, top, bottom, left, right, scale
|
||||
return frame, instyle, message
|
||||
|
||||
#@torch.inference_mode()
|
||||
def detect_and_align_image(self, image: str, top: int, bottom: int, left: int, right: int
|
||||
) -> tuple[np.ndarray, torch.Tensor, str]:
|
||||
if image is None:
|
||||
return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load empty file.'
|
||||
frame = cv2.imread(image)
|
||||
if frame is None:
|
||||
return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load the image.'
|
||||
frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)
|
||||
return self.detect_and_align(frame, top, bottom, left, right)
|
||||
|
||||
def detect_and_align_video(self, video: str, top: int, bottom: int, left: int, right: int
|
||||
) -> tuple[np.ndarray, torch.Tensor, str]:
|
||||
if video is None:
|
||||
return np.zeros((256,256,3), np.uint8), None, 'Error: fail to load empty file.'
|
||||
video_cap = cv2.VideoCapture(video)
|
||||
if video_cap.get(7) == 0:
|
||||
video_cap.release()
|
||||
return np.zeros((256,256,3), np.uint8), torch.zeros(1,18,512).to(self.device), 'Error: fail to load the video.'
|
||||
success, frame = video_cap.read()
|
||||
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||
video_cap.release()
|
||||
return self.detect_and_align(frame, top, bottom, left, right)
|
||||
|
||||
def detect_and_align_full_video(self, video: str, top: int, bottom: int, left: int, right: int) -> tuple[str, torch.Tensor, str]:
|
||||
message = 'Error: no face detected! Please retry or change the video.'
|
||||
instyle = None
|
||||
if video is None:
|
||||
return 'default.mp4', instyle, 'Error: fail to load empty file.'
|
||||
video_cap = cv2.VideoCapture(video)
|
||||
if video_cap.get(7) == 0:
|
||||
video_cap.release()
|
||||
return 'default.mp4', instyle, 'Error: fail to load the video.'
|
||||
num = min(self.video_limit_gpu, int(video_cap.get(7)))
|
||||
if self.device == 'cpu':
|
||||
num = min(self.video_limit_cpu, num)
|
||||
success, frame = video_cap.read()
|
||||
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||
frame, instyle, message, w, h, top, bottom, left, right, scale = self.detect_and_align(frame, top, bottom, left, right, True)
|
||||
if instyle is None:
|
||||
return 'default.mp4', instyle, message
|
||||
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
||||
videoWriter = cv2.VideoWriter('input.mp4', fourcc, video_cap.get(5), (int(right-left), int(bottom-top)))
|
||||
videoWriter.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
|
||||
kernel_1d = np.array([[0.125],[0.375],[0.375],[0.125]])
|
||||
for i in range(num-1):
|
||||
success, frame = video_cap.read()
|
||||
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||
if scale <= 0.75:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
if scale <= 0.375:
|
||||
frame = cv2.sepFilter2D(frame, -1, kernel_1d, kernel_1d)
|
||||
frame = cv2.resize(frame, (w, h))[top:bottom, left:right]
|
||||
videoWriter.write(cv2.cvtColor(frame, cv2.COLOR_RGB2BGR))
|
||||
|
||||
videoWriter.release()
|
||||
video_cap.release()
|
||||
|
||||
return 'input.mp4', instyle, 'Successfully rescale the video to (%d, %d)'%(bottom-top, right-left)
|
||||
|
||||
def image_toonify(self, aligned_face: np.ndarray, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float) -> tuple[np.ndarray, str]:
|
||||
if instyle is None or aligned_face is None:
|
||||
return np.zeros((256,256,3), np.uint8), 'Opps, something wrong with the input. Please go to Step 2 and Rescale Image/First Frame again.'
|
||||
if exstyle is None:
|
||||
return np.zeros((256,256,3), np.uint8), 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
|
||||
if exstyle is None:
|
||||
exstyle = self.exstyle
|
||||
with torch.no_grad():
|
||||
if self.color_transfer:
|
||||
s_w = exstyle
|
||||
else:
|
||||
s_w = instyle.clone()
|
||||
s_w[:,:7] = exstyle[:,:7]
|
||||
|
||||
x = self.transform(aligned_face).unsqueeze(dim=0).to(self.device)
|
||||
x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
|
||||
scale_factor=0.5, recompute_scale_factor=False).detach()
|
||||
inputs = torch.cat((x, x_p/16.), dim=1)
|
||||
y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), d_s = style_degree)
|
||||
y_tilde = torch.clamp(y_tilde, -1, 1)
|
||||
print('*** Toonify %dx%d image'%(y_tilde.shape[2], y_tilde.shape[3]))
|
||||
return ((y_tilde[0].cpu().numpy().transpose(1, 2, 0) + 1.0) * 127.5).astype(np.uint8), 'Successfully toonify the image with style of %s'%(self.style_name)
|
||||
|
||||
def video_tooniy(self, aligned_video: str, instyle: torch.Tensor, exstyle: torch.Tensor, style_degree: float) -> tuple[str, str]:
|
||||
if aligned_video is None:
|
||||
return 'default.mp4', 'Opps, something wrong with the input. Please go to Step 2 and Rescale Video again.'
|
||||
video_cap = cv2.VideoCapture(aligned_video)
|
||||
if instyle is None or aligned_video is None or video_cap.get(7) == 0:
|
||||
video_cap.release()
|
||||
return 'default.mp4', 'Opps, something wrong with the input. Please go to Step 2 and Rescale Video again.'
|
||||
if exstyle is None:
|
||||
return 'default.mp4', 'Opps, something wrong with the style type. Please go to Step 1 and load model again.'
|
||||
num = min(self.video_limit_gpu, int(video_cap.get(7)))
|
||||
if self.device == 'cpu':
|
||||
num = min(self.video_limit_cpu, num)
|
||||
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
|
||||
videoWriter = cv2.VideoWriter('output.mp4', fourcc,
|
||||
video_cap.get(5), (int(video_cap.get(3)*4),
|
||||
int(video_cap.get(4)*4)))
|
||||
|
||||
batch_frames = []
|
||||
if video_cap.get(3) != 0:
|
||||
if self.device == 'cpu':
|
||||
batch_size = max(1, int(4 * 256* 256/ video_cap.get(3) / video_cap.get(4)))
|
||||
else:
|
||||
batch_size = min(max(1, int(4 * 400 * 360/ video_cap.get(3) / video_cap.get(4))), 4)
|
||||
else:
|
||||
batch_size = 1
|
||||
print('*** Toonify using batch size of %d on %dx%d video of %d frames'%(batch_size, int(video_cap.get(3)*4), int(video_cap.get(4)*4), num))
|
||||
with torch.no_grad():
|
||||
if self.color_transfer:
|
||||
s_w = exstyle
|
||||
else:
|
||||
s_w = instyle.clone()
|
||||
s_w[:,:7] = exstyle[:,:7]
|
||||
for i in range(num):
|
||||
success, frame = video_cap.read()
|
||||
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
||||
batch_frames += [self.transform(frame).unsqueeze(dim=0).to(self.device)]
|
||||
if len(batch_frames) == batch_size or (i+1) == num:
|
||||
x = torch.cat(batch_frames, dim=0)
|
||||
batch_frames = []
|
||||
with torch.no_grad():
|
||||
x_p = F.interpolate(self.parsingpredictor(2*(F.interpolate(x, scale_factor=2, mode='bilinear', align_corners=False)))[0],
|
||||
scale_factor=0.5, recompute_scale_factor=False).detach()
|
||||
inputs = torch.cat((x, x_p/16.), dim=1)
|
||||
y_tilde = self.vtoonify(inputs, s_w.repeat(inputs.size(0), 1, 1), style_degree)
|
||||
y_tilde = torch.clamp(y_tilde, -1, 1)
|
||||
for k in range(y_tilde.size(0)):
|
||||
videoWriter.write(tensor2cv2(y_tilde[k].cpu()))
|
||||
gc.collect()
|
||||
|
||||
videoWriter.release()
|
||||
video_cap.release()
|
||||
return 'output.mp4', 'Successfully toonify video of %d frames with style of %s'%(num, self.style_name)
|
||||
|
||||
Reference in New Issue
Block a user